feat(bill): add server-side filterBy support and clarify status skill rules

This commit is contained in:
gitea committed 2026-09-17 14:58:02 +08:00
1 parent 4b75132b43
commit ca713cfafc
7 files changed
+234 -16

No files matched your search

+20 -2
View File
@@ -38,6 +38,20 @@ metadata:
5. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
6. **写操作两阶段确认**:所有 CLI 写操作先使用 `--dry-run` 查看目标和变更,再使用同一命令追加 `--yes` 或 `--confirm` 执行;未确认时不会发起写请求或写入本地状态。
7. **开发版全局安装**:需要让 PATH 中的命令立即跟随当前工作区时,运行 `bun run dev:override`;它会构建本机二进制、同步 Agent Skill,并更新全局 `hose-use` / `hose-aipro`。可先用 `bun run dev:override -- --dry-run` 查看计划;不要使用 `npm install -g .` 留下静态旧副本。
8. **工具域强隔离(Zero External Tool Cross-Calling)**:在处理合思/易快报相关诉求时,严格在 `hose-use` 体系内完成,**严禁跨域调用任何外部系统的 CLI(如 `seal-use` 等)**,绝不把其他系统的状态或数据强行拼接进来。
9. **企业状态与信息分级披露(Progressive Disclosure & Stop Rules)**:
- **4 大状态命令正交语义(严禁概念混淆)**:
* `hose-use probe [--corp=<id>]`:**企业接入连通性与 Token 时效探针(回答“某某企业状态怎么样/连通性如何/过期没有”的唯一标准命令)**。输出仅限网络 Session、EASO 换票、自建应用网关连通性以及 Token 剩余有效时长。
* `hose-use auth status`:统一用户中心 (IDP) 主账号登录态与会话检查。
* `hose-use context`:Agent 本地运行环境与配置全景自省(纯本地零网络 IO)。
* `hose-use corps list`:本地企业租户名录与工号花名册。
- **行为分级与终止准则**:
* **L1 基础设施与连通性(默认)**:用户询问企业状态时,**仅执行一次 `hose-use probe`**,以简短卡片输出核心连通性与时效,**立即停止工具调用并结束 Turn**。
* **L2 业务待办与通知(按需)**:仅在用户明确询问“有我的待办吗 / 有新消息吗”时,才调用 `task todo` 或 `message count`。
* **L3 深度排查与健康巡检(明确指令)**:严禁在日常状态询问中擅自执行 `workflow check` 巡检错误或无条件拉取全量单据,仅在用户下达“排查系统故障 / 检查工作流报错”等明确指令时才可触发。
10. **单据检索服务端过滤优先(Server-Side Filtering First)**:
- 查询单据列表优先使用服务端时间过滤 `--since=7d`、`--since=30d`、`--start-date`、`--end-date` 或指定 `--code`,服务端毫秒级利用索引返回;
- 在海量单据租户下,严禁无参数滥用全量检索,优先引导用户查看个人发起单据(`hose-use bill list --mine`)或待办(`hose-use task todo`)。
---
@@ -54,7 +68,7 @@ metadata:
| 第三方免密/协助链接一键秒级导入 | `hose-use corps add-link <url>`, `hose-use auth add-link <url>` | [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 <id>` | [references/auth.md](references/auth.md) |
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](references/bill.md) |
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list [--since=7d] [--code=<单号>]`, `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) |
@@ -115,7 +129,11 @@ hose-use contact list --json -o /tmp/staffs.json # 导出全量通讯录
hose-use contact get ID01MCcOgJl1td:3LsanKdS7Uo000 # 精准获取指定员工档案
# 3. 单据与费用
hose-use bill list # 查看最新单据与报销记录
hose-use bill list --since=7d # 推荐:服务端按近 7 天极速索引检索(防大租户超时)
hose-use bill list --since=30d --count=10 # 检索近 30 天最新 10 笔单据
hose-use bill list --start-date=2026-09-01 --end-date=2026-09-17 # 指定明确日期区间服务端过滤
hose-use bill list --code=CL20260901001 # 精准单号服务端索引匹配
hose-use bill list --keyword=打车 # 单据名称/摘要模糊匹配
hose-use bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接
hose-use bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
hose-use bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
+19 -1
View File
@@ -167,6 +167,11 @@ export async function handleBillCommand(
const stage = stringOption(parsed.options, ["stage"]);
const state = stringOption(parsed.options, ["state", "s"]);
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
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"]);
const rawOrder = stringOption(parsed.options, ["order", "sort", "direction"]);
const order = rawOrder && /asc/i.test(rawOrder) ? "ASC" : "DESC";
const result = await searchAndFormatBills(await getClient(), corpId, {
code,
@@ -174,6 +179,10 @@ export async function handleBillCommand(
stage,
state,
count,
since,
startDate,
endDate,
order,
});
if (runtime.jsonMode) {
@@ -204,8 +213,17 @@ export async function handleBillCommand(
b.submitDate || b.createTime || "-",
]);
const filterSummary: string[] = [];
if (since) filterSummary.push(`近 ${since}`);
if (startDate || endDate) filterSummary.push(`${startDate || "起"} ~ ${endDate || "止"}`);
if (code) filterSummary.push(`单号: ${code}`);
if (keyword) filterSummary.push(`关键字: ${keyword}`);
if (stage) filterSummary.push(`阶段: ${stage}`);
if (state) filterSummary.push(`状态: ${state}`);
const filterTag = filterSummary.length > 0 ? ` | 筛选: ${filterSummary.join(", ")}` : "";
const tableOutput = printTable(headers, rows);
const title = `====== 单据与费用明细列表 (企业: ${corp.name} | 总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
const title = `====== 单据与费用明细列表 (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
return {
+7 -1
View File
@@ -17,7 +17,13 @@ src/domains/bill/
1. **单据检索与分页 (`searchAndFormatBills`)**:
- 跨单据池查询费用明细、报销单、借款单与发票。
- 支持按单号(`code`)、阶段(`stage`)、状态(`state`)、关键字(`keyword`)过滤。
- 原生支持合思服务端 `filterBy` 索引检索(杜绝全表拉取与大租户超时):
- 时间范围(`since`、`startDate`、`endDate`、`from`、`to`);
- 单号服务端索引匹配(`code`,使用 `.in(...)` 语法避免 WAF 拦截);
- 名称与标题关键字匹配(`keyword`,走服务端 `INSTR`);
- 状态与软删除过滤(`active.in(true)`);
- 服务端 `orderBy: [{ value: "createTime", order: "DESC" }]` 排序与精简 `select` 字段;
- 客户端辅助精确二次过滤:阶段(`stage`)、状态(`state`)。
2. **按单号/ID 精确查询 (`getBillByCodeOrId`)**:
- 根据业务单号(如 `n0GMIM0dkQmKbS`)或单据 ID(如 `ID01TRzg7HMLcb`)查询单据。
3. **DataLink 字段元数据字典 (`getFieldDictionary`)**:
+28 -7
View File
@@ -310,20 +310,41 @@ export async function getRawBillRisk(
// ── 原始单据检索 API ──────────────────────────────────────────────────────────
export interface RawBillSearchOptions {
start?: number;
count?: number;
timeout?: number | false;
filterBy?: string;
orderBy?: Array<{ value: string; order: "ASC" | "DESC" }>;
select?: string;
}
export async function searchRawBills(
client: KyInstance,
corpId: string,
options: { start?: number; count?: number; timeout?: number | false } = {}
options: RawBillSearchOptions = {}
): Promise<RawBillSearchResponse> {
const jsonBody: Record<string, unknown> = {
limit: {
start: options.start ?? 0,
count: options.count ?? 50,
},
};
if (options.filterBy) {
jsonBody.filterBy = options.filterBy;
}
if (options.orderBy && options.orderBy.length > 0) {
jsonBody.orderBy = options.orderBy;
}
if (options.select) {
jsonBody.select = options.select;
}
const response = await client.post("api/v2/invoice/search", {
searchParams: { corporationId: corpId, corpId },
timeout: options.timeout ?? 30000,
json: {
limit: {
start: options.start ?? 0,
count: options.count ?? 50,
},
},
json: jsonBody,
});
const json = await response.json();
+58 -1
View File
@@ -1,5 +1,22 @@
import { describe, it, expect } from "bun:test";
import { formatSingleBill, getBillReferences, getBillRelations, getBillAttachments, getBillRisk, getBillFlow, approveBill, rejectBill, transferBill, addNodeBill, commentBill, resolveBillStaffIds } from "./tools.js";
import {
formatSingleBill,
getBillReferences,
getBillRelations,
getBillAttachments,
getBillRisk,
getBillFlow,
approveBill,
rejectBill,
transferBill,
addNodeBill,
commentBill,
resolveBillStaffIds,
parseDateFilter,
parseSinceDuration,
buildServerBillFilterBy,
searchAndFormatBills,
} from "./tools.js";
import { RawBillItemSchema, EntitySchema } from "./types.js";
describe("Bill Domain", () => {
@@ -539,4 +556,44 @@ describe("Bill Domain", () => {
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');
const timeFilter = buildServerBillFilterBy({ since: "7d" });
expect(timeFilter).toContain("createTime >");
const inactiveFilter = buildServerBillFilterBy({ active: false });
expect(inactiveFilter).toBe("(active.in(false))");
});
});
});
+95 -4
View File
@@ -1140,23 +1140,110 @@ export async function getBillRisk(
// ── 业务操作:多条件搜索与分页单据 ─────────────────────────────────────────────
export function parseDateFilter(value: string | number | undefined, isEnd = false): number | undefined {
if (value === undefined || value === "") return undefined;
if (typeof value === "number") return value;
const trimmed = String(value).trim();
if (!trimmed) return undefined;
if (/^\d+$/.test(trimmed)) return Number(trimmed);
const parsed = Date.parse(trimmed);
if (!Number.isNaN(parsed)) {
if (isEnd && /^\d{4}-\d{2}-\d{2}$/.test(trimmed)) {
const d = new Date(parsed);
d.setHours(23, 59, 59, 999);
return d.getTime();
}
return parsed;
}
return undefined;
}
export function parseSinceDuration(since: string | undefined): number | undefined {
if (!since) return undefined;
const match = /^(\d+)([dhmyw])$/i.exec(since.trim());
if (!match) return undefined;
const count = Number(match[1]);
const unit = match[2].toLowerCase();
const MS_PER_HOUR = 3600 * 1000;
const MS_PER_DAY = 24 * MS_PER_HOUR;
switch (unit) {
case "h": return count * MS_PER_HOUR;
case "d": return count * MS_PER_DAY;
case "w": return count * 7 * MS_PER_DAY;
case "m": return count * 30 * MS_PER_DAY;
case "y": return count * 365 * MS_PER_DAY;
default: return undefined;
}
}
export function buildServerBillFilterBy(params: BillQueryParams): string | undefined {
const parts: string[] = [];
// 1. active 软删除过滤 (使用 .in 避免 CloudWAF 误拦截)
if (params.active !== false) {
parts.push("(active.in(true))");
} else if (params.active === false) {
parts.push("(active.in(false))");
}
// 2. 时间范围过滤
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);
if (fromTime !== undefined) {
parts.push(`(createTime > ${fromTime})`);
}
if (toTime !== undefined) {
parts.push(`(createTime < ${toTime})`);
}
// 3. 单号服务端过滤 (使用 .in 避免 CloudWAF 误拦截)
if (params.code && params.code.trim()) {
parts.push(`(code.in(${JSON.stringify(params.code.trim())}))`);
}
// 4. 标题/名称关键字过滤
if (params.keyword && params.keyword.trim()) {
parts.push(`(INSTR(name, ${JSON.stringify(params.keyword.trim())}) > 0)`);
}
if (parts.length === 0) return undefined;
if (parts.length === 1) return parts[0];
return `(${parts.join(" && ")})`;
}
export async function searchAndFormatBills(
client: KyInstance,
corpId: string,
params: BillQueryParams = {}
): Promise<BillPageResult> {
const { dictionary } = await getFieldDictionary(client, corpId);
const filterBy = buildServerBillFilterBy(params);
const sortDirection = (params.order || "DESC").toUpperCase() as "ASC" | "DESC";
const orderBy = [{ value: "createTime", order: sortDirection }];
let searchRes: RawBillSearchResponse;
try {
searchRes = await searchRawBills(client, corpId, {
start: params.start ?? 0,
count: params.count ?? 50,
count: params.count ?? 20,
filterBy,
orderBy,
select: "id,code,name,createTime,updateTime,form,active",
});
} catch (err) {
if (String(err).includes("timed out") || (err as any)?.name === "TimeoutError") {
throw new Error(
`全局单据台账检索超时。在大企业或海量单据租户中,全量检索较为耗时。\n` +
`全局单据台账检索超时。在大企业或海量单据租户中,建议指定时间范围或单号筛选:\n` +
`建议:\n` +
` - 指定时间范围:hose-use bill list --since=7d 或 --start-date=2026-09-01\n` +
` - 查看当前员工发起的单据:hose-use task submitted 或 hose-use bill list --mine\n` +
` - 查看待我审批单据:hose-use task todo\n` +
` - 按单号精确查询:hose-use bill get <单号>`
@@ -1231,17 +1318,21 @@ export async function searchAndFormatBills(
export const billTools = [
{
name: "bill_search",
description: "检索企业名下的费用单据、报销单、借款单与发票列表(已自动将字段代码还原为可读业务名称)",
description: "检索企业名下的费用单据、报销单、借款单与发票列表(已自动将字段代码还原为可读业务名称,原生支持服务端时间与单号过滤)",
parameters: z.object({
code: z.string().optional().describe("按单据编号/单号过滤(如 jO1it3cIufDjNS)"),
keyword: z.string().optional().describe("按关键字模糊搜索标题、名称或内容"),
since: z.string().optional().describe("相对时间范围,如 7d (7天), 30d (30天), 90d, 1y"),
startDate: z.string().optional().describe("起始时间 (YYYY-MM-DD 或毫秒时间戳)"),
endDate: z.string().optional().describe("截止时间 (YYYY-MM-DD 或毫秒时间戳)"),
stage: z.string().optional().describe("按阶段过滤(如 expense 报销, loan 借款, payment 付款)"),
state: z.string().optional().describe("按审批/支付状态过滤(如 paid 已支付, approving 审批中, draft 草稿)"),
count: z.number().optional().default(20).describe("拉取记录数"),
order: z.enum(["ASC", "DESC", "asc", "desc"]).optional().default("DESC").describe("排序方向,默认 DESC 最新在前"),
}),
handler: async (
{ corpContext }: { corpContext: CorpContext },
params: { code?: string; keyword?: string; stage?: string; state?: string; count?: number }
params: BillQueryParams
) => {
const corp = corpContext.getCurrent();
if (!corp) {
+7
View File
@@ -102,6 +102,13 @@ export interface BillQueryParams {
state?: string;
start?: number;
count?: number;
since?: string;
from?: number;
to?: number;
startDate?: string;
endDate?: string;
active?: boolean;
order?: "ASC" | "DESC" | "asc" | "desc";
}
export interface BillFlowEntry {