From 4b4a7049a0bd49c078b4cc50f38c578db6341e4e Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 18 Nov 2026 16:06:34 +0800 Subject: [PATCH] =?UTF-8?q?feat(bill):=20=E6=94=AF=E6=8C=81=E6=9C=AA?= =?UTF-8?q?=E6=8F=90=E4=BA=A4=E8=8D=89=E7=A8=BF=E6=9F=A5=E8=AF=A2=E4=B8=8E?= =?UTF-8?q?=20flowId=20=E7=9B=B4=E8=AF=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- skills/hose-use/SKILL.md | 5 +- skills/hose-use/references/bill.md | 15 +- specs/hose-open-api/paths/bill.yaml | 29 +++- specs/openapi.json | 39 ++++- src/cli/command-metadata.ts | 5 +- src/cli/commands/bill/list-draft.test.ts | 106 +++++++++++++ src/cli/commands/bill/search.ts | 99 ++++++++++--- src/domains/bill/README.bill.md | 5 + src/domains/bill/api.ts | 95 ++++++++++++ src/domains/bill/bill.test.ts | 180 +++++++++++++++++++++++ src/domains/bill/tools.ts | 158 +++++++++++++++++++- src/domains/bill/types.ts | 16 ++ 12 files changed, 716 insertions(+), 36 deletions(-) create mode 100644 src/cli/commands/bill/list-draft.test.ts diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index a420d29..188f775 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -116,7 +116,7 @@ metadata: | OpenAPI 密钥持久化接入 / 从链接提取密钥 | `hose-use corps add-persistent`, `hose-use corps extract-keys ` | [references/auth.md](./references/auth.md) | | 代客协助凭证导入 / 探针连通性诊断 | `hose-use auth import`, `hose-use probe` | [references/auth.md](./references/auth.md) | | 企业租户切换 / 查看当前企业 | `hose-use corps list`, `hose-use corps switch ` | [references/auth.md](./references/auth.md) | -| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list [--since=7d] [--code=<单号>]`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](./references/bill.md) | +| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list [--since=7d] [--code=<单号>] [--state=draft]`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](./references/bill.md) | | 单据审批动作(同意/驳回/转交/加签/评论) | `hose-use bill approve|reject|transfer|add-node|comment <单号|ID> --yes` | [references/bill.md](./references/bill.md) | | 单据审批历史 / 当前节点 / 后续流程 | `hose-use bill flow <单号|ID>` | [references/bill.md](./references/bill.md) | | 单据风控预警 / 预算状态 / 发票风险 | `hose-use bill risk <单号|ID>` | [references/bill.md](./references/bill.md) | @@ -191,7 +191,10 @@ hose-use bill list --keyword=打车 # 单据关键字跨 hose-use bill list --keyword=打车 --search-fields=name,form # 自定义匹配字段 (支持 name,code,form 等) hose-use bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接 hose-use bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘 +hose-use bill list --state=draft --json # 查询我发起的未提交草稿(flows/my 数据源) +hose-use bill list --state=draft --template=<模板ID> --title=付款 --staff=张三 --page=1 # 草稿模板/标题/提交人过滤 hose-use bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射) +hose-use bill get <单号|flowId> # 草稿也支持按 flowId 直读(工作流 Job 输出) hose-use bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照 hose-use bill approve S26000001 --yes # 同意当前待办 hose-use bill reject S26000001 --comment "金额不符" --yes # 驳回并写明原因 diff --git a/skills/hose-use/references/bill.md b/skills/hose-use/references/bill.md index b85b098..69ef882 100644 --- a/skills/hose-use/references/bill.md +++ b/skills/hose-use/references/bill.md @@ -22,9 +22,10 @@ hose-use bill list --corp=uzU7pcWfScck00 --json - `--since=` / `-d`: 相对时间范围(如 `7d`、`30d`、`90d`、`1y`),大租户海量单据下强烈推荐以避免全量超时; - `--start-date=` / `--end-date=`: 起止日期过滤(支持 `YYYY-MM-DD` 或毫秒时间戳); - `--stage=`: 业务阶段过滤(如 `expense` 报销, `loan` 借款, `payment` 付款); -- `--state=` / `-s`: 审批与支付状态过滤(如 `paid` 已支付, `approving` 审批中, `draft` 草稿); +- `--state=` / `-s`: 审批与支付状态过滤(如 `paid` 已支付, `approving` 审批中)。`--state=draft`(或 `草稿`)使用专用草稿列表:草稿尚未进入台账索引,数据源为「我发起」的 `flows/my`; +- 草稿专用过滤:`--template=<模板ID>`、`--title=<标题关键字>`、`--staff=<姓名|工号|员工ID>`、`--page=<页码>`(与 `--count` 配合分页); - `--count=` / `--limit` / `-n`: 单页拉取数量(默认 20); -- `--mine`: 快捷查询当前登录人提交的单据(自动桥接至 `task submitted`); +- `--mine`: 快捷查询当前登录人提交的单据(自动桥接至 `task submitted`;`--state=draft` 时仍走草稿列表); - `--select=`: 按需指定返回字段(逗号分隔,如 `id,code,name,createTime,form`); - `--distinct`: 是否对单据记录去重。 @@ -40,8 +41,18 @@ hose-use bill list --code=CL20260901001 # 查询近 30 天已支付的报销单 hose-use bill list --since=30d --stage=expense --state=paid --limit=50 + +# 查询我发起的未提交草稿(支持模板、标题、提交人与分页过滤) +hose-use bill list --state=draft +hose-use bill list --state=draft --template=<模板ID> --title=付款 --staff=张三 --page=1 --count=20 + +# 草稿详情:支持单号或 flowId(工作流创建的草稿可用 Job 输出里的 flowId 查询) +hose-use bill get <单号|flowId> ``` +> 草稿列表只覆盖当前身份可见的「我发起」流程。他人或系统创建的草稿可能不在 `flows/my` 中; +> 已知单号时用 `bill get <单号>`,已知 flowId 时用 `bill get ` 直读详情。 + --- ## 2. 单据详情精准下钻 (`bill get`) diff --git a/specs/hose-open-api/paths/bill.yaml b/specs/hose-open-api/paths/bill.yaml index 3220cb6..52d2591 100644 --- a/specs/hose-open-api/paths/bill.yaml +++ b/specs/hose-open-api/paths/bill.yaml @@ -27,9 +27,36 @@ list: - name: state in: query required: false - description: 按审批/支付状态过滤(paid 已支付, approving 审批中, draft 草稿) + description: >- + 按审批/支付状态过滤(paid 已支付, approving 审批中)。传 draft/草稿 时改用 + 「我发起」的 flows/my 草稿列表,因为草稿尚未进入台账索引。 schema: type: string + - name: template + in: query + required: false + description: 草稿模式下按模板(表单规格)ID 过滤;版本化 ID 会剥离末尾哈希 + schema: + type: string + - name: title + in: query + required: false + description: 草稿模式下按标题关键字过滤 + schema: + type: string + - name: staff + in: query + required: false + description: 草稿模式下按提交人(员工 ID、工号或唯一姓名)过滤 + schema: + type: string + - name: page + in: query + required: false + description: 页码,与 count 配合分页(从 1 开始) + schema: + type: integer + default: 1 - name: count in: query required: false diff --git a/specs/openapi.json b/specs/openapi.json index bce6ba6..5c141d6 100644 --- a/specs/openapi.json +++ b/specs/openapi.json @@ -662,11 +662,48 @@ "name": "state", "in": "query", "required": false, - "description": "按审批/支付状态过滤(paid 已支付, approving 审批中, draft 草稿)", + "description": "按审批/支付状态过滤(paid 已支付, approving 审批中)。传 draft/草稿 时改用 「我发起」的 flows/my 草稿列表,因为草稿尚未进入台账索引。", "schema": { "type": "string" } }, + { + "name": "template", + "in": "query", + "required": false, + "description": "草稿模式下按模板(表单规格)ID 过滤;版本化 ID 会剥离末尾哈希", + "schema": { + "type": "string" + } + }, + { + "name": "title", + "in": "query", + "required": false, + "description": "草稿模式下按标题关键字过滤", + "schema": { + "type": "string" + } + }, + { + "name": "staff", + "in": "query", + "required": false, + "description": "草稿模式下按提交人(员工 ID、工号或唯一姓名)过滤", + "schema": { + "type": "string" + } + }, + { + "name": "page", + "in": "query", + "required": false, + "description": "页码,与 count 配合分页(从 1 开始)", + "schema": { + "type": "integer", + "default": 1 + } + }, { "name": "count", "in": "query", diff --git a/src/cli/command-metadata.ts b/src/cli/command-metadata.ts index 99f59bc..55ecae8 100644 --- a/src/cli/command-metadata.ts +++ b/src/cli/command-metadata.ts @@ -376,6 +376,7 @@ export const COMMAND_METADATA: Record = { "--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容", + "--state=draft/草稿 查询未提交草稿(数据源为 flows/my),支持 --template/--title/--staff/--page 过滤", "trace 的 --no-invoice/--noInvoice/--basic 为兼容空操作;穿透诊断本身不补充加载发票详情" ], "aliases": [ @@ -415,7 +416,7 @@ export const COMMAND_METADATA: Record = { "url": "link", "specification": "spec" }, - flags: { ...flagList("all audit basic confirm distinct drop-attachments dropAttachments force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target template title to amount reason fee-type feeType", "value") } + flags: { ...flagList("all audit basic confirm distinct drop-attachments dropAttachments force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir page participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target template title to amount reason fee-type feeType", "value") } }, "flow": { "summary": "审批流全域透视与穿透诊断", @@ -447,7 +448,7 @@ export const COMMAND_METADATA: Record = { "show": "get", "find": "get" }, - flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") } + flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir page participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") } }, "contact": { "summary": "企业通讯录与人员检索", diff --git a/src/cli/commands/bill/list-draft.test.ts b/src/cli/commands/bill/list-draft.test.ts new file mode 100644 index 0000000..8a133f3 --- /dev/null +++ b/src/cli/commands/bill/list-draft.test.ts @@ -0,0 +1,106 @@ +import { afterEach, describe, expect, it, spyOn } from "bun:test"; +import * as session from "../../../core/http/hose-web-session-client.js"; +import { parseArgs } from "../../parser.js"; +import { createBillActionContext } from "./context.js"; +import { handleList } from "./search.js"; + +const spies: Array<{ mockRestore(): void }> = []; +afterEach(() => { + for (const spy of spies.splice(0).reverse()) spy.mockRestore(); +}); + +function json(value: unknown): Response { + return new Response(JSON.stringify(value)); +} + +function draftClient(corpId: string) { + const flowsPosts: any[] = []; + const client = { + get: async (url: string) => { + if (url.includes("staffs/actives")) { + return json({ items: [{ id: "staff-1", name: "张三", code: "1001" }] }); + } + return json({}); + }, + post: async (url: string, payload: any) => { + if (url.includes("datalink/entity/search")) return json({ items: [] }); + if (url.endsWith("/flows/my")) { + flowsPosts.push({ url, payload, corpId }); + return json({ + count: 1, + items: [{ + flow: { + id: "flow-cli-draft", + state: "draft", + formType: "payment", + createTime: 1781682826000, + updateTime: 1781682870000, + }, + form: { + code: "FK26000009", + title: "付款草稿CLI", + specificationId: { id: "spec-pay", name: "对公付款单" }, + submitterId: { id: "staff-1", name: "张三", code: "1001" }, + payMoney: { standard: "10.00", standardSymbol: "¥", standardStrCode: "CNY" }, + }, + }], + }); + } + return json({}); + }, + }; + return { client, flowsPosts }; +} + +function context(args: string[], corpId: string, jsonMode: boolean) { + const corp = { id: corpId, name: "测试企业", credentials: { corpId } }; + return createBillActionContext(parseArgs(args), { jsonMode, selectedCorp: corp } as any); +} + +describe("bill list draft mode", () => { + it("routes --state=draft to flows/my with template, title, submitter and page filters", async () => { + const { client, flowsPosts } = draftClient("cli-draft-corp-json"); + spies.push(spyOn(session, "createSessionClient").mockResolvedValue(client as any)); + + const args = [ + "bill", "list", "--state=draft", "--mine", + `--template=spec-pay:${"a".repeat(32)}`, + "--title=付款", "--staff=张三", + "--page=2", "--count=10", "--json", + ]; + const result = await handleList(context(args, "cli-draft-corp-json", true)); + + expect(result.exitCode).toBe(0); + const output = JSON.parse(result.stdout); + expect(output.total).toBe(1); + expect(output.items[0]).toMatchObject({ + billId: "flow-cli-draft", + billCode: "FK26000009", + billName: "付款草稿CLI", + state: "draft", + }); + expect(output.items[0].amount).toContain("10.00"); + + expect(flowsPosts).toHaveLength(1); + const filterBy = flowsPosts[0].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).not.toContain("a".repeat(32)); + expect(filterBy).toContain('INSTR(form.submitterId, "staff-1")'); + expect(flowsPosts[0].payload.json.limit).toEqual({ start: 10, count: 10 }); + expect(flowsPosts[0].payload.json.orderBy).toEqual([{ value: "createTime", order: "DESC" }]); + }); + + it("renders a draft-specific text header for --state=草稿", async () => { + const { client } = draftClient("cli-draft-corp-text"); + spies.push(spyOn(session, "createSessionClient").mockResolvedValue(client as any)); + + const result = await handleList(context(["bill", "list", "--state=草稿"], "cli-draft-corp-text", false)); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("单据草稿列表"); + expect(result.stdout).toContain("FK26000009"); + expect(result.stdout).toContain("bill submit"); + }); +}); diff --git a/src/cli/commands/bill/search.ts b/src/cli/commands/bill/search.ts index d6342fa..6735240 100644 --- a/src/cli/commands/bill/search.ts +++ b/src/cli/commands/bill/search.ts @@ -1,4 +1,10 @@ -import { getBillByCodeOrId, getBillRisk, searchAndFormatBills, traceBillFlowDetail } from "../../../domains/bill/tools.js"; +import { + getBillByCodeOrId, + getBillRisk, + searchAndFormatBills, + searchAndFormatDraftBills, + traceBillFlowDetail, +} from "../../../domains/bill/tools.js"; import { booleanOption, numberOption, stringOption } from "../../parser.js"; import { printJson, printTable, printKeyValue } from "../../printer.js"; import type { CliResult } from "../../types.js"; @@ -6,8 +12,10 @@ import type { BillActionContext } from "./context.js"; export async function handleList(ctx: BillActionContext): Promise { const { parsed, runtime, corp, corpId } = ctx; + const state = stringOption(parsed.options, ["state", "s"]); + const isDraft = state ? /^(draft|草稿)$/i.test(state.trim()) : false; const mine = booleanOption(parsed.options, ["mine", "my", "self"]); - if (mine) { + if (mine && !isDraft) { const { handleTaskCommand } = await import("./../task.js"); return handleTaskCommand( { @@ -23,8 +31,9 @@ export async function handleList(ctx: BillActionContext): Promise { const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]); const searchFields = stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "sf"]); const stage = stringOption(parsed.options, ["stage"]); - const state = stringOption(parsed.options, ["state", "s"]); - const count = numberOption(parsed.options, ["count", "limit", "n"], 20); + const count = numberOption(parsed.options, ["count", "limit", "n"], 20) ?? 20; + const page = Math.max(1, numberOption(parsed.options, ["page"], 1) ?? 1); + const start = (page - 1) * count; const since = stringOption(parsed.options, ["since", "days", "d"]); const startDate = stringOption(parsed.options, ["start-date", "startDate", "from", "start"]); const endDate = stringOption(parsed.options, ["end-date", "endDate", "to", "end"]); @@ -34,21 +43,54 @@ export async function handleList(ctx: BillActionContext): Promise { const select = stringOption(parsed.options, ["select", "fields"]); const distinct = booleanOption(parsed.options, ["distinct"]); - const result = await searchAndFormatBills(await ctx.getClient(), corpId, { - code, - keyword, - searchFields, - stage, - state, - count, - since, - startDate, - endDate, - order, - filterBy, - select, - distinct, - }); + const title = stringOption(parsed.options, ["title"]); + const rawTemplate = stringOption(parsed.options, [ + "template", + "spec", + "specification", + "specification-id", + "specificationId", + ]); + const templateId = rawTemplate + ? rawTemplate + .trim() + .replace(/^\[|\]$/g, "") + .replace(/:[0-9a-f]{32,64}$/i, "") + : undefined; + const staffValues = ctx.listOption(["staff", "staff-id"]); + const submitterIds = + isDraft && staffValues?.length ? await ctx.resolveApproverIds(staffValues) : undefined; + + const result = isDraft + ? await searchAndFormatDraftBills(await ctx.getClient(), corpId, { + code, + keyword, + title, + templateId, + submitterIds, + start, + count, + since, + startDate, + endDate, + order, + }) + : await searchAndFormatBills(await ctx.getClient(), corpId, { + code, + keyword, + searchFields, + stage, + state, + start, + count, + since, + startDate, + endDate, + order, + filterBy, + select, + distinct, + }); if (runtime.jsonMode) { return { @@ -67,7 +109,7 @@ export async function handleList(ctx: BillActionContext): Promise { }; } - const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", "提交时间"]; + const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", isDraft ? "创建时间" : "提交时间"]; const rows = result.items.map((b, idx) => [ idx + 1, b.billCode, @@ -75,7 +117,7 @@ export async function handleList(ctx: BillActionContext): Promise { b.stage || "-", b.state || "-", b.amount || "-", - b.submitDate || b.createTime || "-", + isDraft ? b.createTime || b.submitDate || "-" : b.submitDate || b.createTime || "-", ]); const filterSummary: string[] = []; @@ -87,14 +129,23 @@ export async function handleList(ctx: BillActionContext): Promise { } if (stage) filterSummary.push(`阶段: ${stage}`); if (state) filterSummary.push(`状态: ${state}`); + if (isDraft) { + if (templateId) filterSummary.push(`模板: ${templateId}`); + if (title) filterSummary.push(`标题: ${title}`); + if (staffValues?.length) filterSummary.push(`提交人: ${staffValues.join(", ")}`); + if (page > 1) filterSummary.push(`第 ${page} 页`); + } const filterTag = filterSummary.length > 0 ? ` | 筛选: ${filterSummary.join(", ")}` : ""; const tableOutput = printTable(headers, rows); - const title = `====== 单据与费用明细列表 (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`; - const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`; + const listLabel = isDraft ? "单据草稿列表" : "单据与费用明细列表"; + const titleLine = `====== ${listLabel} (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`; + const tip = isDraft + ? `\n提示: 运行 hose-use bill get <单号|flowId> 查看草稿详情;提交使用 hose-use bill submit <单号|flowId> --yes\n` + : `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`; return { - stdout: title + tableOutput + tip, + stdout: titleLine + tableOutput + tip, stderr: "", exitCode: 0, }; diff --git a/src/domains/bill/README.bill.md b/src/domains/bill/README.bill.md index faf50f2..5c991f7 100644 --- a/src/domains/bill/README.bill.md +++ b/src/domains/bill/README.bill.md @@ -86,6 +86,11 @@ src/domains/bill/ - 先 `POST /api/v1/flow/plans/computed` 计算审批计划; - 未指派审批人的节点必须由 `--approver` 显式指定,绝不自动编造; - 再 `POST /api/flow/v1/flows/$`(`name: freeflow.submit`,携带 `nodes`)。 +15. **未提交草稿列表 (`searchAndFormatDraftBills`)**: + - 草稿未进入 `POST /api/v2/invoice/search` 台账索引,`bill list --state=draft` 改走 `POST /api/flow/v1/flows/my`; + - 服务端过滤 `state.in("draft")`,支持 `--template`、`--title`、`--staff`、`--code`、`--keyword`、时间范围与 `--page/--count` 分页,按流程 `createTime` 排序; + - 客户端再按模板、标题、提交人做兜底匹配,避免 RQL 对对象字段的差异造成漏筛; + - 列表只覆盖当前身份可见的「我发起」草稿。他人/系统或工作流创建的草稿按已知单号查询;`getRawBillFlow` 新增 flowId 直读通道,`bill get ` 不依赖 `flows/my` 可见性。 ### 草稿写入前校验 diff --git a/src/domains/bill/api.ts b/src/domains/bill/api.ts index 515c017..73e7164 100644 --- a/src/domains/bill/api.ts +++ b/src/domains/bill/api.ts @@ -120,6 +120,25 @@ export async function getRawBillFlow( // 通道 0 失败时继续走既有回溯通道 } + // 通道 0.2: 已知 flowId 时直接读取流程详情。 + // 工作流或其他身份创建的草稿可能不在当前身份的 flows/my 中,但 Job 输出/页面链接会给出 flowId; + // 该通道不依赖列表可见性,也避免回退到「最近 N 条」本地匹配。 + if (/^ID01/i.test(cleanTarget)) { + try { + const detail = await client.post(`api/flow/v1/flows/flowId/$${cleanTarget}`, { + searchParams: { id: cleanTarget, corpId }, + json: { + filterBy: `(id==${quoted(cleanTarget)})`, + select: "id,state,form,logs", + }, + }); + const json = (await detail.json()) as { value?: Record }; + if (json.value) return { flowId: json.value }; + } catch { + // 非流程 ID 或不可见时继续走既有回溯通道 + } + } + // 通道 1: api/flow/v2/backlogs/search 精准单号与 ID 匹配 const searchFilters = [ `(id==${quoted(cleanTarget)})||((flowId.id==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)}))`, @@ -496,6 +515,82 @@ export async function searchRawBills( return RawBillSearchResponseSchema.parse(json); } +export interface RawDraftFlowSearchOptions { + start?: number; + count?: number; + code?: string; + keyword?: string; + title?: string; + templateId?: string; + submitterIds?: string[]; + from?: number; + to?: number; + order?: "ASC" | "DESC"; +} + +/** + * 查询「我发起」的未提交草稿流程。 + * + * 草稿尚未进入单据台账索引(`api/v2/invoice/search`),因此列表必须走 + * `api/flow/v1/flows/my`。服务端过滤字段与 task 域提交列表保持一致: + * state 使用小写 `draft`,模板/标题用 `INSTR(form.*, ...)`,时间用流程 `createTime`。 + */ +export async function searchMyDraftFlows( + client: KyInstance, + corpId: string, + options: RawDraftFlowSearchOptions = {} +): Promise<{ count: number; items: Record[] }> { + const filters: string[] = [ + '(state.in("draft"))', + // 与 task submitted 一致:对账单流程不是费控单据草稿,避免混入列表。 + `(INSTR(form.specificationId, ${quoted(`${corpId}:system:对账单`)})==0)`, + ]; + + const code = options.code?.trim(); + if (code) filters.push(`(form.code.in(${quoted(code)}))`); + + const title = options.title?.trim(); + if (title) filters.push(`(INSTR(form.title, ${quoted(title)}) > 0)`); + + const templateId = options.templateId?.trim(); + if (templateId) filters.push(`(INSTR(form.specificationId, ${quoted(templateId)}) > 0)`); + + const submitterIds = (options.submitterIds ?? []).map((id) => id.trim()).filter(Boolean); + if (submitterIds.length > 0) { + const submitterFilters = submitterIds.map((id) => `(INSTR(form.submitterId, ${quoted(id)}) > 0)`); + filters.push(submitterFilters.length === 1 ? submitterFilters[0]! : `(${submitterFilters.join(" || ")})`); + } + + const keyword = options.keyword?.trim(); + if (keyword) { + filters.push( + `((INSTR(form.title, ${quoted(keyword)}) > 0) || (INSTR(form.code, ${quoted(keyword)}) > 0))` + ); + } + + if (options.from !== undefined) filters.push(`(createTime > ${options.from})`); + if (options.to !== undefined) filters.push(`(createTime < ${options.to})`); + + const response = await client.post("api/flow/v1/flows/my", { + searchParams: { + type: "home5", + delegatedFilter: "DELEGATE_TO_ME", + corpId, + }, + json: { + filterBy: filters.join("&&"), + limit: { start: options.start ?? 0, count: options.count ?? 20 }, + orderBy: [{ value: "createTime", order: options.order ?? "DESC" }], + }, + }); + + const json = (await response.json()) as { count?: number; items?: unknown[] }; + const items = Array.isArray(json.items) + ? json.items.filter((item): item is Record => Boolean(item && typeof item === "object")) + : []; + return { count: json.count ?? items.length, items }; +} + // ── 按 ID 列表精确拉取单据详情 API ───────────────────────────────────────────── export async function getRawBillsByIds( diff --git a/src/domains/bill/bill.test.ts b/src/domains/bill/bill.test.ts index 7e3a623..13b4369 100644 --- a/src/domains/bill/bill.test.ts +++ b/src/domains/bill/bill.test.ts @@ -1,6 +1,9 @@ import { describe, it, expect } from "bun:test"; import { formatSingleBill, + formatFlowAsBill, + searchAndFormatDraftBills, + getBillByCodeOrId, getBillReferences, getBillRelations, getBillAttachments, @@ -714,6 +717,183 @@ describe("Bill Domain", () => { }); }); + 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 = { diff --git a/src/domains/bill/tools.ts b/src/domains/bill/tools.ts index ff38e8f..6eb0844 100644 --- a/src/domains/bill/tools.ts +++ b/src/domains/bill/tools.ts @@ -12,6 +12,7 @@ import { } from "../../core/errors.js"; import { searchRawBills, + searchMyDraftFlows, getRawBillsByIds, listEntitySchemas, getRawBillFlow, @@ -44,6 +45,7 @@ import { type BillPageResult, type EntityMeta, type BillQueryParams, + type BillDraftQueryParams, type BillFlowEntry, type BillFlowNode, type BillFlowTimeline, @@ -678,12 +680,20 @@ export function formatFlowAsBill( raw: Record, dictionary: Map ): FormattedBill { - const flow = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : {}) as Record; - const form = (flow.form && typeof flow.form === "object" ? flow.form : {}) as Record; + const flow = (raw.flowId && typeof raw.flowId === "object" + ? raw.flowId + : raw.flow && typeof raw.flow === "object" + ? raw.flow + : {}) as Record; + const form = (flow.form && typeof flow.form === "object" + ? flow.form + : raw.form && typeof raw.form === "object" + ? raw.form + : {}) as Record; 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 stage = typeof flow.formType === "string" ? flow.formType : typeof form.type === "string" ? form.type : "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"); @@ -714,8 +724,24 @@ export function formatFlowAsBill( 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; + // flows/my 的精简响应不一定带流程 createTime;草稿没有 submitDate 语义上的提交时间, + // 服务端仍会写入该字段,可作为创建时间兜底,避免列表展示为空。 + const createTimeNum = typeof flow.createTime === "number" + ? flow.createTime + : typeof raw.createTime === "number" + ? raw.createTime + : typeof form.createTime === "number" + ? form.createTime + : typeof form.submitDate === "number" + ? form.submitDate + : 0; + const updateTimeNum = typeof flow.updateTime === "number" + ? flow.updateTime + : typeof raw.updateTime === "number" + ? raw.updateTime + : typeof form.updateTime === "number" + ? form.updateTime + : 0; const createTimeStr = createTimeNum > 0 ? new Date(createTimeNum).toLocaleString("zh-CN") : ""; const updateTimeStr = updateTimeNum > 0 ? new Date(updateTimeNum).toLocaleString("zh-CN") : ""; @@ -1631,6 +1657,128 @@ export async function searchAndFormatBills( }; } +function draftFlowParts(item: Record): { + flow: Record; + form: Record; +} { + const flow = (item.flow && typeof item.flow === "object" + ? item.flow + : item.flowId && typeof item.flowId === "object" + ? item.flowId + : {}) as Record; + const form = (flow.form && typeof flow.form === "object" + ? flow.form + : item.form && typeof item.form === "object" + ? item.form + : {}) as Record; + return { flow, form }; +} + +/** + * 查询未提交草稿列表。 + * + * 草稿不在 `api/v2/invoice/search` 台账索引中,数据源改为 `api/flow/v1/flows/my`; + * 服务端过滤之外再做一次客户端兜底匹配,避免 RQL 对对象字段的差异造成漏筛。 + * 该列表只覆盖当前身份可见的「我发起」草稿;他人/系统创建的草稿按已知单号或 flowId + * 使用 `bill get` 查询(`getRawBillFlow` 的 flowId 直读通道)。 + */ +export async function searchAndFormatDraftBills( + client: KyInstance, + corpId: string, + params: BillDraftQueryParams = {} +): Promise { + const { dictionary } = await getFieldDictionary(client, corpId); + + let fromTime = params.from ?? parseDateFilter(params.startDate); + if (params.since) { + const duration = parseSinceDuration(params.since); + if (duration !== undefined) fromTime = Math.max(fromTime ?? 0, Date.now() - duration); + } + const toTime = params.to ?? parseDateFilter(params.endDate, true); + + const page = await searchMyDraftFlows(client, corpId, { + start: params.start ?? 0, + count: params.count ?? 20, + code: params.code, + keyword: params.keyword, + title: params.title, + templateId: params.templateId, + submitterIds: params.submitterIds, + from: fromTime, + to: toTime, + order: (params.order ?? "DESC").toUpperCase() as "ASC" | "DESC", + }); + + let items = page.items; + + const code = params.code?.trim(); + if (code) { + items = items.filter((item) => { + const { flow, form } = draftFlowParts(item); + return form.code === code || flow.id === code; + }); + } + + const title = params.title?.trim().toLowerCase(); + if (title) { + items = items.filter((item) => { + const { form } = draftFlowParts(item); + return typeof form.title === "string" && form.title.toLowerCase().includes(title); + }); + } + + const templateId = params.templateId?.trim(); + if (templateId) { + items = items.filter((item) => { + const { form } = draftFlowParts(item); + // flows/my 返回精简表单时字段名为 specification;创建/详情接口则常用 specificationId。 + const specification = form.specificationId ?? form.specification; + if (typeof specification === "string") return specification.includes(templateId); + if (specification && typeof specification === "object") { + const record = specification as Record; + return ["id", "originalId", "name"].some((key) => { + const value = record[key]; + return typeof value === "string" && (value === templateId || value.includes(templateId)); + }); + } + return false; + }); + } + + const submitterIds = (params.submitterIds ?? []).map((id) => id.trim()).filter(Boolean); + if (submitterIds.length > 0) { + items = items.filter((item) => { + const { form } = draftFlowParts(item); + const submitter = form.submitterId; + if (typeof submitter === "string") { + return submitterIds.some((id) => submitter === id || submitter.includes(id)); + } + if (submitter && typeof submitter === "object") { + const record = submitter as Record; + return submitterIds.some((id) => + [record.id, record.userId].some( + (value) => typeof value === "string" && (value === id || value.endsWith(`:${id}`)) + ) + ); + } + return false; + }); + } + + const keyword = params.keyword?.trim().toLowerCase(); + if (keyword) { + items = items.filter((item) => { + const { form } = draftFlowParts(item); + return [form.title, form.code].some( + (value) => typeof value === "string" && value.toLowerCase().includes(keyword) + ); + }); + } + + const formatted = items.map((item) => formatFlowAsBill(item, dictionary)); + return { total: page.count, returned: formatted.length, items: formatted }; +} + export async function getTranslatorContext( client: KyInstance, corpId: string, diff --git a/src/domains/bill/types.ts b/src/domains/bill/types.ts index 38718f3..287a793 100644 --- a/src/domains/bill/types.ts +++ b/src/domains/bill/types.ts @@ -192,6 +192,22 @@ export interface BillQueryParams { join?: string | string[]; } +export interface BillDraftQueryParams { + code?: string; + keyword?: string; + title?: string; + templateId?: string; + submitterIds?: string[]; + start?: number; + count?: number; + since?: string; + from?: number; + to?: number; + startDate?: string; + endDate?: string; + order?: "ASC" | "DESC" | "asc" | "desc"; +} + export interface BillFlowEntry { id?: string; time?: number;