From b21d92efae498f519d63a0ca72e86924b0b438f8 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 20 Oct 2026 10:15:08 +0800 Subject: [PATCH] Add expense store lookup by document number --- skills/seal-use/SKILL.md | 1 + skills/seal-use/references/cli.md | 4 +- skills/seal-use/references/expense-data.md | 60 +++++++ src/cli/commands/data.ts | 14 +- src/cli/commands/expenses.test.ts | 127 ++++++++++++++ src/cli/commands/expenses.ts | 33 ++++ src/cli/help.ts | 10 +- src/cli/parser.ts | 2 +- src/cli/read-only.test.ts | 7 +- src/cli/read-only.ts | 1 + src/cli/runner.ts | 2 +- src/core/embedded-skill.generated.ts | 43 ++--- src/domains/seal/api.test.ts | 17 ++ src/domains/seal/api.ts | 18 +- src/domains/seal/capabilities/insight.ts | 18 +- src/domains/seal/expenses/lookup.test.ts | 164 +++++++++++++++++++ src/domains/seal/expenses/lookup.ts | 182 +++++++++++++++++++++ src/domains/seal/types.ts | 4 +- src/server.test.ts | 2 +- 19 files changed, 658 insertions(+), 51 deletions(-) create mode 100644 skills/seal-use/references/expense-data.md create mode 100644 src/cli/commands/expenses.test.ts create mode 100644 src/cli/commands/expenses.ts create mode 100644 src/domains/seal/expenses/lookup.test.ts create mode 100644 src/domains/seal/expenses/lookup.ts diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index 7d24801..0661dec 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -128,6 +128,7 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr | 配置、同步或排查发布到 HoseCloud | `references/hose-enterprise-deploy.md` | 涉及生产/测试配对或模拟时,再读 `staging-simulation-workflow.md` | | 生产草稿、测试同步、模拟、回归、发布 | `references/staging-simulation-workflow.md` | 需要客诉证据定界时,再读 `customer-feedback-rule-remediation.md` | | 按单号、SN、record ID 查审批、结论、引用规则或直达链接 | `references/approval-run-lightweight.md` | 明确涉及附件/OCR/发票争议时,转读 `approval-attachment-trace.md` | +| 单号对应费用是否入库、数据管理费用明细、费用库检索或记录关联 | `references/expense-data.md` | 明确要求审批结论时,再读 `approval-run-lightweight.md` | | CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 | | Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 | | 规则数量、摘要列表、历史规则、编号重排、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` | diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 73f1c6f..54d736d 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -183,12 +183,12 @@ seal-use contacts departments [] [--corp ] seal-use contacts children [--corp ] seal-use contacts users [--corp ] seal-use contacts sync-time [--corp ] -seal-use data expenses [--search ] [--start-date ] [--end-date ] [--offset ] [--limit ] [--corp ] +seal-use data expenses [--sn |--record-id |--search ] [--start-date ] [--end-date ] [--offset ] [--limit ] [--max-scan ] [--corp ] seal-use data invoices [--search ] [--start-date ] [--end-date ] [--offset ] [--limit ] [--full] [--corp ] seal-use invoices [list] [--search ] [--start-date ] [--end-date ] [--offset ] [--limit ] [--full] [--corp ] seal-use invoices trace [--corp ] seal-use invoices [--corp ] -seal-use expenses [list] [--search ] [--start-date ] [--end-date ] [--offset ] [--limit ] [--corp ] +seal-use expenses [list] [--sn |--record-id |--search ] [--start-date ] [--end-date ] [--offset ] [--limit ] [--max-scan ] [--corp ] seal-use llm config [--corp ] seal-use llm providers [--corp ] seal-use permissions available [--corp ] diff --git a/skills/seal-use/references/expense-data.md b/skills/seal-use/references/expense-data.md new file mode 100644 index 0000000..d4fbc54 --- /dev/null +++ b/skills/seal-use/references/expense-data.md @@ -0,0 +1,60 @@ +# 费用明细:按单号核验入库 + +## 首选入口 + +用户问“某单据的费用明细是否进入 SealAI 数据管理 → 费用明细”时,先确定目标企业,再运行: + +```bash +seal-use expenses --sn --corp +``` + +这是只读查询,使用同一个 `sealExpensesList` 内部能力和既有 MCP 网关,不触发同步、审批或费用写入。`data expenses --sn` 与该入口等价。不要把查询扩大为自动补录或重新审核。 + +## 已验证的关联路径 + +2026-10-20 对测试站点公开前端契约和测试企业进行只读往返验证:费用列表支持 `filter.recordId`,返回 `id`、`documentId`、`recordId` 等字段;普通文本搜索用于费用类型、描述、金额。同一已存在费用对应的原单号作为普通搜索词时未命中,按关联审批记录 ID 筛选则命中。因此不能用 `--search <单号>` 的空结果判断未入库,也不能仅因审批记录存在就说费用已入库。 + +CLI 先分页查询单号候选审批记录,对 `sourceDocumentSN` 做精确相等匹配,再对每个匹配记录调用费用列表的 `filter[recordId]`。返回的费用必须与请求记录 ID 一致;若双方都有 documentId,还必须一致。重审/重放产生的多个记录均纳入查询,不默认只查最新一次;费用按稳定费用 ID 去重,不按单号去重。 + +单号对应多个不同来源单据时返回 `ambiguous_source_documents`,不混合归因。费用列表本身没有已验证的单号直接过滤;找不到关联审批记录时返回 `approval_link_not_found` 和“无法确定”,无法凭该路径排除孤立费用记录。必要时取得明确关联记录 ID,用下面的原始列表入口补查。 + +## 结论判定 + +- `status:found, found:true`:至少一条费用已从费用库读取并通过关联校验。`matchedCount` 是已观察到的去重条数,`complete:false` 时仅为下限。 +- `status:not_found, found:false, complete:true`:单号匹配到的可见审批记录及其费用分页均已查完,指定费用日期范围内未找到关联费用。对外表述“关联范围内未找到”,不要断言该单据从未入库或推断入库失败根因。 +- `status:unknown, found:null, complete:false`:没有足够证据确认存在或不存在。常见原因包括没有审批关联、同号多原单据、扫描上限、分页重复/变化、关联字段不符或接口失败。 + +所有结果都有 `source:seal_expense_store`、`verification:existence_only`、查询时间、queryScope、scanned、关联记录及费用摘要;摘要不输出员工手机号和邮箱。不得把存在性查询解释成“所有原始费用明细均完整入库”;逐项完整性对账需另有原单明细和稳定行标识。 + +## 日期、分页和上限 + +单号查询不自动添加本月或最近一年范围;显式日期只过滤费用列表,不过滤用于定位的审批记录创建日期: + +```bash +seal-use expenses --sn --start-date 2025-01-01 --end-date 2025-12-31T23:59:59+08:00 --corp +seal-use expenses --sn --limit 100 --max-scan 10000 --corp +``` + +queryScope.startDate/endDate 是规范化毫秒时间戳,null 表示未显式传入;不代表服务端所有历史数据都永久可见。费用记录时间戳和 checkedAt 使用北京时间 ISO 秒级格式。 + +单号查询中 `--limit` 为每页大小(1–100,默认 100),不是最多返回匹配条数。审批候选扫描和费用扫描各最多 `--max-scan` 条(默认 5000,最高 10000);整个流程最多发起 100 次业务分页调用。命中上限保留已发现证据,标记 `complete:false`,不会以不完整查询得出否定结论。HTTP 层安全 GET 重试不包含在业务分页调用计数中。 + +总数缺失或变化、重复页、过早空页、记录变化、响应超出页大小都不能认为查询完整。分页不是数据库快照,`complete:true` 只表示当前观察到的相关分页已遍历,不是对并发写入的事务保证。 + +`--sn` 与 `--search`、`--record-id`、`--offset` 互斥;`--max-scan` 仅用于 `--sn`。非法组合报 exit 2,扫描范围参数未通过 schema 校验报 exit 13。 + +## 普通费用列表 + +```bash +seal-use expenses list --search --offset 0 --limit 50 --corp +seal-use expenses list --record-id --corp +seal-use data expenses --record-id --corp +``` + +不传 `--sn` 时继续返回原始 `{expenses,total}`,不进行入库判定;`--record-id` 透传精确关联过滤,普通列表由调用者控制分页。列表请求始终包含平台要求的 filter 对象,未指定筛选时发送空搜索值。日期支持 ISO 或时间戳,并转换为接口所需毫秒值。未知子命令和裸位置单号会报用法错误,不会被忽略后返回无关列表。 + +## 失败和大结果 + +单号查询接口失败时 stdout 保留结构化查询状态,stderr 说明不完整,进程返回非零:认证失败 exit 11,其他上游/响应格式失败 exit 1。已有确切匹配仍保留 `found:true`,但 `complete:false`;没有匹配证据时保持 unknown。不能把失败当作未入库。 + +大结果可使用 `--output-file ` 保存 JSON,或有意选择 `--full` 放开现有输出保护;默认超过输出限制返回 exit 12。原始费用列表和结构化单号查询均遵守 stdout 纯 JSON。 diff --git a/src/cli/commands/data.ts b/src/cli/commands/data.ts index 803883f..c1bbae0 100644 --- a/src/cli/commands/data.ts +++ b/src/cli/commands/data.ts @@ -1,9 +1,6 @@ import { usageError } from "../../core/errors.js"; import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; -import { runCapability } from "../helpers.js"; -import { numberOption, stringOption } from "../parser.js"; -import { outputOptions } from "../printer.js"; import type { ParsedArgs } from "../types.js"; export async function handleDataCommand( @@ -12,16 +9,9 @@ export async function handleDataCommand( corp: CorpConfig, args: ParsedArgs ) { - const params = { - offset: numberOption(args.options.offset), - limit: numberOption(args.options.limit), - startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]), - endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]), - search: stringOption(args.options.search) ?? stringOption(args.options.query) - }; - if (action === "expenses" || action === "expense") { - await runCapability("sealExpensesList", client, corp, params, outputOptions(args.options)); + const { handleExpensesCommand } = await import("./expenses.js"); + await handleExpensesCommand(args.command[2], client, corp, args); return; } diff --git a/src/cli/commands/expenses.test.ts b/src/cli/commands/expenses.test.ts new file mode 100644 index 0000000..4ef964b --- /dev/null +++ b/src/cli/commands/expenses.test.ts @@ -0,0 +1,127 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test" +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { runCli } from "../runner.js" + +const envKeys = ["SEAL_USE_CONFIG_FILE", "SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE"] as const +const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]])) +const oldFetch = globalThis.fetch +let dir: string +let requests: Array<{ method: string; path: string; query: URLSearchParams }> +let approvalSN: string +let expenseCount: number +let failureStatus: number | undefined +let description: string +const sn = "SN-CLI-FIXTURE" + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "seal-expense-cli-")) + const enterprises = join(dir, "enterprises") + mkdirSync(enterprises) + process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json") + process.env.SEAL_USE_ENTERPRISES_DIR = enterprises + process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json") + process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json") + writeFileSync(join(enterprises, "expense-cli-test.json"), JSON.stringify({ + id: "expense-cli-test", name: "Expense Test", environment: "test", seal: { url: "https://expense.example.test" }, + source: { type: "seal", token: "test-token", sealUrl: "https://expense.example.test", staffId: "fixture" } + })) + requests = [] + approvalSN = sn + expenseCount = 2 + failureStatus = undefined + description = "Fixture only" + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const request = new Request(input, init) + const url = new URL(request.url) + requests.push({ method: request.method, path: url.pathname, query: url.searchParams }) + if (request.method !== "GET") throw new Error("Unexpected mutation") + if (url.pathname === "/api/v1/approvals") return Response.json({ data: { records: [{ id: "record-1", sourceDocumentSN: approvalSN, sourceDocumentId: "source-1", documentId: "document-1" }], total: 1 } }) + if (failureStatus) return Response.json({ error: { message: "fixture failure" } }, { status: failureStatus }) + if (!url.searchParams.has("filter[search]") && !url.searchParams.has("filter[recordId]")) return Response.json({ error: "filter required" }, { status: 400 }) + const offset = Number(url.searchParams.get("offset")) + const limit = Number(url.searchParams.get("limit")) + const expenses = Array.from({ length: expenseCount }, (_, i) => ({ id: `expense-${i}`, recordId: "record-1", documentId: "document-1", type: "fixture", amount: i + 1, currency: "CNY", description, user: { mobile: "private-fixture" } })) + return Response.json({ data: { expenses: expenses.slice(offset, offset + limit), total: expenses.length } }) + }) as typeof fetch +}) +afterEach(() => { + for (const key of envKeys) { + if (oldEnv[key] === undefined) delete process.env[key] + else process.env[key] = oldEnv[key] + } + globalThis.fetch = oldFetch + rmSync(dir, { recursive: true, force: true }) +}) +function cli(...argv: string[]) { return runCli([...argv, "--corp", "expense-cli-test"]) } + +describe("expense document lookup CLI", () => { + test("canonical, singular, list and data entrances all execute the same read-only lookup", async () => { + for (const prefix of [["expenses"], ["expense"], ["expenses", "list"], ["data", "expenses"], ["data", "expense", "list"]]) { + const result = await cli(...prefix, "--sn", sn, "--limit", "1") + expect(result.exitCode).toBe(0) + expect(JSON.parse(result.stdout)).toMatchObject({ status: "found", found: true, complete: true, matchedCount: 2 }) + expect(result.stdout).not.toContain("private-fixture") + } + expect(requests.every(request => request.method === "GET")).toBe(true) + expect(requests.filter(request => request.path.includes("expenses")).every(request => request.query.get("filter[recordId]") === "record-1")).toBe(true) + }) + + test("raw list behavior stays compatible while bare list and record filters get a required filter object", async () => { + const raw = await cli("expenses", "list") + expect(raw.exitCode).toBe(0) + expect(JSON.parse(raw.stdout)).toHaveProperty("expenses") + expect(requests[0]?.query.get("filter[search]")).toBe("") + expect(requests[0]?.query.has("filter[startDate]")).toBe(false) + const byRecord = await cli("data", "expenses", "--record-id", "record-1") + expect(byRecord.exitCode).toBe(0) + expect(requests[1]?.query.get("filter[recordId]")).toBe("record-1") + await cli("expenses", "--search", "交通", "--offset", "2") + expect(requests[2]?.query.get("filter[search]")).toBe("交通") + expect(requests[2]?.query.get("offset")).toBe("2") + }) + + test("absence and unresolved linking have different JSON conclusions", async () => { + expenseCount = 0 + expect(JSON.parse((await cli("expenses", "--sn", sn)).stdout)).toMatchObject({ status: "not_found", found: false, complete: true }) + approvalSN = `${sn}-UNRELATED` + expect(JSON.parse((await cli("expenses", "--sn", sn)).stdout)).toMatchObject({ status: "unknown", found: null, complete: false, reason: "approval_link_not_found" }) + }) + + test("limits are explicit and partial scans cannot return not_found", async () => { + const result = await cli("expenses", "--sn", sn, "--max-scan", "1") + expect(result.exitCode).toBe(0) + expect(JSON.parse(result.stdout)).toMatchObject({ status: "found", complete: false, reason: "scan_limit", matchedCount: 1 }) + }) + + test("bad selector combinations, unknown verbs and invalid scan budgets fail before requests", async () => { + for (const argv of [ + ["expenses", "delete"], ["expenses", "SN-as-unsupported-positional"], ["expenses", "list", sn], ["data", "expenses", "list", sn], + ["expenses", "--sn", sn, "--search", "text"], ["expenses", "--sn", sn, "--record-id", "record-1"], + ["expenses", "--sn", sn, "--offset", "0"], ["expenses", "--max-scan", "1"] + ]) expect((await cli(...argv)).exitCode).toBe(2) + expect((await cli("expenses", "--sn", sn, "--max-scan", "0")).exitCode).toBe(13) + expect(requests).toHaveLength(0) + }) + + test("expense lookup failures retain JSON uncertainty and correct exit codes", async () => { + for (const status of [400, 403]) { + failureStatus = status + const result = await cli("expenses", "--sn", sn) + expect(result.exitCode).toBe(status === 403 ? 11 : 1) + expect(JSON.parse(result.stdout)).toMatchObject({ status: "unknown", complete: false, found: null }) + expect(result.stderr).toContain("incomplete") + } + }) + + test("oversized reports retain existing output protection and can be exported as JSON", async () => { + description = "x".repeat(210000) + expect((await cli("expenses", "--sn", sn)).exitCode).toBe(12) + const path = join(dir, "report.json") + const result = await cli("expenses", "--sn", sn, "--output-file", path) + expect(result.exitCode).toBe(0) + expect(JSON.parse(result.stdout)).toMatchObject({ outputFile: path }) + expect(JSON.parse(readFileSync(path, "utf8"))).toMatchObject({ status: "found", complete: true, matchedCount: 2 }) + }) +}) diff --git a/src/cli/commands/expenses.ts b/src/cli/commands/expenses.ts new file mode 100644 index 0000000..25cdccd --- /dev/null +++ b/src/cli/commands/expenses.ts @@ -0,0 +1,33 @@ +import type { CorpConfig } from "../../core/config/types.js" +import type { createSealClient } from "../../core/http/factory.js" +import { usageError } from "../../core/errors.js" +import { ExpenseLookupError } from "../../domains/seal/expenses/lookup.js" +import { runCapabilityResult } from "../helpers.js" +import { numberOption, stringOption } from "../parser.js" +import { outputOptions, printJson } from "../printer.js" +import type { ParsedArgs } from "../types.js" + +export async function handleExpensesCommand(action: string | undefined, client: Awaited>, corp: CorpConfig, args: ParsedArgs) { + const prefixLength = args.command[0]?.toLowerCase() === "data" ? 2 : 1 + if ((action && action !== "list") || args.command.length > prefixLength + Number(Boolean(action))) { + throw usageError("Usage: seal-use expenses [list] [--sn |--record-id |--search ]") + } + const sn = stringOption(args.options.sn) + const recordId = stringOption(args.options["record-id"]) ?? stringOption(args.options.recordId) + const search = stringOption(args.options.search) ?? stringOption(args.options.query) + const offset = numberOption(args.options.offset) + const maxScan = numberOption(args.options["max-scan"]) ?? numberOption(args.options.maxScan) + if (sn !== undefined && (recordId !== undefined || search !== undefined || offset !== undefined)) throw usageError("--sn cannot be combined with --search, --record-id, or --offset") + if (maxScan !== undefined && sn === undefined) throw usageError("--max-scan requires --sn") + try { + const result = await runCapabilityResult("sealExpensesList", client, corp, { + sn, recordId, search, offset, maxScan, limit: numberOption(args.options.limit), + startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]), + endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]) + }) + printJson(result, outputOptions(args.options)) + } catch (error) { + if (error instanceof ExpenseLookupError) printJson(error.report, outputOptions(args.options)) + throw error + } +} diff --git a/src/cli/help.ts b/src/cli/help.ts index adddd89..8ad75a7 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -1169,8 +1169,8 @@ export const HELP_REGISTRY: AreaHelp[] = [ commands: [ { name: "expenses", - summary: "Search raw expense items (also available as 'seal-use expenses')", - usage: ["seal-use data expenses [--search ] [--start-date ] [--end-date ] [--offset ] [--limit ] [--corp ]"] + summary: "List expenses, or verify expense-store membership by exact document number with --sn", + usage: ["seal-use data expenses [--sn |--record-id |--search ] [--start-date ] [--end-date ] [--offset ] [--limit ] [--max-scan ] [--corp ]"] }, { name: "invoices", @@ -1204,13 +1204,13 @@ export const HELP_REGISTRY: AreaHelp[] = [ { area: "expenses", title: "费用明细查询", - description: "查询历史费用明细记录。", + description: "查询历史费用明细;--sn 按单号关联审批记录并核验费用库存在性,区分找到、关联范围内未找到和无法确定。", commands: [ { name: "list", - summary: "分页查询费用明细", + summary: "普通查询分页返回原始记录;--sn 自动翻页核验,--limit 为页大小,--max-scan 默认为 5000", usage: [ - "seal-use expenses [list] [--search ] [--start-date ] [--end-date ] [--offset ] [--limit ] [--corp ]" + "seal-use expenses [list] [--sn |--record-id |--search ] [--start-date ] [--end-date ] [--offset ] [--limit ] [--max-scan ] [--corp ]" ] } ] diff --git a/src/cli/parser.ts b/src/cli/parser.ts index 189ae3c..e7cba4c 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -59,7 +59,7 @@ export const VALUE_FLAGS = new Set([ "json", "json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit", "lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus", "max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode", - "max-runs", + "max-runs", "max-scan", "maxScan", "month", "n", "name", "name-contains", "node-id", "nodeId", "note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", diff --git a/src/cli/read-only.test.ts b/src/cli/read-only.test.ts index 86dc8f8..e10a40d 100644 --- a/src/cli/read-only.test.ts +++ b/src/cli/read-only.test.ts @@ -27,7 +27,8 @@ describe("CLI read-only classification", () => { "auth test", "auth doctor", "auth seal-link list", - "doctor auth" + "doctor auth", + "expenses " ]); test("every allow-listed command exists in the help registry", () => { @@ -55,6 +56,10 @@ describe("CLI read-only classification", () => { ["corp", "list"], ["corp", "get", "corp-a"], ["documents", "list", "--corp", "corp-a"], + ["expenses", "--sn", "SN-FIXTURE", "--corp", "corp-a"], + ["expenses", "list", "--record-id", "run-1", "--corp", "corp-a"], + ["expense", "--sn", "SN-FIXTURE", "--corp", "corp-a"], + ["data", "expenses", "--sn", "SN-FIXTURE", "--corp", "corp-a"], ["documents", "get", "doc-1", "--corp", "corp-a"], ["documents", "search", "差旅", "--corp", "corp-a"], ["approval-runs", "get", "01a09dac-c688-767b-8eb4-37b945095585"], diff --git a/src/cli/read-only.ts b/src/cli/read-only.ts index 31bfc91..bd2d266 100644 --- a/src/cli/read-only.ts +++ b/src/cli/read-only.ts @@ -70,6 +70,7 @@ const READ_ONLY_COMMANDS: Record = { users: ["search", "get"], contacts: ["departments", "children", "users", "sync-time"], data: ["expenses", "invoices"], + expenses: ["", "list"], llm: ["config", "providers"], permissions: ["available", "configs"], billing: ["status", "plans", "features"], diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 9c23818..22ba08d 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -66,7 +66,7 @@ const CLIENT_COMMANDS: Record = { "contacts": async (args, corp, client) => (await import("./commands/contacts.js")).handleContactsCommand(args.command[1], args.command[2], client, corp, args), "data": async (args, corp, client) => (await import("./commands/data.js")).handleDataCommand(args.command[1], client, corp, args), "invoices": async (args, corp, client) => (await import("./commands/invoices.js")).handleInvoicesCommand(args.command[1], args.command[2], client, corp, args), - "expenses": async (args, corp, client) => (await import("./commands/data.js")).handleDataCommand("expenses", client, corp, args), + "expenses": async (args, corp, client) => (await import("./commands/expenses.js")).handleExpensesCommand(args.command[1], client, corp, args), "llm": async (args, corp, client) => (await import("./commands/llm.js")).handleLlmCommand(args.command[1], client, corp, args), "permissions": async (args, corp, client) => (await import("./commands/permissions.js")).handlePermissionsCommand(args.command[1], client, corp, args), "billing": async (args, corp, client) => (await import("./commands/billing.js")).handleBillingCommand(args.command[1], client, corp, args), diff --git a/src/core/embedded-skill.generated.ts b/src/core/embedded-skill.generated.ts index 588c6f5..4feeafe 100644 --- a/src/core/embedded-skill.generated.ts +++ b/src/core/embedded-skill.generated.ts @@ -14,16 +14,17 @@ import file10 from "../../skills/seal-use/references/approval-run-lightweight.md import file11 from "../../skills/seal-use/references/cli.md" with { type: "text" }; import file12 from "../../skills/seal-use/references/customer-feedback-rule-remediation.md" with { type: "text" }; import file13 from "../../skills/seal-use/references/enterprise-onboarding.md" with { type: "text" }; -import file14 from "../../skills/seal-use/references/first-time-user.md" with { type: "text" }; -import file15 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" }; -import file16 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" }; -import file17 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" }; -import file18 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" }; -import file19 from "../../skills/seal-use/references/report-templates.md" with { type: "text" }; -import file20 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" }; -import file21 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" }; -import file22 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" }; -import file23 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" }; +import file14 from "../../skills/seal-use/references/expense-data.md" with { type: "text" }; +import file15 from "../../skills/seal-use/references/first-time-user.md" with { type: "text" }; +import file16 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" }; +import file17 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" }; +import file18 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" }; +import file19 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" }; +import file20 from "../../skills/seal-use/references/report-templates.md" with { type: "text" }; +import file21 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" }; +import file22 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" }; +import file23 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" }; +import file24 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" }; export const EMBEDDED_SKILL_TEXT_FILES: Record = { "SKILL.md": file0, @@ -34,16 +35,17 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record = { "references/cli.md": file11, "references/customer-feedback-rule-remediation.md": file12, "references/enterprise-onboarding.md": file13, - "references/first-time-user.md": file14, - "references/hose-enterprise-auth.md": file15, - "references/hose-enterprise-deploy.md": file16, - "references/hose-enterprise-init.md": file17, - "references/langfuse-trace.md": file18, - "references/report-templates.md": file19, - "references/rule-lightweight.md": file20, - "references/rule-lint.md": file21, - "references/staging-simulation-workflow.md": file22, - "references/webhook-resource-pack.md": file23, + "references/expense-data.md": file14, + "references/first-time-user.md": file15, + "references/hose-enterprise-auth.md": file16, + "references/hose-enterprise-deploy.md": file17, + "references/hose-enterprise-init.md": file18, + "references/langfuse-trace.md": file19, + "references/report-templates.md": file20, + "references/rule-lightweight.md": file21, + "references/rule-lint.md": file22, + "references/staging-simulation-workflow.md": file23, + "references/webhook-resource-pack.md": file24, }; export const EMBEDDED_SKILL_ASSET_PATHS: Record = { @@ -70,6 +72,7 @@ export const EMBEDDED_SKILL_ALL_PATHS = [ "references/cli.md", "references/customer-feedback-rule-remediation.md", "references/enterprise-onboarding.md", + "references/expense-data.md", "references/first-time-user.md", "references/hose-enterprise-auth.md", "references/hose-enterprise-deploy.md", diff --git a/src/domains/seal/api.test.ts b/src/domains/seal/api.test.ts index 35149c8..68bb47c 100644 --- a/src/domains/seal/api.test.ts +++ b/src/domains/seal/api.test.ts @@ -280,6 +280,23 @@ describe("Seal contact API", () => { ]); }); + test("expenses always sends a filter object and supports recordId plus normalized dates", async () => { + const queries: URLSearchParams[] = []; + const client = { + get: (_url: string, options: { searchParams: URLSearchParams }) => { + queries.push(options.searchParams); + return { json: async () => ({ data: { expenses: [], total: 0 } }) }; + } + } as unknown as KyInstance; + await listExpenses(client); + expect(queries[0]?.has("filter[search]")).toBe(true); + expect(queries[0]?.get("filter[search]")).toBe(""); + expect(queries[0]?.has("filter[startDate]")).toBe(false); + await listExpenses(client, { recordId: "record-fixture", startDate: "2025-01-01T00:00:00+08:00" }); + expect(queries[1]?.get("filter[recordId]")).toBe("record-fixture"); + expect(queries[1]?.get("filter[startDate]")).toBe("1735660800000"); + }); + test("lists Feishu simulation approval definitions", async () => { let requestedUrl = ""; const client = { diff --git a/src/domains/seal/api.ts b/src/domains/seal/api.ts index 9b530a2..b089acb 100644 --- a/src/domains/seal/api.ts +++ b/src/domains/seal/api.ts @@ -10,7 +10,7 @@ import { CorpConfig } from "../../core/config/types.js"; import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js"; import { createSealClientForUrl } from "../../core/http/factory.js"; import { redactSensitiveText } from "../../core/redact.js"; -import { safetyBlocked } from "../../core/errors.js"; +import { safetyBlocked, validationError } from "../../core/errors.js"; import { resolveSealCustomHeaders } from "../../core/http/request-headers.js"; import { ApprovalDocumentListData, @@ -1123,6 +1123,8 @@ export type DataListParams = { search?: string; }; +export type ExpenseListParams = DataListParams & { recordId?: string }; + function dataListSearchParams(params: DataListParams): URLSearchParams { const searchParams = new URLSearchParams(); setOptional(searchParams, "filter[startDate]", params.startDate); @@ -1135,10 +1137,20 @@ function dataListSearchParams(params: DataListParams): URLSearchParams { export async function listExpenses( client: KyInstance, - params: DataListParams = {} + params: ExpenseListParams = {} ): Promise { + // The expense endpoint requires a filter object even for an unfiltered list. + const searchParams = dataListSearchParams(params); + searchParams.set("filter[search]", params.search ?? ""); + setOptional(searchParams, "filter[recordId]", params.recordId); + for (const [key, value] of [["startDate", params.startDate], ["endDate", params.endDate]] as const) { + if (value !== undefined) { + try { searchParams.set(`filter[${key}]`, String(normalizeToTimestamp(value))); } + catch { throw validationError(`Invalid expense ${key}: expected ISO date or timestamp`); } + } + } return unwrap( - await client.get("api/v1/expenses/list", { searchParams: dataListSearchParams(params) }), + await client.get("api/v1/expenses/list", { searchParams }), ExpenseListDataSchema ); } diff --git a/src/domains/seal/capabilities/insight.ts b/src/domains/seal/capabilities/insight.ts index f10e9a6..9a9268e 100644 --- a/src/domains/seal/capabilities/insight.ts +++ b/src/domains/seal/capabilities/insight.ts @@ -7,6 +7,8 @@ import type { } from "./helpers.js"; import { flattenInvoiceRecord } from "../approval-runs/invoices.js"; +import { lookupDocumentExpenses } from "../expenses/lookup.js"; +import { usageError } from "../../../core/errors.js"; export const insightCapabilities = [ { @@ -77,15 +79,25 @@ export const insightCapabilities = [ }, { name: "sealExpensesList", - description: "分页查询费用明细", + description: "分页查询费用明细;传 sn 时精确关联审批记录、分页核验费用库并返回存在性证据", parameters: z.object({ offset: z.number().int().nonnegative().optional(), limit: z.number().int().positive().max(100).optional(), startDate: z.string().optional().describe("开始时间"), endDate: z.string().optional().describe("结束时间"), - search: z.string().optional().describe("搜索费用类型、描述或金额") + search: z.string().optional().describe("搜索费用类型、描述或金额"), + recordId: z.string().trim().min(1).optional().describe("按关联审批记录 ID 精确筛选"), + sn: z.string().trim().min(1).optional().describe("按源单号核验入库;不能与 search、offset 或 recordId 同传"), + maxScan: z.number().int().positive().max(10000).optional().describe("单号核验每阶段最多扫描条数,默认 5000") }), - handler: async (client: KyInstance, params: api.DataListParams) => api.listExpenses(client, params) + handler: async (client: KyInstance, params: api.ExpenseListParams & { sn?: string; maxScan?: number }) => { + if (params.sn !== undefined) { + if (params.search !== undefined || params.offset !== undefined || params.recordId !== undefined) throw usageError("--sn cannot be combined with search, offset, or recordId"); + return lookupDocumentExpenses(client, { ...params, sn: params.sn }); + } + if (params.maxScan !== undefined) throw usageError("maxScan requires sn"); + return api.listExpenses(client, params); + } }, { name: "sealInvoicesList", diff --git a/src/domains/seal/expenses/lookup.test.ts b/src/domains/seal/expenses/lookup.test.ts new file mode 100644 index 0000000..cabdbc0 --- /dev/null +++ b/src/domains/seal/expenses/lookup.test.ts @@ -0,0 +1,164 @@ +import { describe, expect, test } from "bun:test" +import type { KyInstance } from "ky" +import { classifyCliError } from "../../../core/errors.js" +import { lookupDocumentExpenses, ExpenseLookupError } from "./lookup.js" + +const sn = "SN-FIXTURE" +const run = (id = "run-1", overrides: Record = {}) => ({ + id, sourceDocumentSN: sn, sourceDocumentId: "source-1", sourceSystem: "hose", documentId: `document-${id}`, ...overrides +}) +const expense = (id = "expense-1", recordId = "run-1", overrides: Record = {}) => ({ + id, recordId, documentId: `document-${recordId}`, type: "交通费", amount: 12.5, currency: "CNY", description: "Fixture expense", + createdAt: "2025-01-01T00:00:00Z", user: { mobile: "not-for-output", name: "Fixture Person" }, ...overrides +}) +type Reply = (path: string, query: URLSearchParams) => unknown +function mockClient(reply: Reply) { + const requests: Array<{ path: string; query: URLSearchParams }> = [] + const client = { get(path: string, options: { searchParams: URLSearchParams }) { + const query = options.searchParams + requests.push({ path, query }) + return { json: async () => ({ data: reply(path, query) }) } + } } as unknown as KyInstance + return { client, requests } +} +function pages(records: ReturnType[], expenses: ReturnType[]) { + return mockClient((path, query) => { + const offset = Number(query.get("offset")) + const limit = Number(query.get("limit")) + if (path === "api/v1/approvals") return { records: records.slice(offset, offset + limit), total: records.length } + const selected = expenses.filter(row => row.recordId === query.get("filter[recordId]")) + return { expenses: selected.slice(offset, offset + limit), total: selected.length } + }) +} + +describe("expense lookup by document number", () => { + test("joins every exact run across pages, verifies expense links and does not collapse document lines", async () => { + const f = pages([run(), run("run-2"), run("run-unrelated", { sourceDocumentSN: `${sn}-EXTRA` })], [expense(), expense("expense-2"), expense("expense-3", "run-2")]) + const result = await lookupDocumentExpenses(f.client, { sn, limit: 1 }) + expect(result).toMatchObject({ status: "found", found: true, complete: true, matchedCount: 3, verification: "existence_only", scanned: { approvalRecords: 3, expenseRecords: 3, requests: 6 } }) + expect(result.approvalRecords.map(row => row.recordId)).toEqual(["run-1", "run-2"]) + expect(result.expenses.map(row => row.id)).toEqual(["expense-1", "expense-2", "expense-3"]) + expect(result.expenses[0]).toMatchObject({ amount: 12.5, currency: "CNY", sourceDocumentSN: sn, createdAt: "2025-01-01T08:00:00+08:00" }) + expect(result.expenses[0]).not.toHaveProperty("user") + for (const request of f.requests) { + expect(request.query.has("filter[startDate]")).toBe(false) + expect(request.query.has("startDate")).toBe(false) + if (request.path.includes("expenses")) expect(request.query.get("filter[search]")).toBe("") + } + }) + + test("only exhaustive linked expense queries may report not_found", async () => { + const f = pages([run(), run("run-2")], []) + const result = await lookupDocumentExpenses(f.client, { sn, limit: 1 }) + expect(result).toMatchObject({ status: "not_found", found: false, complete: true, matchedCount: 0, queryScope: { association: "visible_approval_records", approvalRecordsComplete: true } }) + expect(f.requests.filter(request => request.path.includes("expenses"))).toHaveLength(2) + }) + + test("missing run links and substring matches never prove absence", async () => { + for (const records of [[], [run("other", { sourceDocumentSN: `${sn}-OTHER` })]]) { + const f = pages(records, []) + expect(await lookupDocumentExpenses(f.client, { sn })).toMatchObject({ status: "unknown", found: null, complete: false, reason: "approval_link_not_found" }) + expect(f.requests.every(request => request.path.includes("approvals"))).toBe(true) + } + }) + + test("the same SN pointing to different source documents is ambiguous", async () => { + const f = pages([run(), run("run-2", { sourceDocumentId: "another-source" })], [expense()]) + expect(await lookupDocumentExpenses(f.client, { sn })).toMatchObject({ status: "unknown", found: null, reason: "ambiguous_source_documents" }) + expect(f.requests).toHaveLength(1) + }) + + test("a foreign or missing record link cannot be counted as a match", async () => { + for (const invalid of [expense("bad", "foreign"), expense("bad", "run-1", { documentId: "foreign" }), { id: "bad" }]) { + const f = mockClient(path => path.includes("approvals") ? { records: [run()], total: 1 } : { expenses: [invalid], total: 1 }) + expect(await lookupDocumentExpenses(f.client, { sn })).toMatchObject({ status: "unknown", found: null, reason: "association_mismatch", matchedCount: 0 }) + } + }) + + test("repeated pages stop without producing a negative conclusion", async () => { + const f = mockClient(path => path.includes("approvals") ? { records: [run()], total: 2 } : { expenses: [], total: 0 }) + expect(await lookupDocumentExpenses(f.client, { sn, limit: 1 })).toMatchObject({ status: "unknown", found: null, reason: "repeated_page", complete: false }) + expect(f.requests).toHaveLength(3) + }) + + test("overlapping expense pages deduplicate IDs while retaining distinct expense lines", async () => { + const f = mockClient((path, query) => { + if (path.includes("approvals")) return { records: [run()], total: 1 } + const offset = Number(query.get("offset")) + return { expenses: offset === 0 ? [expense(), expense("expense-2")] : offset === 2 ? [expense("expense-2"), expense("expense-3")] : [], total: 3 } + }) + expect(await lookupDocumentExpenses(f.client, { sn, limit: 2 })).toMatchObject({ status: "found", complete: true, matchedCount: 3 }) + }) + + for (const stage of ["approval", "expense"] as const) { + test(`${stage} scan limits retain positive evidence but cannot assert completeness`, async () => { + const f = pages(stage === "approval" ? [run(), run("run-2")] : [run()], [expense(), expense("expense-2")]) + expect(await lookupDocumentExpenses(f.client, { sn, maxScan: 1 })).toMatchObject({ status: "found", found: true, complete: false, reason: "scan_limit", matchedCount: 1 }) + }) + } + + test("missing totals, changing totals, and premature empty pages remain inconclusive", async () => { + for (const mode of ["missing", "changing", "empty", "oversized"] as const) { + const f = mockClient((path, query) => { + if (path.includes("approvals")) return { records: [run()], total: 1 } + const offset = Number(query.get("offset")) + if (mode === "missing") return { expenses: [] } + if (mode === "oversized") return { expenses: [expense(), expense("extra")], total: 2 } + return { expenses: offset === 0 ? [expense()] : [], total: mode === "changing" && offset ? 3 : 2 } + }) + const result = await lookupDocumentExpenses(f.client, { sn, limit: 1 }) + expect(result.complete).toBe(false) + expect(result.found).not.toBe(false) + expect(result.reason).toBe({ missing: "missing_total", changing: "total_changed", empty: "inconsistent_page", oversized: "inconsistent_page" }[mode]) + } + }) + + test("request count is bounded independently of repeated or empty candidate histories", async () => { + const f = mockClient((_path, query) => ({ records: [run(`run-${query.get("offset")}`)], total: 1000 })) + const result = await lookupDocumentExpenses(f.client, { sn, limit: 1 }) + expect(result).toMatchObject({ status: "unknown", complete: false, reason: "request_limit" }) + expect(f.requests).toHaveLength(100) + }) + + test("explicit dates filter expenses, not approval creation dates", async () => { + const f = pages([run()], [expense()]) + const result = await lookupDocumentExpenses(f.client, { sn, startDate: "2025-01-01T00:00:00+08:00", endDate: "2025-12-31T23:59:59+08:00" }) + expect(result.queryScope.startDate).toBe("1735660800000") + expect(f.requests[0]?.query.has("startDate")).toBe(false) + expect(f.requests[1]?.query.get("filter[startDate]")).toBe("1735660800000") + }) + + test("malformed dates and reversed ranges fail before HTTP", async () => { + const f = pages([], []) + for (const input of [{ startDate: "bad" }, { startDate: "2026-02-01", endDate: "2026-01-01" }]) { + try { await lookupDocumentExpenses(f.client, { sn, ...input }); throw new Error("expected rejection") } + catch (error) { expect(classifyCliError(error).exitCode).toBe(2) } + } + expect(f.requests).toHaveLength(0) + }) + + test("query failures preserve partial matches and distinguish auth errors", async () => { + for (const auth of [true, false]) { + const f = mockClient((path, query) => { + if (path.includes("approvals")) return { records: [run()], total: 1 } + if (query.get("offset") === "0") return { expenses: [expense()], total: 2 } + throw Object.assign(new Error("secret upstream body must not be printed"), { response: { status: auth ? 403 : 500 } }) + }) + try { await lookupDocumentExpenses(f.client, { sn, limit: 1 }); throw new Error("expected rejection") } + catch (error) { + expect(error).toBeInstanceOf(ExpenseLookupError) + const failure = error as ExpenseLookupError + expect(failure.exitCode).toBe(auth ? 11 : 1) + expect(failure.report).toMatchObject({ status: "found", found: true, complete: false, matchedCount: 1, reason: auth ? "authentication_required" : "expense_query_failed" }) + expect(JSON.stringify(failure.report)).not.toContain("secret upstream") + } + } + }) + + test("invalid upstream expense shapes do not default to an empty successful page", async () => { + for (const data of [{ total: 0 }, { expenses: [{}], total: 1 }]) { + const f = mockClient(path => path.includes("approvals") ? { records: [run()], total: 1 } : data) + await expect(lookupDocumentExpenses(f.client, { sn })).rejects.toMatchObject({ report: { status: "unknown", reason: "expense_query_failed", complete: false } }) + } + }) +}) diff --git a/src/domains/seal/expenses/lookup.ts b/src/domains/seal/expenses/lookup.ts new file mode 100644 index 0000000..a101f07 --- /dev/null +++ b/src/domains/seal/expenses/lookup.ts @@ -0,0 +1,182 @@ +import { z } from "zod" +import type { KyInstance } from "ky" +import { CliError, classifyCliError, usageError } from "../../../core/errors.js" +import { formatBeijingIso } from "../../../core/config/timestamps.js" +import * as api from "../api.js" +import type { ApprovalRun } from "../types.js" + +export const expenseLookupOptionsSchema = z.object({ + sn: z.string().trim().min(1), + limit: z.number().int().positive().max(100).optional(), + maxScan: z.number().int().positive().max(10000).optional(), + startDate: z.string().optional(), + endDate: z.string().optional() +}) +const expenseSchema = z.object({ + id: z.string().min(1), recordId: z.string().optional(), documentId: z.string().optional() +}).passthrough() +type Expense = z.infer +type ScanReason = "scan_limit" | "request_limit" | "missing_total" | "total_changed" | "repeated_page" | "inconsistent_page" +type Scan = { rows: T[]; complete: boolean; reason?: ScanReason } +type Budget = { requests: number; maxRequests: number } + +// Local to expense lookup: both links must be exhaustive before asserting absence. +async function scanPages( + fetchPage: (offset: number, limit: number) => Promise<{ rows: T[]; total?: number }>, + pageSize: number, + maxScan: number, + budget: Budget, + onRows: (rows: T[]) => void +): Promise> { + const seen = new Map() + let offset = 0 + let expectedTotal: number | undefined + const result = (reason?: ScanReason): Scan => ({ rows: [...seen.values()], complete: !reason, ...(reason ? { reason } : {}) }) + while (offset < maxScan) { + if (budget.requests >= budget.maxRequests) return result("request_limit") + const limit = Math.min(pageSize, maxScan - offset) + budget.requests++ + const page = await fetchPage(offset, limit) + const rows = page.rows.slice(0, limit) + onRows(rows) + let newCount = 0 + let changedRow = false + for (const row of rows) { + const previous = seen.get(row.id) + if (previous && JSON.stringify(previous) !== JSON.stringify(row)) changedRow = true + if (!previous) { seen.set(row.id, row); newCount++ } + } + if (page.total === undefined) return result("missing_total") + if (expectedTotal !== undefined && expectedTotal !== page.total) return result("total_changed") + expectedTotal = page.total + if (changedRow || page.rows.length > limit || seen.size > expectedTotal) return result("inconsistent_page") + if (rows.length && newCount === 0) return result("repeated_page") + if (seen.size === expectedTotal) return result() + if (!rows.length) return result("inconsistent_page") + offset += rows.length + } + return result("scan_limit") +} + +export class ExpenseLookupError extends CliError { + constructor(readonly report: ExpenseLookupReport, auth: boolean) { + super("Expense lookup is incomplete; inspect the JSON query state before drawing a conclusion.", auth ? 11 : 1) + this.name = "ExpenseLookupError" + } +} + +function isoTimestamp(value: unknown): string | undefined { + const ms = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : NaN + return Number.isFinite(new Date(ms).getTime()) ? formatBeijingIso(ms) : undefined +} + +function projectExpense(expense: Expense, record: ApprovalRun) { + return { + id: expense.id, recordId: expense.recordId, documentId: expense.documentId, + sourceDocumentSN: record.sourceDocumentSN, sourceDocumentId: record.sourceDocumentId, + type: typeof expense.type === "string" ? expense.type : undefined, + amount: typeof expense.amount === "number" ? expense.amount : undefined, + currency: typeof expense.currency === "string" ? expense.currency : undefined, + description: typeof expense.description === "string" ? expense.description : undefined, + startTime: isoTimestamp(expense.startTime), endTime: isoTimestamp(expense.endTime), + createdAt: isoTimestamp(expense.createdAt), updatedAt: isoTimestamp(expense.updatedAt) + } +} + +export type ExpenseLookupReport = { + source: "seal_expense_store" + sourceDocumentSN: string + status: "found" | "not_found" | "unknown" + found: boolean | null + complete: boolean + matchedCount: number + reason?: string + checkedAt: string + verification: "existence_only" + queryScope: { + association: "visible_approval_records" + startDate: string | null + endDate: string | null + approvalRecordsComplete: boolean + maxScan: number + maxRequests: number + } + scanned: { approvalRecords: number; expenseRecords: number; requests: number } + approvalRecords: Array<{ recordId: string; documentId?: string; sourceDocumentId?: string; sourceSystem?: string }> + expenses: ReturnType[] +} + +export async function lookupDocumentExpenses(client: KyInstance, input: z.infer): Promise { + const params = expenseLookupOptionsSchema.parse(input) + // Dates only constrain expenses, never the creation time of the linking approval. + const dateValue = (value: string | undefined): string | null => { + if (value === undefined) return null + const parsed = /^\d+$/.test(value) ? Number(value) * (Number(value) < 1e11 ? 1000 : 1) : Date.parse(value) + if (!Number.isFinite(parsed) || parsed < 0 || parsed > 8.64e15) throw usageError("Invalid expense date: expected ISO date or timestamp") + return String(parsed) + } + const startDate = dateValue(params.startDate) + const endDate = dateValue(params.endDate) + if (startDate !== null && endDate !== null && Number(startDate) > Number(endDate)) throw usageError("Expense start date must not be after end date") + const pageSize = params.limit ?? 100 + const maxScan = params.maxScan ?? 5000 + const budget: Budget = { requests: 0, maxRequests: 100 } + const matched = new Map>() + const records = new Map() + let approvalComplete = false + let approvalScanned = 0 + let expenseScanned = 0 + let phase: "approval" | "expense" = "approval" + const report = (complete: boolean, reason?: string): ExpenseLookupReport => { + const found = matched.size > 0 ? true : complete ? false : null + return { + source: "seal_expense_store", sourceDocumentSN: params.sn, status: found === true ? "found" : found === false ? "not_found" : "unknown", + found, complete, matchedCount: matched.size, ...(reason ? { reason } : {}), checkedAt: formatBeijingIso(), verification: "existence_only", + queryScope: { association: "visible_approval_records", startDate, endDate, approvalRecordsComplete: approvalComplete, maxScan, maxRequests: budget.maxRequests }, + scanned: { approvalRecords: approvalScanned, expenseRecords: expenseScanned, requests: budget.requests }, + approvalRecords: [...records.values()].map(record => ({ recordId: record.id, documentId: record.documentId, sourceDocumentId: record.sourceDocumentId, sourceSystem: record.sourceSystem })), + expenses: [...matched.values()] + } + } + try { + const approvals = await scanPages(async (offset, limit) => { + // The deployed route supports search; SN equality is checked locally. + const data = await api.listApprovalRuns(client, { search: params.sn, offset, limit }) + return { rows: data.records, total: data.total } + }, pageSize, maxScan, budget, rows => { + approvalScanned += rows.length + for (const row of rows) if (row.sourceDocumentSN === params.sn) records.set(row.id, row) + }) + approvalComplete = approvals.complete + if (!records.size) return report(false, approvals.reason ?? "approval_link_not_found") + const documents = new Set([...records.values()].map(record => JSON.stringify([record.sourceSystem, record.sourceDocumentId ?? record.documentId ?? record.id]))) + if (documents.size > 1) return report(false, "ambiguous_source_documents") + phase = "expense" + let reason: string | undefined = approvals.reason + for (const record of records.values()) { + if (expenseScanned >= maxScan) { reason ??= "scan_limit"; break } + const expenses = await scanPages(async (offset, limit) => { + const data = await api.listExpenses(client, { recordId: record.id, startDate: params.startDate, endDate: params.endDate, offset, limit }) + return { rows: z.array(expenseSchema).parse(data.expenses), total: data.total } + }, pageSize, maxScan - expenseScanned, budget, rows => { + expenseScanned += rows.length + for (const row of rows) { + if (row.recordId !== record.id || (row.documentId && record.documentId && row.documentId !== record.documentId)) { + reason ??= "association_mismatch" + continue + } + const previous = matched.get(row.id) + const projected = projectExpense(row, record) + if (previous && JSON.stringify(previous) !== JSON.stringify(projected)) reason ??= "expense_changed_during_scan" + else matched.set(row.id, projected) + } + }) + reason ??= expenses.reason + if (expenses.reason === "request_limit") break + } + return report(!reason && approvalComplete, reason) + } catch (error) { + const auth = classifyCliError(error).exitCode === 11 + throw new ExpenseLookupError(report(false, auth ? "authentication_required" : `${phase}_query_failed`), auth) + } +} diff --git a/src/domains/seal/types.ts b/src/domains/seal/types.ts index ad26735..db61c49 100644 --- a/src/domains/seal/types.ts +++ b/src/domains/seal/types.ts @@ -385,8 +385,8 @@ export const InsightPerformanceSchema = z.object({ const DataRecordSchema = z.record(z.string(), z.unknown()); export const ExpenseListDataSchema = z.object({ - expenses: z.array(DataRecordSchema).default([]), - total: z.number().optional() + expenses: z.array(DataRecordSchema), + total: z.number().int().nonnegative().optional() }).passthrough(); export const InvoiceListDataSchema = z.object({ diff --git a/src/server.test.ts b/src/server.test.ts index e69012f..25d38f6 100644 --- a/src/server.test.ts +++ b/src/server.test.ts @@ -156,7 +156,7 @@ describe("seal-use MCP server", () => { // Read-only commands must get past the policy; `version` is a top-level command with no // registry row, and `corp` is an area alias the CLI dispatches as `corps`. - for (const command of ["seal-use version", "seal-use corps list", "seal-use corp list", "seal-use documents list --corp corp-a"]) { + for (const command of ["seal-use version", "seal-use corps list", "seal-use corp list", "seal-use documents list --corp corp-a", "seal-use expenses --sn SN-FIXTURE --corp missing-fixture-corp"]) { const allowed = await callRead(command); expect({ command, refusedByPolicy: allowed.text.includes("only runs read-only commands") }).toEqual({ command,