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>
This commit is contained in:
giteaandClaude committed 2026-11-18 16:06:34 +08:00
1 parent baec8be6d3
commit 4b4a7049a0
12 files changed
+716 -36

No files matched your search

+5
View File
@@ -86,6 +86,11 @@ src/domains/bill/
- 先 `POST /api/v1/flow/plans/computed` 计算审批计划;
- 未指派审批人的节点必须由 `--approver` 显式指定,绝不自动编造;
- 再 `POST /api/flow/v1/flows/$<flowId>`(`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 <flowId>` 不依赖 `flows/my` 可见性。
### 草稿写入前校验
+95
View File
@@ -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<string, unknown> };
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<string, unknown>[] }> {
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<string, unknown> => Boolean(item && typeof item === "object"))
: [];
return { count: json.count ?? items.length, items };
}
// ── 按 ID 列表精确拉取单据详情 API ─────────────────────────────────────────────
export async function getRawBillsByIds(
+180
View File
@@ -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 = {
+153 -5
View File
@@ -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<string, unknown>,
dictionary: Map<string, { label: string; type: string }>
): FormattedBill {
const flow = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : {}) as Record<string, unknown>;
const form = (flow.form && typeof flow.form === "object" ? flow.form : {}) as Record<string, unknown>;
const flow = (raw.flowId && typeof raw.flowId === "object"
? raw.flowId
: raw.flow && typeof raw.flow === "object"
? raw.flow
: {}) as Record<string, unknown>;
const form = (flow.form && typeof flow.form === "object"
? flow.form
: raw.form && typeof raw.form === "object"
? raw.form
: {}) as Record<string, unknown>;
const billCode = (typeof form.code === "string" && form.code.trim()) || (typeof flow.id === "string" ? flow.id : String(raw.id || ""));
const title = (typeof form.title === "string" && form.title.trim()) || (typeof flow.title === "string" ? flow.title : undefined);
const billName = title || (flow.formType === "requisition" ? "差旅申请单" : "审批单据");
const stage = typeof flow.formType === "string" ? flow.formType : "flow";
const 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<string, unknown>): {
flow: Record<string, unknown>;
form: Record<string, unknown>;
} {
const flow = (item.flow && typeof item.flow === "object"
? item.flow
: item.flowId && typeof item.flowId === "object"
? item.flowId
: {}) as Record<string, unknown>;
const form = (flow.form && typeof flow.form === "object"
? flow.form
: item.form && typeof item.form === "object"
? item.form
: {}) as Record<string, unknown>;
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<BillPageResult> {
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<string, unknown>;
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<string, unknown>;
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,
+16
View File
@@ -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;