Compare commits

..
19 Commits
Author SHA1 Message Date
yunyingk ed3f38f1ab Merge pull request #104 from yunyingk/feat/workflow-debug-test-and-branch-diagnosis
feat(workflow): end-to-end workflow debug test command and condition branch explanation
2026-10-15 13:24:50 +08:00
gitea fe6183dd44 feat(workflow): add end-to-end workflow debug test command and condition branch explanation 2026-10-15 13:24:14 +08:00
yunyingk febeecdec7 Merge pull request #103 from yunyingk/feat/datalink-ref-card-display
feat(datalink): support card data.dataLink unwrapping in normalizeDatalinkRecord
2026-10-15 11:05:38 +08:00
gitea 0b3b022edf feat(datalink): support card data.dataLink unwrapping in normalizeDatalinkRecord 2026-10-15 11:05:12 +08:00
yunyingk 0e2fb6a9b8 Merge pull request #102 from yunyingk/feat/datalink-compact-reference-normalization
fix(datalink): compact reference and card object flattening in normalizeDatalinkRecord
2026-10-15 11:03:17 +08:00
gitea 2c32758e34 fix(datalink): compact reference and card object flattening in normalizeDatalinkRecord 2026-10-15 11:02:57 +08:00
yunyingk 1ee26d786a Merge pull request #101 from yunyingk/feat/platform-records-streaming-and-stats
feat(platform): add streaming ndjson, stats profiling, flat normalization, and public sdk surface
2026-10-15 11:01:23 +08:00
gitea 03195bbbe5 feat(platform): add streaming ndjson, stats profiling, flat normalization, and public sdk surface 2026-10-15 11:00:18 +08:00
yunyingk 26a6b7318c Merge pull request #100 from yunyingk/feat/platform-ledger-audit-and-batch-ops
feat(datalink,platform): add ledger math audit, continuity check, and in-line declarative batch update (Phase 4 & 5)
2026-10-14 22:26:27 +08:00
gitea cd0aa2bf41 feat(datalink,platform): add ledger math audit, continuity check, and in-line declarative batch update 2026-10-14 22:25:48 +08:00
yunyingk d3f7d3efbc Merge pull request #99 from yunyingk/feat/workflow-diff-suite
feat(workflow): add workflow snapshot diff and job execution diff suite (Phase 3)
2026-10-14 22:13:32 +08:00
gitea 2f94768184 feat(workflow): add workflow snapshot diff and job execution diff suite (Phase 3) 2026-10-14 22:13:05 +08:00
yunyingk d37ebb7fcd Merge pull request #98 from yunyingk/feat/flow-trace-diagnostics
feat(bill,flow): add unified bill trace and flow get diagnostic engine (Phase 2)
2026-10-14 22:01:35 +08:00
gitea ffec604ed9 feat(bill,flow): add unified bill trace and flow get diagnostic engine (Phase 2) 2026-10-14 22:00:55 +08:00
yunyingk 7891959853 Merge pull request #97 from yunyingk/feat/observable-ops-phase1
feat(ops): add dynamic staff link switching and deep failed job inspection (Phase 1)
2026-10-14 18:33:06 +08:00
gitea 0c6a3ee660 feat(workflow,corps): add dynamic staff link switching and deep failed job inspection 2026-10-14 18:32:14 +08:00
gitea 0499ccb2cc refactor(corps): normalize credential categories and format workflow history logs 2026-10-14 18:19:13 +08:00
yunyingk f91a80f9dd Merge pull request #96 from yunyingk/chore/legacy-cleanup
chore(legacy): remove ekb-mcp migration layer and other compat residue
2026-10-05 16:29:33 +08:00
gitea 95eb8ee676 chore(legacy): remove ekb-mcp migration layer, approval db compat shim, and stale daily notes
The ekb-mcp -> hose-use rename migration (LEGACY_* constants,
syncLegacyEnterprisesDir/syncLegacyGlobalConfig with 7-day grace
cleanup, dual-source enterprises resolution) has completed its job:
legacy data self-deleted on active machines years of grace ago.
Config resolution now returns the single primary
~/.config/hose-use source; startup no longer scans the legacy dir.

- core/config/loader.ts: drop legacy constants, sync functions, and
  LEGACY path from diagnostics candidates; loader.test.ts drops the
  three legacy-migration cases
- domains/approval/db.ts deleted: pure pass-through over core/db whose
  consumers (repository.ts) already call core/db directly; the four
  test files now import getDatabase/closeDatabase from core/db
- scripts/dev-hygiene.ts: drop the config.legacy finding and
  legacyConfig snapshot field
- docs/daily/* removed: Python-era (ekb-cli/ekb-mcp) notes describing
  commands and architecture that no longer exist (preserved in git
  history)

No behavior change on machines without legacy data: tsc clean,
313 tests pass (316 minus the 3 removed legacy cases).
2026-10-05 16:29:19 +08:00
64 changed files with 5507 additions and 597 deletions

No files matched your search

+3
View File
@@ -46,3 +46,6 @@ data/
# Local roadmaps & scratch notes
*.local.md
# Exports
exports/
-84
View File
@@ -1,84 +0,0 @@
# 2026-04-06 开发日报
> 截止提交:`792314a`(日报本身所在提交)
> 下一个实例可用 `git log 792314a` 查看全部历史,或 `git checkout 792314a` 还原此状态。
## 今日目标
从零搭建 ekb-cli,实现快报智能审核 Agent 的命令行管理,替代图形界面操作。
---
## 完成事项
### 一、项目骨架
- 初始化 Python 包结构(uv + pyproject.toml)
- 实现认证机制:自定义 Header(accesstoken / corpid / staffid),支持多企业存储与切换
- 解决 SOCKS5 代理兼容问题(补充 `httpx[socks]` 依赖)
### 二、ekb auth 命令组
| 命令 | 功能 |
|---|---|
| `ekb auth add` | 添加企业认证 |
| `ekb auth list` | 列出所有企业 |
| `ekb auth use` | 切换当前企业 |
| `ekb auth remove` | 删除企业 |
| `ekb auth whoami` | 查看当前企业 |
### 三、ekb agent 命令组
**Agent 管理**
| 命令 | 功能 |
|---|---|
| `ekb agent list` | 列出所有 Agent |
| `ekb agent get <id>` | 查看 Agent 详情(含四类条款、关联规则列表) |
| `ekb agent get <id> --full` | 不截断规则字段,提示完整文本总字符数 |
| `ekb agent update <id>` | patch 式修改(只改传入字段,其余保持原值) |
| `ekb agent logs` | 查看审核日志(待实现) |
**规则管理**
| 命令 | 功能 |
|---|---|
| `ekb agent rules` | 列出企业全部审核规则 |
| `ekb agent rules --level 严重` | 按风险等级筛选 |
| `ekb agent rules --full` | 不截断描述字段 |
| `ekb agent rule-get <编码或ID>` | 查看规则详情,含关联 Agent 列表 |
> 编码输入自适应:`1` / `01` / `0001` / `#0001` 均可识别,自动补零对齐。
### 四、ekb commands
`ekb commands` / `ekb commands agent` — 分层展示命令树,引导向下钻取。
### 五、API 封装(api/agent.py)
对接接口:
```
GET /api/engine/hab/agent/list
GET /api/engine/hab/agent/detail
POST /api/engine/hab/agent/save
GET /api/engine/hab/agent/rule/list
POST /api/engine/hab/agent/rule/save
POST /api/engine/hab/agent/rule/update
```
---
## 设计决策
- **截断提示展示字符总数**:CLI 是生产环境唯一入口(无 MCP),AI 读输出时需要知道是否值得拉全量数据,所以截断时提示完整文本总字符数而非截断标准。
- **patch 式 update**:先 GET 当前值,再合并传入字段,避免覆盖未传字段。
- **文档分层**:`CLAUDE.md`(项目级全图)→ `README.agent.md`(agent 语义/常量)→ `README.rule.md`(rule 语义/常量)。枚举常量不写在顶层文件。
---
## 待办
- [ ] `ekb agent logs` — 需抓包确认 API 结构
- [ ] 规则关联管理 — 给 Agent 增删关联规则(`ruleIds` 字段)
- [ ] `ekb rule update` — 修改规则内容(API 已封装,命令未实现)
-72
View File
@@ -1,72 +0,0 @@
# 2026-04-08 开发日报
> 截止提交:`c041966`(日报本身所在提交)
> 下一个实例可用 `git log c041966` 查看全部历史,或 `git checkout c041966` 还原此状态。
## 今日目标
在昨日基础上扩展写操作命令,完善 API 层架构。
---
## 完成事项
### 一、新增写操作命令
**规则管理**
| 命令 | 功能 |
|---|---|
| `ekb agent rule-create` | 新建审核规则(`--purpose` / `--desc` / `--level`) |
**Agent 管理**
| 命令 | 功能 |
|---|---|
| `ekb agent create` | 新建 Agent(支持全部字段,含关联规则 ID) |
| `ekb agent copy <id>` | 复制 Agent,名称自动追加「(副本)」,检测重名 |
| `ekb agent delete <id>` | 删除 Agent,方向键交互确认,不可恢复 |
### 二、API 层重构
- **拆分文件**:`api/agent.py`(Agent 接口)+ `api/rule.py`(Rule 接口)+ `api/schemas.py`(Pydantic 模型)
- **统一 re-export**:所有 commands 只从 `ekb_cli.api` 导入,内部拆分对上层透明
- **引入 Pydantic 校验**:所有接口响应经 `model_validate` 强制校验,字段变更时抛 `ValidationError` 精确定位,而非静默返回空值
- 新增接口:`GET /engine/hab/agent/checkName`、`GET /engine/hab/agent/active`
### 三、交互体验优化
- `ekb agent delete` 默认使用 `questionary` 方向键选择器,默认停在「取消」
- 非 tty 环境(管道/AI调用)自动降级为 `y/N` 文字输入;`--ai` 参数可强制指定;`--yes` 跳过确认
- 修复 `checkName` 接口语义反转 bug(`data=false` 表示名称可用)
### 四、文档补全
- 新增 `api/README.api.md`:三层架构说明、各接口签名、Pydantic 应对策略
- 补全 `README.agent.md`:`state` 枚举含义(0=启用 / 1=禁用 / 2=已删除)及对应接口
- 补全 `README.rule.md`:`rule-create` 命令速查
---
## 新增接口
```
GET /api/engine/hab/agent/checkName?name=xxx # 检查名称唯一性(data=false 表示可用)
GET /api/engine/hab/agent/active?id=xxx&state= # 变更 Agent 状态(0启用/1禁用/2删除)
```
---
## 设计决策
- **"删除"是状态变更**:快报无真正的 DELETE 接口,`state=2` 即为删除,通过 `/active` 接口实现。
- **Pydantic `extra="allow"`**:允许快报新增字段,但已知字段强制类型,兼顾前向兼容与变更感知。
- **`questionary` 仅在 tty 下启用**:`sys.stdin.isatty()` 自动检测,无需用户关心环境差异。
---
## 待办
- [ ] `ekb agent logs` — 需抓包确认 API 结构
- [ ] `ekb agent rule update` — 修改规则内容(API 已封装,命令未实现)
- [ ] `ekb agent rule delete` — 删除规则(接口待确认)
-107
View File
@@ -1,107 +0,0 @@
# 2026-05-18 开发日报
> 截止提交:`298e114`(当前 feature/workflow-control 分支)
> 下一个实例可用 `git log 298e114` 查看全部历史,或 `git checkout 298e114` 还原此状态。
## 今日目标
讨论并确定 ekb-mcp 项目的数据库方案。
---
## 讨论内容
### 一、数据库选型分析
**时间:2026-05-18 18:30**
针对项目是否需要数据库进行了深入讨论:
| 方案 | 优点 | 缺点 | 适用场景 |
|------|------|------|----------|
| PostgreSQL | 功能强大,支持复杂查询和并发 | 需要额外部署,运维复杂 | 多用户并发,复杂查询 |
| SQLite | 轻量级,嵌入式,无需额外服务 | 并发支持有限 | 单机部署,小规模应用 |
| 内存缓存 + JSON 文件 | 简单,无依赖,性能最高 | 重启后缓存丢失 | 单实例,数据量小 |
### 二、项目特点分析
**当前状态:**
- 配置存储在 `enterprises/*.json` 文件中
- 企业配置数量少(几个到几十个)
- 结构简单,只需按 ID 读取
- MCP 服务器单实例运行
**性能问题:**
- `loadCorpConfigs()` 每次调用都读取文件系统
- `getCorpTokens()` 每次调用都读取文件系统
- 没有任何缓存机制
- 大量重复查询会导致频繁的文件 I/O
### 三、中间件方案讨论
**时间:2026-05-18 19:00**
曾考虑实现存储中间件(Repository 模式),支持多种存储后端:
```
src/core/storage/
├── types.ts # 接口定义
├── memory.ts # 内存存储实现
├── sqlite.ts # SQLite 实现
├── postgres.ts # PostgreSQL 实现
└── factory.ts # 工厂函数
```
**反思:**
- 过度设计:对于当前项目来说太复杂
- 维护成本:需要维护多个存储后端的代码
- 依赖管理:需要处理可选依赖
- 学习成本:新开发者需要理解抽象层
### 四、最终决策
**时间:2026-05-18 19:30**
**选择方案:内存缓存 + JSON 文件**
**理由:**
1. **数据量小** - 企业配置通常不多,文件足够
2. **结构简单** - 不需要复杂查询,只需按 ID 读取
3. **运维简单** - 无额外依赖,易于备份和版本控制
4. **单实例运行** - MCP 服务器通常单实例,无需高并发支持
5. **性能足够** - 内存缓存可以解决重复查询的性能问题
**实现方案:**
```typescript
// 简单的内存缓存
const cache = new Map<string, CorpConfig>();
function getConfig(id: string): CorpConfig | undefined {
if (cache.has(id)) return cache.get(id);
const config = loadFromFile(id);
if (config) cache.set(id, config);
return config;
}
```
**清理工作:**
- 移除了 `src/core/storage/` 目录(过度设计的中间件方案)
- 移除了 `scripts/migrate-configs.ts`(不再需要的迁移脚本)
---
## 后续计划
1. 实现内存缓存机制,解决重复查询的性能问题
2. 保持现有 JSON 文件方案,简化架构
3. 如果未来数据量增长,再考虑 SQLite 作为轻量级方案
---
## 技术笔记
- 项目使用 TypeScript + Bun 运行时
- 配置文件位于 `enterprises/*.json`
- Token 缓存位于 `~/.cache/ekb-mcp/tokens.json`
- 当前分支:`feature/workflow-control`
- 最新提交:`298e114` - feat(platform): 新增工作流控制及辅助工具
+4
View File
@@ -3,6 +3,10 @@
"version": "0.8.13",
"module": "src/server.ts",
"type": "module",
"exports": {
".": "./src/server.ts",
"./sdk": "./src/sdk.ts"
},
"bin": {
"hose-use": "src/cli.ts",
"hose-aipro": "src/cli.ts"
-1
View File
@@ -39,7 +39,6 @@ describe("dev hygiene tooling", () => {
unreachableCommits: ["deadbeef"],
skill: {} as any,
binaries: [],
legacyConfig: {} as any,
};
const plan = buildCleanupPlan(snapshot, false);
expect(plan.map((action) => action.target)).toEqual(["/tmp/merged", "feat/merged"]);
-18
View File
@@ -90,12 +90,6 @@ interface HygieneSnapshot {
matches: boolean;
error?: string;
}>;
legacyConfig: {
enterprisesDir: string;
configFile: string;
enterprisesDirExists: boolean;
configFileExists: boolean;
};
}
export interface HygieneReport {
@@ -304,13 +298,6 @@ function inspectBinary(name: string): HygieneSnapshot["binaries"][number] {
}
}
function parseLegacyConfig(): HygieneSnapshot["legacyConfig"] {
const home = homedir();
const enterprisesDir = join(home, ".cache", "ekb-mcp", "enterprises");
const configFile = join(home, ".cache", "ekb-mcp", "config.json");
return { enterprisesDir, configFile, enterprisesDirExists: existsSync(enterprisesDir), configFileExists: existsSync(configFile) };
}
function collectSnapshot(): HygieneSnapshot {
return {
repository: parseRepository(),
@@ -319,7 +306,6 @@ function collectSnapshot(): HygieneSnapshot {
unreachableCommits: parseUnreachableCommits(),
skill: parseSkill(),
binaries: [inspectBinary("hose-use"), inspectBinary("hose-aipro")],
legacyConfig: parseLegacyConfig(),
};
}
@@ -370,10 +356,6 @@ function buildFindings(snapshot: HygieneSnapshot): Finding[] {
findings.push({ id: "binary.drift", level: "warning", message: `${binary.name} 全局版本与当前源码不一致`, details: binary, nextAction: "运行 bun run dev:override 同步全局开发版" });
}
}
const legacy = snapshot.legacyConfig;
if (legacy.enterprisesDirExists || legacy.configFileExists) {
findings.push({ id: "config.legacy", level: "warning", message: "发现旧版 ekb-mcp 配置路径;检查不会删除配置", details: legacy, nextAction: "先确认迁移结果,再按配置迁移策略清理" });
}
return findings;
}
+2
View File
@@ -179,6 +179,8 @@ hose-use app list # 查看应用管理列
hose-use app get 用车补贴 # 查看指定应用管理的配置与 Web 路由
hose-use platform list # 列出企业可见的自建应用平台
hose-use platform entities 新转转集团 # 查看自建应用下的业务对象与字段
hose-use platform records 新转转集团 合同 --stats # 宏观结构画像(总数/启停比率/重名数/编码规则聚类)
hose-use platform records 新转转集团 合同 --ndjson --flat # 万级海量数据 $O(1)$ 内存逐行流式输出 JSON Lines
hose-use platform records 新转转集团 合同 --all -o /tmp/records.json # 自动翻页导出全量业务对象记录
hose-use platform audit 新转转集团 合同 --check-fields="我方签约主体" # 一键巡检必填缺失、停用引用与跨表同步差异
hose-use platform record get <记录ID> # 免传应用/对象,直接按记录 ID 获取完整详情
+5 -5
View File
@@ -1,13 +1,13 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { runAiProCli } from "./aipro-cli.js";
import { closeApprovalDatabase, getApprovalDatabase } from "./domains/approval/db.js";
import { closeDatabase, getDatabase } from "./core/db/index.js";
import { ApprovalRepository } from "./domains/approval/repository.js";
import { getVersionInfo } from "./version.js";
describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
beforeEach(() => {
process.env.HOSE_APPROVAL_DB = ":memory:";
const db = getApprovalDatabase(":memory:");
const db = getDatabase(":memory:");
const repo = new ApprovalRepository(db);
// 预置规约规则
@@ -22,7 +22,7 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
});
afterEach(() => {
closeApprovalDatabase();
closeDatabase();
delete process.env.HOSE_APPROVAL_DB;
});
@@ -37,7 +37,7 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
});
test("完整闭环:bind 挂载 ➔ review 证据核验 ➔ decide 网关阻拦与裁决 ➔ logs 审计追溯", async () => {
const db = getApprovalDatabase(":memory:");
const db = getDatabase(":memory:");
const repo = new ApprovalRepository(db);
// 1. 创建审批会话
@@ -125,7 +125,7 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
});
test("门禁防御:单据无硬性或弹性违规时,尝试执行 reject 必须被网关阻断(禁止无因驳回)", async () => {
const db = getApprovalDatabase(":memory:");
const db = getDatabase(":memory:");
const repo = new ApprovalRepository(db);
const run = repo.createApprovalRun({
+1 -1
View File
@@ -253,7 +253,7 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
: "✅ 统一认证主账号自动换票"
: "⚪ 短期会话",
"Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接",
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent),
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent, hasOpenApi ? "openapi" : currentCorp?.source),
};
if (currentCorp?.session) {
+7 -2
View File
@@ -1,7 +1,7 @@
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createBillActionContext } from "./context.js";
import { handleApprove, handleReject, handleTransfer, handleAddNode, handleComment } from "./approve.js";
import { handleList, handleGet } from "./search.js";
import { handleList, handleGet, handleTrace } from "./search.js";
import { handleFlow, handleRisk, handleBudget } from "./flow.js";
import { handleRefs, handleRelations, handleAttachments, handleDownload } from "./related.js";
import { handleSchema, handleLink, handleSpec } from "./meta.js";
@@ -53,6 +53,11 @@ export async function handleBillCommand(
case "find":
return handleGet(ctx);
case "trace":
case "inspect":
case "diagnose":
return handleTrace(ctx);
case "schema":
case "schemas":
case "entities":
@@ -100,6 +105,6 @@ export async function handleBillCommand(
return handleSpec(ctx);
default:
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], trace <单号|ID>, spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
}
}
+101 -2
View File
@@ -1,6 +1,6 @@
import { getBillByCodeOrId, getBillRisk, searchAndFormatBills } from "../../../domains/bill/tools.js";
import { getBillByCodeOrId, getBillRisk, searchAndFormatBills, traceBillFlowDetail } from "../../../domains/bill/tools.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { printJson, printTable } from "../../printer.js";
import { printJson, printTable, printKeyValue } from "../../printer.js";
import type { CliResult } from "../../types.js";
import type { BillActionContext } from "./context.js";
@@ -198,3 +198,102 @@ export async function handleGet(ctx: BillActionContext): Promise<CliResult> {
exitCode: 0,
};
}
export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "target", "flowId"]);
if (!target) {
throw new Error("请提供要穿透诊断的单号或单据/流程 ID: hose-use bill trace <单号|ID> 或 hose-use flow get <单号|ID>");
}
const client = await ctx.getClient();
const report = await traceBillFlowDetail(client, corpId, target);
if (!report.found) {
if (runtime.jsonMode) {
return {
stdout: printJson(report, runtime.outputOptions),
stderr: "",
exitCode: 1,
};
}
return {
stdout: "",
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到匹配 [${target}] 的单据或审批流实例\n 诊断提示: ${report.diagnostic.advice}\n`,
exitCode: 1,
};
}
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
...report,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const approverNames = report.pendingApprovers
.map((p) => (p.name ? `${p.name}${p.code ? ` (${p.code})` : ""}` : p.id))
.filter(Boolean)
.join("、");
const lines: string[] = [
`====== 单据全域穿透诊断 [${report.billCode || report.target}] ======`,
printKeyValue({
"单据编号": report.billCode || "-",
"单据 ID": report.billId || "-",
"流程实例 (flowId)": report.flowId || "-",
"单据类型": report.specificationName
? `${report.specificationName}${report.specificationId ? ` (${report.specificationId})` : ""}`
: "-",
"单据标题": report.title || "-",
"提报人员": report.submitter
? `${report.submitter.name || "-"}${report.submitter.id ? ` (${report.submitter.id})` : ""}`
: "-",
"归属部门": report.department || "-",
"提报时间": report.submitDate || "-",
"单据金额": report.amount || "-",
"全局流转状态": `${report.state || "-"} (${report.rawState || "-"})`,
}),
"",
"── 🩺 待办与审批诊断 ──",
` 阶段判定 : ${report.diagnostic.stageLabel}`,
` 当前驻留节点: ${report.currentNode?.name || "-"}${report.currentNode?.id ? ` (${report.currentNode.id})` : ""}`,
` 待办处理人: ${approverNames || "(当前无待办审批人)"}`,
` 是否可审批: ${report.diagnostic.canApprove ? "✅ 是 (支持执行同意/驳回)" : "❌ 否 (当前不可审批)"}`,
` 诊断结论 : ${report.diagnostic.summary}`,
` 排障建议 : ${report.diagnostic.advice}`,
];
if (report.timeline.length > 0) {
lines.push("");
lines.push("── ⏱️ 审批流转历史轨迹 (Timeline) ──");
const timelineRows = report.timeline.map((item) => [
`#${item.index}`,
item.time || "-",
item.nodeName || "-",
item.operator?.name || item.operator?.id || (item.automatic ? "自动执行" : "-"),
item.action || item.state || "-",
item.comment ? (item.comment.length > 30 ? item.comment.slice(0, 30) + "..." : item.comment) : "-",
]);
lines.push(
printTable(
["#", "时间", "节点名称", "操作人", "动作", "审批意见"],
timelineRows
)
);
}
return {
stdout: `${lines.join("\n")}\n`,
stderr: "",
exitCode: 0,
};
}
+3 -3
View File
@@ -1,13 +1,13 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { runCli } from "../runner.js";
import { runAiProCli } from "../../aipro-cli.js";
import { closeApprovalDatabase, getApprovalDatabase } from "../../domains/approval/db.js";
import { closeDatabase, getDatabase } from "../../core/db/index.js";
import { ApprovalRepository } from "../../domains/approval/repository.js";
describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Context)", () => {
beforeEach(() => {
process.env.HOSE_APPROVAL_DB = ":memory:";
const db = getApprovalDatabase(":memory:");
const db = getDatabase(":memory:");
const repo = new ApprovalRepository(db);
repo.createRule({
@@ -21,7 +21,7 @@ describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Cont
});
afterEach(() => {
closeApprovalDatabase();
closeDatabase();
delete process.env.HOSE_APPROVAL_DB;
});
+1 -1
View File
@@ -135,7 +135,7 @@ export async function handleContextCommand(
` 当前操作员工 : ${corpStaffId}`,
` 员工真实姓名 : ${corpStaffName}`,
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source, hasOpenApiPersistentCredentials(currentCorp)) : "-"}`,
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent) : "-"}`,
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent, hasOpenApiPersistentCredentials(currentCorp) ? "openapi" : currentCorp.source) : "-"}`,
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
` 已配置企业总数: ${allCorps.length} 家 (有效: ${validCorps.length} 家, 已过期: ${expiredCorps.length} 家)`,
` AI PRO 规约库 : ${scopesStr}`,
+46
View File
@@ -344,6 +344,52 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
}
});
it("supports dynamic staff switching via corps link [corp] --staff=<id>", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = (async () =>
new Response(JSON.stringify({ items: [] }), {
status: 200,
headers: { "content-type": "application/json" },
})) as unknown as typeof fetch;
try {
const res = await handleCorpsCommand(
{
area: "corps",
action: "link",
args: ["corpAlpha"],
options: { staff: "alphaPhysicalId:NEW_ADMIN_STAFF" },
raw: ["corps", "link", "corpAlpha", "--staff=alphaPhysicalId:NEW_ADMIN_STAFF"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.preserveSensitiveStdout).toBe(true);
expect(res.stdout).toContain("NEW_ADMIN_STAFF");
expect(res.stdout).toContain("动态换签");
// --json 模式验证
const jsonRuntime = { ...searchRuntime, jsonMode: true };
const jsonRes = await handleCorpsCommand(
{
area: "corps",
action: "link",
args: ["corpAlpha"],
options: { staff: "alphaPhysicalId:NEW_ADMIN_STAFF", json: true },
raw: ["corps", "link", "corpAlpha", "--staff=alphaPhysicalId:NEW_ADMIN_STAFF", "--json"],
},
jsonRuntime
);
expect(jsonRes.exitCode).toBe(0);
const parsed = JSON.parse(jsonRes.stdout);
expect(parsed.dynamicStaff).toBe(true);
expect(parsed.staffId).toBe("alphaPhysicalId:NEW_ADMIN_STAFF");
} finally {
globalThis.fetch = originalFetch;
}
});
it("supports corps add-persistent --dry-run", async () => {
const res = await handleCorpsCommand(
{
+1 -1
View File
@@ -55,7 +55,7 @@ export async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime):
"员工姓名": current.staffName || current.session?.staffName || "-",
"凭证来源": formatSourceLabel(current.source, hasOpenApi),
"持久化状态": isPersistent ? (hasOpenApi ? `✅ 已配置 OpenAPI 持久化密钥 (${current.credentials.appKey})` : "✅ 已绑定统一认证主账号") : "⚪ 短期临时会话",
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime, isPersistent),
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime, isPersistent, hasOpenApi ? "openapi" : current.source),
"所属账号": current.accountId || "-",
"主站地址": current.baseUrl || "https://app.ekuaibao.com",
"适用上下文": "同时作为 hose-use 与 hose-aipro 的统一执行环境",
+4
View File
@@ -92,6 +92,8 @@ export function printCorpsHelp(): string {
switch <企业ID> 切换当前激活的工作企业 (别名: use)
current 查看当前激活的企业配置与凭证详情
link [企业ID|名称] 生成企业合思 Web 免密登录直达链接 (别名: hose-link)
[--staff=<姓名|手机号|ID>] 动态指定换签身份
[--persist] 将新身份持久化为企业默认操作人
add-link <URL> 从第三方协助/免密链接导入企业凭证(默认自动探测并持久化 OpenAPI 密钥)
add-persistent 通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业 (别名: add-hose-persistent)
extract-keys <URL> 从协助链接提取企业 OpenAPI 密钥(附加 --save 可直接持久化保存)
@@ -108,6 +110,8 @@ export function printCorpsHelp(): string {
hose-use corps search 17718556446
hose-use corps switch ID01MCcOgJl1td
hose-use corps link 新转转集团
hose-use corps link 新转转集团 --staff="合思-姜尧"
hose-use corps link 新转转集团 --staff="17865187018" --persist
hose-use corps add-link "<url>" --elevate --yes
hose-use corps add-persistent --app-key=... --app-security=... --yes
`.trim();
+117 -2
View File
@@ -1,6 +1,21 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
import { getCorpProvisionalAuthLink, hasOpenApiPersistentCredentials, importFromLink } from "../../../core/auth/login.js";
import {
getCorpProvisionalAuthLink,
hasOpenApiPersistentCredentials,
importFromLink,
} from "../../../core/auth/login.js";
import {
DEFAULT_EKB_BASE_URL,
fetchHoseOpenApiAccessToken,
fetchHoseStaffDetails,
getCorpOpenApiCredentials,
listHoseStaffsByOpenApi,
normalizeBaseUrl,
} from "../../../core/auth/openapi-v1.js";
import { searchStaffs } from "../../../domains/contact/tools.js";
import { NotFoundError, ValidationError } from "../../../core/errors.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { resolveWritableEnterprisesDir } from "../../../core/config/loader.js";
import { stringOption, booleanOption } from "../../parser.js";
import { prompt } from "../../helpers.js";
@@ -9,6 +24,90 @@ import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mu
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveTargetCorpByArgOrContext } from "./shared.js";
export async function resolveStaffForLink(
corp: CorpConfig,
staffQuery: string
): Promise<{ staffId: string; staffName?: string }> {
const q = staffQuery.trim();
if (!q) {
throw new ValidationError("员工检索条件不能为空");
}
const corpId = corp.corpId || corp.credentials.corpId;
// 1. 如果输入本身就是完整 staffId 或 ID01 开头的工号
if (q.includes(":") || (q.startsWith("ID01") && !q.includes(" "))) {
const fullId = q.includes(":") ? q : `${corpId}:${q}`;
const openApiCreds = getCorpOpenApiCredentials(corp);
if (openApiCreds) {
try {
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
const openapiToken = await fetchHoseOpenApiAccessToken({
appKey: openApiCreds.appKey,
appSecurity: openApiCreds.appSecurity,
baseUrl,
});
const details = await fetchHoseStaffDetails(baseUrl, openapiToken, [fullId]);
if (details.length > 0 && details[0]?.name) {
return { staffId: fullId, staffName: details[0].name };
}
} catch {
// fallback to using fullId
}
}
return { staffId: fullId };
}
// 2. 若企业已配置 OpenAPI 密钥,优先在管理员(admin 角色)中查找
const openApiCreds = getCorpOpenApiCredentials(corp);
if (openApiCreds) {
try {
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
const staffRes = await listHoseStaffsByOpenApi({
appKey: openApiCreds.appKey,
appSecurity: openApiCreds.appSecurity,
domain: baseUrl,
role: "admin",
});
// 优先级 1: 姓名或手机号精确匹配
const exactMatch = staffRes.staffs.find(
(s) => s.name?.trim() === q || s.cellphone?.trim() === q || s.id === q
);
if (exactMatch) {
return { staffId: exactMatch.id, staffName: exactMatch.name };
}
// 优先级 2: 姓名包含模糊匹配
const fuzzyMatch = staffRes.staffs.find((s) => s.name && s.name.includes(q));
if (fuzzyMatch) {
return { staffId: fuzzyMatch.id, staffName: fuzzyMatch.name };
}
} catch {
// 容错并回退至通讯录查询
}
}
// 3. 通道 3: 通讯录常规检索
try {
const matchedStaffs = await searchStaffs(corp, { keyword: q, limit: 10 });
if (matchedStaffs.length > 0) {
const exact = matchedStaffs.find(
(s) => s.name?.trim() === q || s.cellphone?.trim() === q || s.id === q
);
const chosen = exact || matchedStaffs[0];
const normalizedId = chosen.id.includes(":") ? chosen.id : `${corpId}:${chosen.id}`;
return { staffId: normalizedId, staffName: chosen.name };
}
} catch {
// 忽略通讯录未配置异常
}
throw new NotFoundError(
`未在企业 [${corp.name}] 中找到匹配 "${q}" 的员工或管理员。请核对姓名/手机号,或直接传入完整员工工号 (staffId)。`
);
}
export async function handleGenerateCorpLink(
parsed: CliParsedArgs,
runtime: CliRuntime
@@ -27,13 +126,26 @@ export async function handleGenerateCorpLink(
stringOption(parsed.options, ["expires-in", "expiresIn", "expire", "expires", "ttl"]) || 7200;
const pageType = stringOption(parsed.options, ["page-type", "pageType"]) || "home";
const force = booleanOption(parsed.options, ["force", "refresh", "f"]);
const staffInput = stringOption(parsed.options, ["staff", "user", "operator"]);
const persistStaff = booleanOption(parsed.options, ["persist", "save", "save-staff"]);
let resolvedStaff: { staffId: string; staffName?: string } | undefined;
if (staffInput) {
resolvedStaff = await resolveStaffForLink(targetCorp, staffInput);
}
const linkRes = await getCorpProvisionalAuthLink(targetCorp, {
expiresIn,
pageType,
force,
staffId: resolvedStaff?.staffId,
staffName: resolvedStaff?.staffName,
persistStaff,
});
const isSwitched = Boolean(resolvedStaff);
const persistSaved = Boolean(persistStaff && isSwitched);
if (runtime.jsonMode) {
return {
stdout: printJson(
@@ -48,6 +160,8 @@ export async function handleGenerateCorpLink(
token: linkRes.token,
persistent: linkRes.persistent,
method: linkRes.method,
dynamicStaff: isSwitched,
persisted: persistSaved,
},
runtime.outputOptions
),
@@ -60,9 +174,10 @@ export async function handleGenerateCorpLink(
const lines = [
`====== 合思企业 Web 免密登录直达链接 ======`,
` 企业名称 : ${linkRes.corpName} (${linkRes.corpId})`,
` 操作人身份: ${linkRes.staffName ? `${linkRes.staffName} (${linkRes.staffId})` : linkRes.staffId}`,
` 操作人身份: ${linkRes.staffName ? `${linkRes.staffName} (${linkRes.staffId})` : linkRes.staffId}${isSwitched ? " (🔄 动态换签)" : ""}`,
` 签发通道 : ${linkRes.method === "provisional-openapi" ? "OpenAPI 持久化密钥动态签发 (getProvisionalAuth)" : "当前有效会话令牌拼装 (session-token)"}`,
` 过期时间 : ${linkRes.expiresAt}`,
...(persistSaved ? [` 配置持久化: ✅ 已保存为该企业默认操作人`] : []),
` 直达链接 :`,
` ${linkRes.url}`,
``,
+25 -17
View File
@@ -1,6 +1,6 @@
import { canRefreshCorpAccessToken } from "../../../core/auth/login.js";
import { stringOption } from "../../parser.js";
import { printJson, printTable, formatExpiresAt } from "../../printer.js";
import { printJson, printTable, formatExpiresAt, formatSourceLabel } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
const FIELD_LABEL_MAP: Record<string, string> = {
@@ -30,19 +30,26 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
: null;
const normalizedCorps = rawCorps
? rawCorps.map((c) => ({
id: c.id,
name: c.name,
corpId: c.corpId || c.credentials?.corpId || c.id,
staffId: c.staffId || c.credentials?.staffId || "",
staffName: c.staffName || c.session?.staffName || "",
accountId: c.accountId || "",
source: c.source || "manual",
baseUrl: c.baseUrl,
current: c.id === runtime.selectedCorp?.id,
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
persistent: canRefreshCorpAccessToken(c),
}))
? rawCorps.map((c) => {
const hasOpenApi = Boolean(
(c.credentials?.appKey || c.auth?.appKey) &&
(c.credentials?.appSecurity || c.auth?.appSecurity)
);
return {
id: c.id,
name: c.name,
corpId: c.corpId || c.credentials?.corpId || c.id,
staffId: c.staffId || c.credentials?.staffId || "",
staffName: c.staffName || c.session?.staffName || "",
accountId: c.accountId || "",
source: c.source || "manual",
baseUrl: c.baseUrl,
current: c.id === runtime.selectedCorp?.id,
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
persistent: canRefreshCorpAccessToken(c),
hasOpenApi,
};
})
: runtime.corpContext.listCorps().map((c) => ({
id: c.id,
name: c.name,
@@ -55,6 +62,7 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
current: c.current || c.id === runtime.selectedCorp?.id,
expiresAt: c.expiresAt,
persistent: c.persistent,
hasOpenApi: c.hasOpenApi,
}));
const matches: Array<typeof normalizedCorps[number] & { matchedFields: string[] }> = [];
@@ -134,7 +142,7 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
m.staffName ? (m.matchedFields.includes("staffName") ? `[${m.staffName}]` : m.staffName) : "-",
m.accountId ? (m.matchedFields.includes("accountId") ? `[${m.accountId}]` : m.accountId) : "-",
matchLabels.map((l) => `命中${l}`).join(", "),
formatExpiresAt(m.expiresAt, m.persistent),
formatExpiresAt(m.expiresAt, m.persistent, m.hasOpenApi ? "openapi" : m.source),
];
});
@@ -176,8 +184,8 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
c.id,
c.name,
c.staffId,
c.source || "manual",
formatExpiresAt(c.expiresAt, c.persistent),
formatSourceLabel(c.source, c.hasOpenApi),
formatExpiresAt(c.expiresAt, c.persistent, c.hasOpenApi ? "openapi" : c.source),
c.accountId || "-",
]);
+248
View File
@@ -0,0 +1,248 @@
import { describe, expect, it, spyOn, afterEach } from "bun:test";
import { handleFlowCommand } from "./flow.js";
import { handleBillCommand } from "./bill/index.js";
import { findCommandByArea } from "../registry.js";
import * as sessionModule from "../../core/http/session-client.js";
import type { CliRuntime } from "../types.js";
import type { CorpConfig } from "../../core/config/types.js";
const mockCorp: CorpConfig = {
id: "corp-test-1",
name: "测试企业",
baseUrl: "https://app.ekuaibao.com",
source: "openapi",
credentials: {
accessToken: "mock-token",
corpId: "corp-test-1",
staffId: "corp-test-1:STAFF_TEST",
},
};
const mockRuntime: CliRuntime = {
corpContext: {
listCorps: () => [mockCorp],
getCurrent: () => mockCorp,
switchCorp: () => true,
resolve: () => mockCorp,
} as any,
selectedCorp: mockCorp,
jsonMode: false,
outputOptions: {},
};
describe("CLI - flow & trace 全域透视与穿透诊断命令族", () => {
let spies: ReturnType<typeof spyOn>[] = [];
afterEach(() => {
for (const spy of spies) {
spy.mockRestore();
}
spies = [];
});
it("registry 正确注册 flow 命令与 trace 别名", () => {
const flowDef = findCommandByArea("flow");
expect(flowDef).toBeDefined();
expect(flowDef?.area).toBe("flow");
expect(flowDef?.aliases).toContain("trace");
const traceDef = findCommandByArea("trace");
expect(traceDef).toBeDefined();
expect(traceDef?.area).toBe("flow");
});
it("未选中企业时返回错误并提示切换企业", async () => {
const res = await handleFlowCommand(
{
area: "flow",
action: "get",
args: ["ZJ-001"],
options: {},
raw: ["flow", "get", "ZJ-001"],
},
{ ...mockRuntime, selectedCorp: null }
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未选中企业");
});
it("hose-use flow --help 输出帮助信息", async () => {
const res = await handleFlowCommand(
{
area: "flow",
action: undefined,
args: [],
options: { help: true },
raw: ["flow", "--help"],
},
mockRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("hose-use flow - 审批流全域透视与穿透诊断命令族");
expect(res.stdout).toContain("hose-use flow get <单号|ID>");
});
it("hose-use flow <单号> (位置参数) 自动识别并穿透诊断", async () => {
const mockRawFlow = {
id: "backlog-1",
state: "APPROVING",
flowId: {
id: "flow-1",
state: "APPROVING",
form: {
code: "ZJ-20261014-001",
title: "转转合同付款",
payMoney: "12500.00",
submitterId: { id: "u1", name: "张敏" },
expenseDepartment: { name: "财务部" },
},
plan: {
nodes: [
{ id: "n1", name: "出纳打款", state: "APPROVING", approverId: { id: "u2", name: "李出纳" } },
],
},
logs: [],
},
};
const mockClient = {
post: async () => new Response(JSON.stringify({ value: mockRawFlow })),
} as any;
spies.push(spyOn(sessionModule, "createSessionClient").mockResolvedValue(mockClient));
const res = await handleFlowCommand(
{
area: "flow",
action: "zj-20261014-001",
args: [],
positional: ["flow", "ZJ-20261014-001"],
options: {},
raw: ["flow", "ZJ-20261014-001"],
},
mockRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("单据全域穿透诊断 [ZJ-20261014-001]");
expect(res.stdout).toContain("提报人员");
expect(res.stdout).toContain("张敏");
expect(res.stdout).toContain("待办处理人: 李出纳");
expect(res.stdout).toContain("出纳打款");
});
it("hose-use flow get <单号> --json 结构化输出", async () => {
const mockRawFlow = {
id: "backlog-2",
state: "PAYING",
flowId: {
id: "flow-2",
state: "PAYING",
form: {
code: "ZJ-20261014-002",
title: "资金调拨",
},
plan: {
nodes: [
{ id: "n1", name: "出纳打款", state: "APPROVING" },
],
},
logs: [],
},
};
const mockClient = {
post: async () => new Response(JSON.stringify({ value: mockRawFlow })),
} as any;
spies.push(spyOn(sessionModule, "createSessionClient").mockResolvedValue(mockClient));
const res = await handleFlowCommand(
{
area: "flow",
action: "get",
args: ["ZJ-20261014-002"],
positional: ["flow", "get", "ZJ-20261014-002"],
options: { json: true },
raw: ["flow", "get", "ZJ-20261014-002", "--json"],
},
{ ...mockRuntime, jsonMode: true }
);
expect(res.exitCode).toBe(0);
const parsed = JSON.parse(res.stdout);
expect(parsed.found).toBe(true);
expect(parsed.billCode).toBe("ZJ-20261014-002");
expect(parsed.diagnostic.stage).toBe("PAYING");
expect(parsed.diagnostic.canApprove).toBe(false);
expect(parsed.diagnostic.advice).toContain("400");
});
it("hose-use bill trace <单号> 平滑集成并完成诊断", async () => {
const mockRawFlow = {
id: "backlog-3",
state: "APPROVING",
flowId: {
id: "flow-3",
state: "APPROVING",
form: {
code: "BX-999",
title: "日常差旅报销",
},
plan: {
nodes: [
{ id: "n1", name: "总监审批", state: "APPROVING" },
],
},
logs: [],
},
};
const mockClient = {
post: async () => new Response(JSON.stringify({ value: mockRawFlow })),
} as any;
spies.push(spyOn(sessionModule, "createSessionClient").mockResolvedValue(mockClient));
const res = await handleBillCommand(
{
area: "bill",
action: "trace",
args: ["BX-999"],
positional: ["bill", "trace", "BX-999"],
options: {},
raw: ["bill", "trace", "BX-999"],
},
mockRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("单据全域穿透诊断 [BX-999]");
expect(res.stdout).toContain("总监审批");
expect(res.stdout).toContain("是否可审批: ✅ 是");
});
it("未找到单据时返回 exitCode 1 与排障建议", async () => {
const mockClient = {
post: async () => new Response(JSON.stringify({ items: [] })),
} as any;
spies.push(spyOn(sessionModule, "createSessionClient").mockResolvedValue(mockClient));
const res = await handleFlowCommand(
{
area: "flow",
action: "get",
args: ["UNKNOWN-BILL"],
positional: ["flow", "get", "UNKNOWN-BILL"],
options: {},
raw: ["flow", "get", "UNKNOWN-BILL"],
},
mockRuntime
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("[NOT FOUND]");
expect(res.stderr).toContain("诊断提示");
});
});
+99
View File
@@ -0,0 +1,99 @@
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { createBillActionContext } from "./bill/context.js";
import { handleTrace, handleList } from "./bill/search.js";
import { handleFlow, handleRisk } from "./bill/flow.js";
import { handleApprove, handleReject } from "./bill/approve.js";
function printFlowHelp(): string {
return [
"hose-use flow - 审批流全域透视与穿透诊断命令族",
"",
"用法:",
" hose-use flow <单号|ID> 等价于 flow get/trace,快速透视单据流转与诊断待办",
" hose-use flow get <单号|ID> 深度穿透单据全貌、当前驻留节点与 400 待办根因诊断",
" hose-use flow trace <单号|ID> (别名) 同 flow get",
" hose-use flow history <单号|ID> 查看审批历史流转时间线与后续节点",
" hose-use flow risk <单号|ID> 查看费控与合规风控诊断",
" hose-use flow list [options] 列出当前待审批/已审批单据流",
" hose-use flow approve <单号|ID> 执行审批同意 (受 --dry-run 与 --yes 约束)",
" hose-use flow reject <单号|ID> 执行审批驳回 (受 --dry-run 与 --yes 约束)",
"",
"选项:",
" --corp=<id> 指定操作企业 (默认激活企业)",
" --json 以 JSON 结构化格式输出诊断数据",
" --verbose 显示完整调试信息",
" -h, --help 显示帮助信息",
].join("\n");
}
export async function handleFlowCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
if (parsed.options.help || parsed.action === "help") {
return {
stdout: printFlowHelp() + "\n",
stderr: "",
exitCode: 0,
};
}
const corp = runtime.selectedCorp;
if (!corp) {
return {
stdout: "",
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
exitCode: 1,
};
}
const action = parsed.action?.toLowerCase();
const args = [...parsed.args];
// 1. 无动作无参数且无 --code/--id 选项时,默认展示列表
if (!action && args.length === 0 && !parsed.options.code && !parsed.options.id) {
const ctx = createBillActionContext(parsed, runtime);
return handleList(ctx);
}
// 2. 识别透视与穿透类动词
const flowTraceActions = new Set(["get", "trace", "inspect", "diagnose", "show", "find"]);
if (action && flowTraceActions.has(action)) {
const ctx = createBillActionContext(parsed, runtime);
return handleTrace(ctx);
}
// 3. 识别其他常用审批流动作
const flowOtherActions = new Set(["history", "records", "timeline", "risk", "list", "search", "approve", "agree", "reject", "deny"]);
if (action && flowOtherActions.has(action)) {
const ctx = createBillActionContext(parsed, runtime);
switch (action) {
case "history":
case "records":
case "timeline":
return handleFlow(ctx);
case "risk":
return handleRisk(ctx);
case "list":
case "search":
return handleList(ctx);
case "approve":
case "agree":
return handleApprove(ctx);
case "reject":
case "deny":
return handleReject(ctx);
}
}
// 4. 用户直接输入单号:hose-use flow <单号|ID>
// 从原始 positional[1] 获取未经 lowercase 转换的原始单号/ID
const rawTarget = parsed.positional?.[1] || parsed.action;
const rewrittenParsed: CliParsedArgs = {
...parsed,
action: "trace",
args: [rawTarget!, ...args],
};
const ctx = createBillActionContext(rewrittenParsed, runtime);
return handleTrace(ctx);
}
+259
View File
@@ -255,4 +255,263 @@ describe("CLI - platform 命令与 record 动作", () => {
expect(res.stdout).toContain("Dry-Run 预览");
expect(editSpy).not.toHaveBeenCalled();
});
it("platform records 支持 --sum 数学核算与 --group-by 分组统计", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue({
...mockEntity,
fields: [
{ name: "fee", label: "租赁费用", type: "money" },
{ name: "status", label: "状态", type: "text" },
],
} as any));
spies.push(
spyOn(services, "fetchAllEntityRecords").mockResolvedValue({
data: [
{ id: "1", fee: 1000, status: "A" },
{ id: "2", fee: 2000, status: "A" },
{ id: "3", fee: 3000, status: "B" },
],
total: 3,
actions: [],
components: [],
path: null,
template: null,
})
);
const res = await handlePlatformCommand(
{
area: "platform",
action: "records",
args: ["platform-1", "entity-1"],
options: { sum: "租赁费用", "group-by": "状态" },
raw: ["platform", "records", "platform-1", "entity-1", "--sum=租赁费用", "--group-by=状态"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("台账数学聚合核算");
expect(res.stdout).toContain("总合计 (SUM)");
expect(res.stdout).toContain("6000");
expect(res.stdout).toContain("按 [状态] 分组统计");
});
it("platform audit 支持 --check-continuous 与 --expect 基线离群诊断", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue({
...mockEntity,
fields: [
{ name: "seq", label: "摊销序号", type: "number" },
{ name: "fee", label: "租赁费用", type: "money" },
],
} as any));
spies.push(
spyOn(services, "fetchAllEntityRecords").mockResolvedValue({
data: [
{ id: "1", seq: 1, fee: 78787.55 },
{ id: "2", seq: 3, fee: 0 },
],
total: 2,
actions: [],
components: [],
path: null,
template: null,
})
);
const res = await handlePlatformCommand(
{
area: "platform",
action: "audit",
args: ["platform-1", "entity-1"],
options: { "check-continuous": "摊销序号", expect: "租赁费用 ~= 78787.55" },
raw: ["platform", "audit", "platform-1", "entity-1", "--check-continuous=摊销序号", "--expect=租赁费用 ~= 78787.55"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("台账序号连续性体检");
expect(res.stdout).toContain("断层缺失期数 (MISSING)");
expect(res.stdout).toContain("缺少 [2]");
expect(res.stdout).toContain("基线离群异常核对");
expect(res.stdout).toContain("偏离差额");
});
it("platform update 支持 --where 声明式筛选与 --set 原地修改(含 --dry-run 与 --yes)", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue({
...mockEntity,
fields: [
{ name: "fee", label: "租赁费用", type: "money" },
{ name: "status", label: "状态", type: "text" },
],
} as any));
spies.push(
spyOn(services, "fetchAllEntityRecords").mockResolvedValue({
data: [
{ id: "r-1", fee: 0, status: "PENDING" },
{ id: "r-2", fee: 78787.55, status: "DONE" },
],
total: 2,
actions: [],
components: [],
path: null,
template: null,
})
);
spies.push(
spyOn(api, "getRecordDetail").mockResolvedValue({
dataLink: { id: "r-1", active: true, fee: 0, status: "PENDING" },
})
);
const editSpy = spyOn(api, "editRecord").mockResolvedValue({ id: "r-1" } as any);
spies.push(editSpy);
// 1. Dry-run 模式测试
const dryRes = await handlePlatformCommand(
{
area: "platform",
action: "update",
args: ["platform-1", "entity-1"],
options: { where: "租赁费用 == 0", set: "租赁费用 = 78787.55", "dry-run": true },
raw: ["platform", "update", "platform-1", "entity-1", "--where=租赁费用 == 0", "--set=租赁费用 = 78787.55", "--dry-run"],
},
dummyRuntime
);
expect(dryRes.exitCode).toBe(0);
expect(dryRes.stdout).toContain("Dry-Run 预览");
expect(dryRes.stdout).toContain("r-1");
expect(editSpy).not.toHaveBeenCalled();
// 2. 真实确认执行测试 (--yes)
const execRes = await handlePlatformCommand(
{
area: "platform",
action: "update",
args: ["platform-1", "entity-1"],
options: { where: "租赁费用 == 0", set: "租赁费用 = 78787.55", yes: true },
raw: ["platform", "update", "platform-1", "entity-1", "--where=租赁费用 == 0", "--set=租赁费用 = 78787.55", "--yes"],
},
dummyRuntime
);
expect(execRes.exitCode).toBe(0);
expect(execRes.stdout).toContain("已执行");
expect(editSpy).toHaveBeenCalled();
});
it("platform records 支持 --stats 画像统计(计算状态、重名与编码聚类)", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
spies.push(
spyOn(api, "searchEntityRecords").mockResolvedValue({
total: 3,
data: [
{ id: "r-1", dataLink: { id: "r-1", name: "场地A", code: "0-DT-2026-month-1", active: true } },
{ id: "r-2", dataLink: { id: "r-2", name: "场地A", code: "0-DT-2026-period-1", active: false } },
{ id: "r-3", dataLink: { id: "r-3", name: "场地B", code: "0-DT-2026-month-2", active: true } },
],
actions: [],
components: [],
path: null,
template: null,
})
);
// 1. 命令行表格输出测试
const textRes = await handlePlatformCommand(
{
area: "platform",
action: "records",
args: ["platform-1", "entity-1"],
options: { stats: true },
raw: ["platform", "records", "platform-1", "entity-1", "--stats"],
},
dummyRuntime
);
expect(textRes.exitCode).toBe(0);
expect(textRes.stdout).toContain("宏观状态与数据画像");
expect(textRes.stdout).toContain("启用 2 条");
expect(textRes.stdout).toContain("停用 1 条");
expect(textRes.stdout).toContain("N-DT-N-month-N");
// 2. JSON 结构化输出测试
const jsonRes = await handlePlatformCommand(
{
area: "platform",
action: "records",
args: ["platform-1", "entity-1"],
options: { stats: true },
raw: ["platform", "records", "platform-1", "entity-1", "--stats"],
},
{ ...dummyRuntime, jsonMode: true }
);
expect(jsonRes.exitCode).toBe(0);
const parsed = JSON.parse(jsonRes.stdout);
expect(parsed.total).toBe(3);
expect(parsed.activeCount).toBe(2);
expect(parsed.inactiveCount).toBe(1);
expect(parsed.duplicateNamesCount).toBe(1);
});
it("platform records 支持 --ndjson 流式逐行下发与 --flat 归一化", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
spies.push(
spyOn(api, "searchEntityRecords").mockResolvedValue({
total: 2,
data: [
{
id: "r-1",
dataLink: { id: "r-1", name: "项目1", code: "P1", active: true, customField: "测试值" },
},
{
id: "r-2",
dataLink: { id: "r-2", name: "项目2", code: "P2", active: false, customField: "停用值" },
},
],
actions: [],
components: [],
path: null,
template: null,
})
);
const streamedLines: string[] = [];
const writeSpy = spyOn(process.stdout, "write").mockImplementation((str: any) => {
streamedLines.push(String(str));
return true;
});
spies.push(writeSpy);
const streamRes = await handlePlatformCommand(
{
area: "platform",
action: "records",
args: ["platform-1", "entity-1"],
options: { ndjson: true },
raw: ["platform", "records", "platform-1", "entity-1", "--ndjson"],
},
dummyRuntime
);
expect(streamRes.exitCode).toBe(0);
expect(streamedLines.length).toBe(2);
const row1 = JSON.parse(streamedLines[0].trim());
expect(row1.id).toBe("r-1");
expect(row1.name).toBe("项目1");
expect(row1.code).toBe("P1");
expect(row1.active).toBe(true);
expect(row1.fields["自定义字段"]).toBe("测试值");
});
});
+6 -1
View File
@@ -28,7 +28,9 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
case "fields": return handleSchema(parsed, runtime);
case "records":
case "data":
case "search": return handleRecords(parsed, runtime);
case "search":
case "stats":
case "profile": return handleRecords(parsed, runtime);
case "audit":
case "check":
case "health": return handleAudit(parsed, runtime);
@@ -38,6 +40,9 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
case "record-edit":
case "record-batch-edit":
case "batch-edit":
case "record-update":
case "update":
case "batch-update":
case "record-recompute": return handleRecordAction(parsed, runtime);
case "permissions":
case "permission":
+59 -17
View File
@@ -4,7 +4,9 @@ import {
buildSafeRecordEditPayload,
editRecord,
fetchAllEntityRecords,
filterRecordsByPredicate,
getRecordDetail,
parseSetClause,
recomputeRecordLedger,
toggleRecordState,
type BatchEditTargetItem,
@@ -137,20 +139,22 @@ async function handleBatchEdit(
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
if (!resolved.entity) {
throw new Error(
"用法: hose-use platform record batch-edit <应用> <业务对象> (--ids=<id1,id2> | --filter=<expr>) (--data='<json>' | --file=<patch.json>) [--concurrency=8] [--dry-run] [--yes]"
"用法: hose-use platform record batch-edit <应用> <业务对象> (--where='<expr>' | --ids=<id1,id2> | --filter=<expr>) (--set='<expr>' | --data='<json>' | --file=<patch.json>) [--concurrency=8] [--dry-run] [--yes]"
);
}
const idsOpt = stringOption(parsed.options, ["ids", "id"]);
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]);
const whereClause = stringOption(parsed.options, ["where"]);
const setClause = stringOption(parsed.options, ["set"]);
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
const filePath = stringOption(parsed.options, ["file", "f"]);
const concurrency = numberOption(parsed.options, ["concurrency", "c"], 8);
const activeOpt =
parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
if (!dataStr && !filePath) {
throw new Error("请通过 --data='<json>' 或 --file=<patch.json> 提供要批量更新的字段内容");
if (!dataStr && !filePath && !setClause) {
throw new Error("请通过 --set='字段=值'、--data='<json>' 或 --file=<patch.json> 提供要批量更新的字段内容");
}
requireMutationConfirmation(
@@ -170,7 +174,9 @@ async function handleBatchEdit(
}
let uniformPatch: Record<string, unknown> | undefined;
if (dataStr) {
if (setClause) {
uniformPatch = parseSetClause(setClause, resolved.entity);
} else if (dataStr) {
try {
uniformPatch = JSON.parse(dataStr) as Record<string, unknown>;
} catch {
@@ -223,14 +229,18 @@ async function handleBatchEdit(
throw new Error("未解析到有效的批量更新内容");
}
let recordIds = splitFields(idsOpt);
if (recordIds.length === 0 && filterBy) {
if (recordIds.length === 0 && (whereClause || filterBy)) {
const page = await fetchAllEntityRecords(
resolved.clients.ekbClient,
resolved.corpId,
resolved.entity.id,
{ filterBy }
);
recordIds = page.data
let records = page.data;
if (whereClause) {
records = filterRecordsByPredicate(records, whereClause, resolved.entity);
}
recordIds = records
.map((r) => {
const dl =
r.dataLink && typeof r.dataLink === "object"
@@ -241,7 +251,14 @@ async function handleBatchEdit(
.filter(Boolean);
}
if (recordIds.length === 0) {
throw new Error("请通过 --ids=<id1,id2,...> 或 --filter=<表达式> 指定要批量更新的目标记录");
if (whereClause) {
return {
stdout: `未找到符合条件 [--where="${whereClause}"] 的记录,无需更新。\n`,
stderr: "",
exitCode: 0,
};
}
throw new Error("请通过 --where=<条件>、--ids=<id1,id2,...> 或 --filter=<表达式> 指定要批量更新的目标记录");
}
for (const id of recordIds) {
targets.push({
@@ -289,14 +306,23 @@ async function handleBatchEdit(
item.error || "-",
]);
const outputLines = [
`====== 批量安全编辑业务对象记录 (${dryRun ? "Dry-Run 预览" : "已执行"}) ======`,
`应用: ${resolved.platform.name} (${resolved.platform.id}) | 业务对象: ${resolved.entity.name} (${resolved.entity.id})`,
`总计: ${results.length} | 成功/预览: ${succeeded} | 失败: ${failed}`,
];
if (uniformPatch) {
outputLines.push(`应用变更 Patch: ${JSON.stringify(uniformPatch)}`);
}
outputLines.push(printTable(["#", "记录 ID", "状态", "合并后字段数", "错误信息"], rows));
if (dryRun) {
outputLines.push("");
outputLines.push("💡 这是 Dry-Run 预演模式,数据未发生任何改变。如需真正执行修改,请追加 --yes(或 --confirm)参数。");
}
outputLines.push("");
return {
stdout: [
`====== 批量安全编辑业务对象记录 (${dryRun ? "Dry-Run 预览" : "已执行"}) ======`,
`应用: ${resolved.platform.name} (${resolved.platform.id}) | 业务对象: ${resolved.entity.name} (${resolved.entity.id})`,
`总计: ${results.length} | 成功/预览: ${succeeded} | 失败: ${failed}`,
printTable(["#", "记录 ID", "状态", "合并后字段数", "错误信息"], rows),
"",
].join("\n"),
stdout: outputLines.join("\n"),
stderr: "",
exitCode: failed > 0 ? 1 : 0,
};
@@ -309,7 +335,11 @@ export async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRunt
let entityIndex: number;
let recordIdIndex: number;
if (action === "batch-edit" || action === "record-batch-edit") {
if (
action === "batch-edit" ||
action === "record-batch-edit" ||
action === "batch-update"
) {
return handleBatchEdit(parsed, runtime, 0, 1);
}
@@ -318,6 +348,11 @@ export async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRunt
appIndex = 0;
entityIndex = 1;
recordIdIndex = 2;
} else if (action === "update") {
subAction = "update";
appIndex = 0;
entityIndex = 1;
recordIdIndex = 2;
} else {
const firstArg = parsed.args[0]?.toLowerCase();
if (
@@ -330,6 +365,7 @@ export async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRunt
"edit",
"update",
"batch-edit",
"batch-update",
"recompute",
"recalc",
].includes(firstArg)
@@ -346,7 +382,12 @@ export async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRunt
}
}
if (subAction === "batch-edit") {
if (subAction === "batch-edit" || subAction === "batch-update") {
return handleBatchEdit(parsed, runtime, appIndex, entityIndex);
}
const whereClause = stringOption(parsed.options, ["where"]);
if ((subAction === "update" || subAction === "edit") && (whereClause || parsed.args.length <= recordIdIndex)) {
return handleBatchEdit(parsed, runtime, appIndex, entityIndex);
}
@@ -442,7 +483,8 @@ export async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRunt
}
case "edit":
case "update": {
const form = parseJsonDataOption(parsed);
const setClause = stringOption(parsed.options, ["set"]);
const form = setClause ? parseSetClause(setClause, resolved.entity) : parseJsonDataOption(parsed);
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
const isRaw = booleanOption(parsed.options, ["raw"], false);
+212 -6
View File
@@ -1,38 +1,192 @@
import {
aggregateRecordFields,
auditEntityRecords,
auditLedgerContinuityAndBaseline,
buildKeywordFilter,
calculateEntityRecordStats,
fetchAllEntityRecords,
filterRecordsByPredicate,
iterateAllEntityRecords,
normalizeDatalinkRecord,
parseExpectClause,
searchEntityRecords,
selectRecordFields,
} from "../../../domains/datalink/services.js";
import type { LedgerContinuityReport } from "../../../domains/datalink/types.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { printJson, printTable, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { cell, resolveAppAndEntity, splitFields } from "./shared.js";
export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const resolved = await resolveAppAndEntity(parsed, runtime);
const isStatsSubcommand = parsed.args[0] === "stats" || parsed.action === "stats";
const appIndex = parsed.args[0] === "stats" ? 1 : 0;
const entityIndex = parsed.args[0] === "stats" ? 2 : 1;
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
const fetchAll = booleanOption(parsed.options, ["all", "a"], false);
const whereClause = stringOption(parsed.options, ["where"]);
const sumOption = stringOption(parsed.options, ["sum", "aggregate"]);
const isProfileStats = isStatsSubcommand || booleanOption(parsed.options, ["stats", "profile"], false);
const isStream = booleanOption(parsed.options, ["ndjson", "stream"], false);
const isRaw = booleanOption(parsed.options, ["raw"], false);
const isFlat = booleanOption(parsed.options, ["flat", "normalize", "normalized"], false);
const isAll = booleanOption(parsed.options, ["all", "a"], false);
const groupBy = stringOption(parsed.options, ["group-by", "groupBy"]);
const fetchAll = isAll || Boolean(whereClause || sumOption || isProfileStats);
const start = numberOption(parsed.options, ["start", "offset"], 0);
const count = numberOption(parsed.options, ["count", "limit"], 20);
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
// 1. 高性能流式下发模式 (--ndjson / --stream,内存开销 O(pageSize),专为海量数据外部脚本管道设计)
if (isStream) {
let streamCount = 0;
const maxLimit = isAll ? Infinity : count;
for await (const rawRecord of iterateAllEntityRecords(
resolved.clients.ekbClient,
resolved.corpId,
resolved.entity.id,
{ filterBy, pageSize }
)) {
if (whereClause) {
const matched = filterRecordsByPredicate([rawRecord], whereClause, resolved.entity);
if (matched.length === 0) continue;
}
let outputRecord: Record<string, unknown> = isRaw
? (rawRecord as Record<string, unknown>)
: (normalizeDatalinkRecord(rawRecord, resolved.entity) as unknown as Record<string, unknown>);
if (fields.length) {
outputRecord = selectRecordFields(outputRecord, fields, resolved.entity.fields);
}
process.stdout.write(JSON.stringify(outputRecord) + "\n");
streamCount++;
if (maxLimit !== undefined && streamCount >= maxLimit) break;
}
return { stdout: "", stderr: "", exitCode: 0 };
}
// 2. 宏观画像与统计模式 (--stats 或 platform records stats <应用> <对象>)
if (isProfileStats) {
const page = await fetchAllEntityRecords(
resolved.clients.ekbClient,
resolved.corpId,
resolved.entity.id,
{ filterBy, pageSize }
);
let records = page.data;
if (whereClause) {
records = filterRecordsByPredicate(records, whereClause, resolved.entity);
}
const stats = calculateEntityRecordStats(records, resolved.entity, page.total);
if (runtime.jsonMode) {
return { stdout: printJson(stats, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const patternRows: Array<Array<string | number>> = stats.codePatterns.map((p, idx) => [
idx + 1,
p.pattern,
p.sample,
p.count,
p.activeCount,
p.inactiveCount,
]);
const lines = [
`====== [${resolved.platform.name}] ${resolved.entity.name} 宏观状态与数据画像 (总数: ${stats.total}) ======`,
` - 状态分布: 🟢 启用 ${stats.activeCount} 条 (${stats.activeRate}) | 🔴 停用 ${stats.inactiveCount} 条`,
` - 名称画像: ${stats.uniqueNames} 个唯一名称 (其中 ${stats.duplicateNamesCount} 组存在重名,${stats.mixedStatusNamesCount} 组同时包含启用与停用)`,
` - 时间跨度: 最早创建 ${stats.earliestCreateTime || "-"} ~ 最晚更新 ${stats.latestUpdateTime || "-"}`,
"",
"── 编码结构与停用分布 ──",
printTable(["#", "编码模式", "样本", "总数", "启用数", "停用数"], patternRows),
];
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
}
const page = fetchAll
? await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize })
: await searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
const data = fields.length ? page.data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields)) : page.data;
let data = page.data;
if (whereClause) {
data = filterRecordsByPredicate(data, whereClause, resolved.entity);
}
// 3. 数学聚合核算模式 (--sum="租赁费用,日折旧费")
if (sumOption) {
const sumFields = splitFields(sumOption);
const aggReport = aggregateRecordFields(data, resolved.entity, { fields: sumFields, groupBy });
if (runtime.jsonMode) {
return { stdout: printJson(aggReport, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const statRows: Array<Array<string | number>> = Object.entries(aggReport.overall).map(([query, s]) => [
query,
s.fieldLabel,
s.count,
s.sum,
s.avg,
s.min,
s.max,
]);
const lines: string[] = [
`====== [${resolved.platform.name}] ${resolved.entity.name} 台账数学聚合核算 (统计样本: ${data.length} 条记录) ======`,
printTable(
["统计字段", "字段标签", "有效样本 (COUNT)", "总合计 (SUM)", "平均值 (AVG)", "最小值 (MIN)", "最大值 (MAX)"],
statRows
),
];
if (aggReport.groups && aggReport.groups.length > 0) {
lines.push("");
lines.push(`── 按 [${groupBy}] 分组统计 ──`);
const groupRows: Array<Array<string | number>> = [];
for (const g of aggReport.groups) {
for (const [query, s] of Object.entries(g.aggregates)) {
groupRows.push([g.groupValue, g.count, s.fieldLabel, s.sum, s.avg, s.min, s.max]);
}
}
lines.push(
printTable(
[`分组 (${groupBy})`, "组内条数", "字段", "组内合计", "组内均值", "最小值", "最大值"],
groupRows
)
);
}
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
}
// 4. 常规记录查询模式 (支持 --flat 扁平归一化)
if (isFlat) {
data = data.map((item) => normalizeDatalinkRecord(item, resolved.entity) as unknown as Record<string, unknown>);
}
if (fields.length) {
data = data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields));
}
const result = {
platform: resolved.platform,
entity: resolved.entity,
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, fields },
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, where: whereClause, fields, flat: isFlat },
total: page.total,
returned: data.length,
data,
};
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
@@ -48,13 +202,18 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
}
export async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const resolved = await resolveAppAndEntity(parsed, runtime);
if (!resolved.entity) {
throw new Error("请提供业务对象 ID、编码或名称: hose-use platform audit <应用> <业务对象> [--check-fields=字段1,字段2] [--active-only]");
throw new Error(
"请提供业务对象 ID、编码或名称: hose-use platform audit <应用> <业务对象> [--check-fields=字段1,字段2] [--active-only] [--check-continuous=序号字段] [--expect=期望表达式]"
);
}
const checkFields = splitFields(stringOption(parsed.options, ["check-fields", "checkFields", "fields"]));
const activeOnly = booleanOption(parsed.options, ["active-only", "activeOnly"], false);
const checkContinuous = stringOption(parsed.options, ["check-continuous", "checkContinuous", "continuous", "seq", "sequence"]);
const expectClause = stringOption(parsed.options, ["expect", "expect-value", "expectValue", "baseline"]);
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (activeOnly ? "(active==true)" : undefined);
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
@@ -68,10 +227,20 @@ export async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): P
total: page.total,
});
let continuityReport: LedgerContinuityReport | undefined;
if (checkContinuous || expectClause) {
const expectedValues = expectClause ? parseExpectClause(expectClause) : undefined;
continuityReport = auditLedgerContinuityAndBaseline(page.data, resolved.entity, {
sequenceField: checkContinuous,
expectedValues,
});
}
const output = {
platform: { id: resolved.platform.id, name: resolved.platform.name, code: resolved.platform.code },
entity: { id: resolved.entity.id, name: resolved.entity.name, code: resolved.entity.code },
...report,
continuity: continuityReport,
};
if (runtime.jsonMode) {
return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: 0 };
@@ -104,7 +273,7 @@ export async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): P
"本次体检记录数": report.auditedRecords,
"健康记录数": report.healthyRecords,
"异常记录数": report.affectedRecordCount,
"总问题项数": report.issueCount,
"总问题项数": report.issueCount + (continuityReport?.issues.length ?? 0),
"关键字段缺失 (MISSING_FIELD)": report.summary.missingFieldCount,
"引用对象已停用 (DISABLED_REFERENCE)": report.summary.disabledReferenceCount,
"跨表同名维度待回填 (CROSS_LEDGER_MISSING_SYNC)": report.summary.crossLedgerMissingSyncCount,
@@ -117,6 +286,42 @@ export async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): P
: "✅ 未发现任何字段缺失、停用引用或跨表维度不一致问题",
];
if (continuityReport) {
if (continuityReport.sequenceSummary) {
const seq = continuityReport.sequenceSummary;
outLines.push("");
outLines.push(`── 台账序号连续性体检 (字段: ${seq.fieldLabel}) ──`);
outLines.push(
printKeyValue({
"最小期数 (MIN)": seq.min,
"最大期数 (MAX)": seq.max,
"期望连续期数": seq.expectedCount,
"实际有效记录数": seq.actualCount,
"断层缺失期数 (MISSING)": seq.missing.length ? `❌ 缺少 [${seq.missing.join(", ")}]` : "✅ 无断层缺失",
"重复重号期数 (DUPLICATE)": seq.duplicates.length ? `❌ 重号 [${seq.duplicates.join(", ")}]` : "✅ 无重复重号",
})
);
}
if (expectClause) {
outLines.push("");
outLines.push(`── 基线离群异常核对 (共 ${continuityReport.outliers.length} 条偏离记录) ──`);
if (continuityReport.outliers.length > 0) {
const outlierRows = continuityReport.outliers.map((o, idx) => [
idx + 1,
o.recordId,
o.fieldLabel,
o.value,
o.expectedValue,
o.diff > 0 ? `+${o.diff}` : o.diff,
]);
outLines.push(printTable(["#", "记录 ID", "字段", "实际值", "基线期望", "偏离差额"], outlierRows));
} else {
outLines.push("✅ 所有记录数值均符合期望基线标准,无离群异常");
}
}
}
if (patchRows.length > 0) {
outLines.push("");
outLines.push(`── 💡 建议自动回填修复清单 (共 ${patchRows.length} 条记录,可通过 platform record batch-edit 执行) ──`);
@@ -129,3 +334,4 @@ export async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): P
exitCode: 0,
};
}
+1 -1
View File
@@ -110,7 +110,7 @@ export async function handleProbeCommand(
? `✅ OpenAPI 持久化密钥 (${currentCorp.credentials.appKey})`
: "✅ 统一认证主账号自动换票"
: "⚪ 短期会话",
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime, isPersistent),
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime, isPersistent, hasOpenApi ? "openapi" : currentCorp.source),
"主站 Session 连通": (results.ekbSession as any).status === "ok" ? "🟢 正常" : "🔴 异常",
"EASO 引擎鉴权换票": (results.easoToken as any).status === "ok" ? "🟢 握手成功" : "🔴 失败",
"自建应用扫描": (results.platformAccess as any).status === "ok" ? `🟢 可访问 (${(results.platformAccess as any).totalPlatforms} 个自建应用)` : "🔴 失败",
+3 -3
View File
@@ -1,12 +1,12 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { runCli } from "../runner.js";
import { closeApprovalDatabase, getApprovalDatabase } from "../../domains/approval/db.js";
import { closeDatabase, getDatabase } from "../../core/db/index.js";
import { ApprovalRepository } from "../../domains/approval/repository.js";
describe("CLI - hose-use rule 规则与场景索引命令", () => {
beforeEach(() => {
process.env.HOSE_APPROVAL_DB = ":memory:";
const db = getApprovalDatabase(":memory:");
const db = getDatabase(":memory:");
const repo = new ApprovalRepository(db);
// 预置几条测试规则 (仅需 适用场景 + 规约正文 两个要素)
@@ -25,7 +25,7 @@ describe("CLI - hose-use rule 规则与场景索引命令", () => {
});
afterEach(() => {
closeApprovalDatabase();
closeDatabase();
delete process.env.HOSE_APPROVAL_DB;
});
+668
View File
@@ -0,0 +1,668 @@
import { describe, expect, it, spyOn, afterEach } from "bun:test";
import { handleWorkflowCommand } from "./workflow/index.js";
import * as helpers from "../helpers.js";
import type { CliRuntime } from "../types.js";
import type { CorpConfig } from "../../core/config/types.js";
const mockCorp: CorpConfig = {
id: "test-corp",
name: "测试企业",
baseUrl: "https://app.ekuaibao.com",
source: "openapi",
credentials: {
accessToken: "mock-token",
corpId: "test-corp",
staffId: "test-corp:STAFF_TEST",
appKey: "test-key",
appSecurity: "test-security",
},
};
const mockRuntime: CliRuntime = {
corpContext: {
listCorps: () => [mockCorp],
getCurrent: () => mockCorp,
switchCorp: () => true,
resolve: () => mockCorp,
} as any,
selectedCorp: mockCorp,
jsonMode: false,
outputOptions: {},
};
describe("CLI - workflow job 执行详情与异常精准透视", () => {
let spies: ReturnType<typeof spyOn>[] = [];
afterEach(() => {
for (const spy of spies) {
spy.mockRestore();
}
spies = [];
});
it("fails when no corp is selected", async () => {
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "job",
args: ["job_123"],
options: {},
raw: ["workflow", "job", "job_123"],
},
{ ...mockRuntime, selectedCorp: null }
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未选中企业");
});
it("fails when no jobId is provided", async () => {
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "job",
args: [],
options: {},
raw: ["workflow", "job"],
},
mockRuntime
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("用法: hose-use workflow job <jobId>");
});
it("handles workflow job --failed with deep error inspection and inputs/outputs", async () => {
const mockPiperClient = {
get: (url: string) => {
let payload: any = {};
if (url.includes("/execution/level/failed")) {
payload = { number: 1, size: 100, totalPages: 0, totalItems: 0, items: [] };
} else if (url.includes("/execution")) {
payload = [
{
id: "exec_1",
name: "auto_approve",
displayName: "资金调拨自动审批",
type: "flow-approval",
status: "FAILED",
executionTime: 350,
error: { message: "400: 无待办审批事项" },
inputs: { formId: "ZJ-20261014-001368", action: "agree" },
outputs: { code: 400, message: "无待办审批事项" },
},
];
} else if (url.includes("/jobs/job_err")) {
payload = {
id: "job_err",
pipelineId: "pipe_1",
state: "FAILED",
startTime: "2026-10-14 10:00:00",
durationTime: 1200,
};
}
return new Response(JSON.stringify({ code: 200, data: payload }), {
status: 200,
headers: { "content-type": "application/json" },
});
},
};
spies.push(
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
ekbClient: {
get: () => ({ json: async () => [{ id: "plat_1", active: true }] }),
},
easoClient: mockPiperClient,
} as any)
);
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockPiperClient as any));
// 文本输出测试
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "job",
args: ["job_err"],
options: { failed: true },
raw: ["workflow", "job", "job_err", "--failed"],
},
mockRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("Job 异常/失败执行节点透视");
expect(res.stdout).toContain("资金调拨自动审批");
expect(res.stdout).toContain("400: 无待办审批事项");
expect(res.stdout).toContain("ZJ-20261014-001368");
// --json 模式测试
const jsonRes = await handleWorkflowCommand(
{
area: "workflow",
action: "job",
args: ["job_err"],
options: { failed: true, json: true },
raw: ["workflow", "job", "job_err", "--failed", "--json"],
},
{ ...mockRuntime, jsonMode: true }
);
expect(jsonRes.exitCode).toBe(0);
const parsed = JSON.parse(jsonRes.stdout);
expect(parsed.totalFailed).toBe(1);
expect(parsed.failedNodes[0].id).toBe("exec_1");
expect(parsed.failedNodes[0].error.message).toBe("400: 无待办审批事项");
expect(parsed.failedNodes[0].inputs.formId).toBe("ZJ-20261014-001368");
});
it("handles workflow job --node=<name|id> targeting specific execution node", async () => {
const mockPiperClient = {
get: (url: string) => {
let payload: any = {};
if (url.includes("/execution")) {
payload = [
{
id: "node_code",
name: "codeRunner_1",
displayName: "MVEL计算节点",
type: "code",
status: "COMPLETED",
executionTime: 85,
inputs: { expression: "pvTotal * dailyRate" },
outputs: { result: 78787.55 },
},
];
}
return new Response(JSON.stringify({ code: 200, data: payload }), {
status: 200,
headers: { "content-type": "application/json" },
});
},
};
spies.push(
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
ekbClient: {
get: () => ({ json: async () => [{ id: "plat_1", active: true }] }),
},
easoClient: mockPiperClient,
} as any)
);
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockPiperClient as any));
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "job",
args: ["job_single"],
options: { node: "MVEL计算" },
raw: ["workflow", "job", "job_single", "--node=MVEL计算"],
},
mockRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("工作流节点执行详情 [node_code]");
expect(res.stdout).toContain("MVEL计算节点");
expect(res.stdout).toContain("pvTotal * dailyRate");
expect(res.stdout).toContain("78787.55");
// 节点不存在时的错误提示拦截
const notFoundRes = await handleWorkflowCommand(
{
area: "workflow",
action: "job",
args: ["job_single"],
options: { node: "不存在的节点" },
raw: ["workflow", "job", "job_single", "--node=不存在的节点"],
},
mockRuntime
);
expect(notFoundRes.exitCode).toBe(1);
expect(notFoundRes.stderr).toContain("未在 Job [job_single] 的执行树中找到匹配 \"不存在的节点\" 的节点");
});
it("handles workflow diff <snapshot1> <snapshot2> comparing code and node changes", async () => {
const snap1 = {
id: "snap_v1",
pipelineId: "pipe_1",
version: "1.0.1",
updateTime: "2026-10-13 14:00:00",
staffName: "张三",
tasks: [
{
name: "fetch_contract",
type: "ekuaibao-datalink-filter",
displayName: "获取合同台账",
groupName: "action",
orderIndex: 0,
levelIndex: [0],
status: "ENABLE",
combineFilters: { condition: "AND", filters: [{ key: "state", compare: "EQUAL", value: "OPEN" }] },
},
{
name: "mvel_calc",
type: "code",
displayName: "MVEL计算节点",
groupName: "action",
orderIndex: 1,
levelIndex: [1],
status: "ENABLE",
code: "double dailyRate = 0.05;\nreturn pvTotal * dailyRate;",
},
],
};
const snap2 = {
id: "snap_v2",
pipelineId: "pipe_1",
version: "1.0.2",
updateTime: "2026-10-14 09:30:00",
staffName: "李四",
tasks: [
{
name: "fetch_contract",
type: "ekuaibao-datalink-filter",
displayName: "获取合同台账",
groupName: "action",
orderIndex: 0,
levelIndex: [0],
status: "ENABLE",
combineFilters: { condition: "AND", filters: [{ key: "state", compare: "EQUAL", value: "APPROVING" }] },
},
{
name: "mvel_calc",
type: "code",
displayName: "MVEL计算节点",
groupName: "action",
orderIndex: 1,
levelIndex: [1],
status: "ENABLE",
code: "double dailyRate = 0.05;\nif (pvTotal <= 0) throw new RuntimeException('金额非法');\nreturn pvTotal * dailyRate;",
},
{
name: "notify_audit",
type: "webhook",
displayName: "审计通知",
groupName: "action",
orderIndex: 2,
levelIndex: [2],
status: "ENABLE",
},
],
};
const mockPiperClient = {
get: (url: string) => {
let payload: any = {};
if (url.includes("snap_v1")) payload = snap1;
else if (url.includes("snap_v2")) payload = snap2;
return new Response(JSON.stringify({ code: 200, data: payload }), {
status: 200,
headers: { "content-type": "application/json" },
});
},
};
spies.push(
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
ekbClient: { get: () => ({ json: async () => [{ id: "plat_1", active: true }] }) },
easoClient: mockPiperClient,
} as any)
);
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockPiperClient as any));
// 1. 文本输出模式
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "diff",
args: ["snap_v1", "snap_v2"],
options: {},
raw: ["workflow", "diff", "snap_v1", "snap_v2"],
},
mockRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("工作流快照比对 [1.0.1 -> 1.0.2]");
expect(res.stdout).toContain("新增节点 (1 个)");
expect(res.stdout).toContain("notify_audit");
expect(res.stdout).toContain("mvel_calc");
expect(res.stdout).toContain("金额非法");
expect(res.stdout).toContain("过滤/触发条件变动");
// 2. JSON 模式
const jsonRes = await handleWorkflowCommand(
{
area: "workflow",
action: "diff",
args: ["snap_v1", "snap_v2"],
options: { json: true },
raw: ["workflow", "diff", "snap_v1", "snap_v2", "--json"],
},
{ ...mockRuntime, jsonMode: true }
);
expect(jsonRes.exitCode).toBe(0);
const parsed = JSON.parse(jsonRes.stdout);
expect(parsed.addedTasks).toContain("notify_audit");
expect(parsed.modifiedTasks.find((t: any) => t.taskName === "mvel_calc")).toBeDefined();
// 3. 缺少参数
const errRes = await handleWorkflowCommand(
{
area: "workflow",
action: "diff",
args: ["snap_v1"],
options: {},
raw: ["workflow", "diff", "snap_v1"],
},
mockRuntime
);
expect(errRes.exitCode).toBe(1);
expect(errRes.stderr).toContain("用法: hose-use workflow diff");
});
it("handles workflow diff-job <job1> <job2> comparing execution branch and error divergence", async () => {
const jobA = {
id: "job_success",
pipelineId: "pipe_1",
state: "COMPLETED",
startTime: "2026-10-14 10:00:00",
durationTime: 450,
hasError: false,
errorTaskCount: 0,
};
const treeA = [
{
id: "ex_1",
name: "get_bill",
displayName: "获取单据",
type: "flow-detail",
status: "COMPLETED",
executionTime: 120,
inputs: { billCode: "ZJ-20261014-001" },
outputs: { state: "APPROVING" },
},
{
id: "ex_2",
name: "auto_approve",
displayName: "自动审批",
type: "flow-approval",
status: "COMPLETED",
executionTime: 330,
inputs: { action: "agree" },
outputs: { code: 200, success: true },
},
];
const jobB = {
id: "job_failed",
pipelineId: "pipe_1",
state: "FAILED",
startTime: "2026-10-14 11:00:00",
durationTime: 320,
hasError: true,
errorTaskCount: 1,
};
const treeB = [
{
id: "ex_1b",
name: "get_bill",
displayName: "获取单据",
type: "flow-detail",
status: "COMPLETED",
executionTime: 100,
inputs: { billCode: "ZJ-20261014-002" },
outputs: { state: "PAYING" },
},
{
id: "ex_2b",
name: "auto_approve",
displayName: "自动审批",
type: "flow-approval",
status: "FAILED",
executionTime: 220,
error: { message: "400: 无待办审批事项" },
inputs: { action: "agree" },
outputs: { code: 400, message: "无待办审批事项" },
},
];
const mockPiperClient = {
get: (url: string) => {
let payload: any = {};
if (url.includes("job_success/execution")) payload = treeA;
else if (url.includes("job_failed/execution")) payload = treeB;
else if (url.includes("job_success")) payload = jobA;
else if (url.includes("job_failed")) payload = jobB;
return new Response(JSON.stringify({ code: 200, data: payload }), {
status: 200,
headers: { "content-type": "application/json" },
});
},
};
spies.push(
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
ekbClient: { get: () => ({ json: async () => [{ id: "plat_1", active: true }] }) },
easoClient: mockPiperClient,
} as any)
);
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockPiperClient as any));
// 1. 文本输出模式
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "diff-job",
args: ["job_success", "job_failed"],
options: {},
raw: ["workflow", "diff-job", "job_success", "job_failed"],
},
mockRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("工作流 Job 执行比对 [job_success vs job_failed]");
expect(res.stdout).toContain("auto_approve");
expect(res.stdout).toContain("400: 无待办审批事项");
expect(res.stdout).toContain("ZJ-20261014-001");
expect(res.stdout).toContain("ZJ-20261014-002");
// 2. JSON 模式
const jsonRes = await handleWorkflowCommand(
{
area: "workflow",
action: "diff-job",
args: ["job_success", "job_failed"],
options: { json: true },
raw: ["workflow", "diff-job", "job_success", "job_failed", "--json"],
},
{ ...mockRuntime, jsonMode: true }
);
expect(jsonRes.exitCode).toBe(0);
const parsed = JSON.parse(jsonRes.stdout);
expect(parsed.jobA.id).toBe("job_success");
expect(parsed.jobB.id).toBe("job_failed");
expect(parsed.summary.statusDiffCount).toBe(1);
expect(parsed.nodes.find((n: any) => n.taskName === "auto_approve").statusB).toBe("FAILED");
});
it("handles workflow test without pipelineId", async () => {
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "test",
args: [],
options: {},
raw: ["workflow", "test"],
},
mockRuntime
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("用法: hose-use workflow test");
});
it("handles workflow test without --flow by listing candidate sources", async () => {
const mockClient = {
post: (url: string) => ({
json: async () => ({
code: 200,
data: {
type: "flowForm",
total: 1,
label: "我的单据",
items: [
{ id: "ZJ-20261015-001387", title: "资金调拨测试单", flowState: "审批中" },
],
fields: [
{ key: "id", label: "单号" },
{ key: "title", label: "标题" },
],
},
}),
}),
get: (url: string) => {
if (url.includes("platform")) {
return { json: async () => ({ items: [] }) };
}
return { json: async () => ({ code: 200, data: [] }) };
},
};
spies.push(
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
ekbClient: mockClient as any,
easoClient: mockClient as any,
corp: mockCorp,
} as any)
);
spies.push(
spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any)
);
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "test",
args: ["wf_test_1"],
options: { platformId: "p1" },
raw: ["workflow", "test", "wf_test_1", "--platform-id=p1"],
},
mockRuntime
);
expect(res.exitCode).toBe(1);
expect(res.stdout).toContain("未指定测试单号");
expect(res.stdout).toContain("ZJ-20261015-001387");
expect(res.stdout).toContain("资金调拨测试单");
});
it("handles workflow test end-to-end with --flow parameter", async () => {
const mockClient = {
post: (url: string) => {
if (url.includes("debugSource")) {
return {
json: async () => ({
code: 200,
data: {
type: "flowForm",
total: 1,
items: [{ id: "ZJ-20261015-001387", title: "资金调拨", flowState: "审批中" }],
},
}),
};
}
if (url.includes("api/easo/jobs")) {
return {
json: async () => ({
code: 200,
data: "job_debug_888",
}),
};
}
return { json: async () => ({ code: 200, data: null }) };
},
get: (url: string) => {
if (url.includes("execution")) {
return {
json: async () => ({
code: 200,
data: [
{
id: "e1",
name: "trigger_1",
label: "触发器",
type: "ekuaibao-flowform-trigger",
status: "COMPLETED",
executionTime: 10,
},
{
id: "e2",
name: "control_1",
label: "条件节点",
type: "condition",
status: "COMPLETED",
executionTime: 5,
tasks: [{ name: "action_auto", label: "自动审批", type: "http" }],
},
{
id: "e3",
name: "action_stop",
label: "终止节点",
type: "stop",
status: "COMPLETED",
executionTime: 2,
},
],
}),
};
}
return {
json: async () => ({
code: 200,
data: {
id: "job_debug_888",
pipelineId: "wf_test_1",
status: "COMPLETED",
runType: "DEBUG",
durationTime: 17,
},
}),
};
},
};
spies.push(
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
ekbClient: mockClient as any,
easoClient: mockClient as any,
corp: mockCorp,
} as any)
);
spies.push(
spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any)
);
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "test",
args: ["wf_test_1"],
options: { flow: "ZJ-20261015-001387", platformId: "p1" },
raw: ["workflow", "test", "wf_test_1", "--flow=ZJ-20261015-001387", "--platform-id=p1"],
},
mockRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("工作流自动化调测报告 [wf_test_1]");
expect(res.stdout).toContain("job_debug_888");
expect(res.stdout).toContain("ZJ-20261015-001387");
expect(res.stdout).toContain("control_1");
});
});
+197
View File
@@ -0,0 +1,197 @@
import {
diffWorkflowJobs,
diffWorkflowSnapshots,
getJob,
getJobExecutionTree,
getWorkflowSnapshot,
} from "../../../domains/platform/services.js";
import { stringOption } from "../../parser.js";
import { printJson, printTable } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createJobPiperClient } from "./shared.js";
export async function handleWorkflowDiff(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const snapIdA = parsed.args[0] || stringOption(parsed.options, ["from", "a", "snapshot1", "snapshotA"]);
const snapIdB = parsed.args[1] || stringOption(parsed.options, ["to", "b", "snapshot2", "snapshotB"]);
if (!snapIdA || !snapIdB) {
return {
stdout: "",
stderr: "用法: hose-use workflow diff <snapshotId1> <snapshotId2> [--pipelineId=<id>]\n",
exitCode: 1,
};
}
const client = await createJobPiperClient(parsed, runtime);
const pipelineId = stringOption(parsed.options, ["pipelineId", "pipeline", "id"]);
const [snapA, snapB] = await Promise.all([
getWorkflowSnapshot(client, snapIdA, pipelineId),
getWorkflowSnapshot(client, snapIdB, pipelineId),
]);
const diff = diffWorkflowSnapshots(snapA, snapB);
if (runtime.jsonMode) {
return {
stdout: printJson(diff, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const lines: string[] = [
`====== 工作流快照比对 [${diff.snapshotA.version || snapIdA} -> ${diff.snapshotB.version || snapIdB}] ======`,
` 快照 A : ${snapIdA} (版本: ${diff.snapshotA.version || "-"}) 更新人: ${diff.snapshotA.staffName || "-"} 时间: ${diff.snapshotA.updateTime || "-"}`,
` 快照 B : ${snapIdB} (版本: ${diff.snapshotB.version || "-"}) 更新人: ${diff.snapshotB.staffName || "-"} 时间: ${diff.snapshotB.updateTime || "-"}`,
` 变更统计: ${diff.summary.changedCount} 个节点有变动 (节点总数: A=${diff.summary.totalA}, B=${diff.summary.totalB})`,
"",
];
if (diff.addedTasks.length > 0) {
lines.push(`── ➕ 新增节点 (${diff.addedTasks.length} 个) ──`);
lines.push(` ${diff.addedTasks.join(", ")}`);
lines.push("");
}
if (diff.removedTasks.length > 0) {
lines.push(`── ➖ 删除节点 (${diff.removedTasks.length} 个) ──`);
lines.push(` ${diff.removedTasks.join(", ")}`);
lines.push("");
}
if (diff.modifiedTasks.length === 0) {
lines.push("✅ 两个快照间未检测到任何节点或代码变更。");
} else {
lines.push(`── 📝 节点变更明细 (${diff.modifiedTasks.length} 个) ──`);
for (const task of diff.modifiedTasks) {
lines.push(`\n• 节点 [${task.taskName}] (${task.displayName || task.type}) [${task.changeType}]:`);
if (task.codeDiff?.unifiedDiff) {
lines.push(` --- 脚本代码变动 ---`);
lines.push(task.codeDiff.unifiedDiff.split("\n").map((l) => ` ${l}`).join("\n"));
}
if (task.filterDiff) {
lines.push(` --- 过滤/触发条件变动 ---`);
lines.push(` 原条件: ${JSON.stringify(task.filterDiff.from) || "(空)"}`);
lines.push(` 现条件: ${JSON.stringify(task.filterDiff.to) || "(空)"}`);
}
if (task.configChanges.length > 0) {
lines.push(` --- 属性配置变动 ---`);
for (const c of task.configChanges) {
lines.push(` • ${c.field}: ${JSON.stringify(c.from)} -> ${JSON.stringify(c.to)}`);
}
}
}
}
return {
stdout: lines.join("\n") + "\n",
stderr: "",
exitCode: 0,
};
}
export async function handleWorkflowDiffJob(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const jobIdA = parsed.args[0] || stringOption(parsed.options, ["from", "a", "job1", "jobA"]);
const jobIdB = parsed.args[1] || stringOption(parsed.options, ["to", "b", "job2", "jobB"]);
if (!jobIdA || !jobIdB) {
return {
stdout: "",
stderr: "用法: hose-use workflow diff-job <jobId1> <jobId2>\n",
exitCode: 1,
};
}
const client = await createJobPiperClient(parsed, runtime);
const [jobA, treeA, jobB, treeB] = await Promise.all([
getJob(client, jobIdA),
getJobExecutionTree(client, jobIdA),
getJob(client, jobIdB),
getJobExecutionTree(client, jobIdB),
]);
const diff = diffWorkflowJobs(jobA, treeA, jobB, treeB);
if (runtime.jsonMode) {
return {
stdout: printJson(diff, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const summaryRows = [
["Job ID", diff.jobA.id, diff.jobB.id],
["运行状态", String(diff.jobA.state ?? "-"), String(diff.jobB.state ?? "-")],
["开始时间", diff.jobA.startTime || "-", diff.jobB.startTime || "-"],
["执行耗时(ms)", String(diff.jobA.durationTime ?? "-"), String(diff.jobB.durationTime ?? "-")],
["执行节点数", String(diff.summary.totalNodesA), String(diff.summary.totalNodesB)],
["错误标记 (hasError)", diff.jobA.hasError ? "⚠️ 包含错误" : "正常", diff.jobB.hasError ? "⚠️ 包含错误" : "正常"],
];
const lines: string[] = [
`====== 工作流 Job 执行比对 [${jobIdA} vs ${jobIdB}] ======`,
printTable(["指标项", `Job A (${jobIdA})`, `Job B (${jobIdB})`], summaryRows),
"",
`── 🔀 分支走向与节点执行状态比对 (差异节点: ${diff.summary.divergedNodesCount} 个) ──`,
];
if (diff.summary.divergedNodesCount === 0) {
lines.push(" ✅ 两个 Job 执行链路完全一致,各节点状态与入参相同。");
} else {
const divergedNodes = diff.nodes.filter((n) => n.diverged);
const nodeRows = divergedNodes.map((n) => [
n.taskName,
n.displayName || "-",
n.type || "-",
n.statusA || "(未执行)",
n.statusB || "(未执行)",
n.statusA !== n.statusB ? "⚠️ 状态不一致" : "一致",
n.errorB ? "❌ B报错" : n.errorA ? "⚠️ A报错" : "-",
]);
lines.push(
printTable(
["节点名称", "显示名称", "类型", "Job A 状态", "Job B 状态", "状态差异", "错误差异"],
nodeRows
)
);
lines.push("\n── 🔍 差异节点入参/出参与报错透视 ──");
for (const n of divergedNodes) {
lines.push(`\n• 节点 [${n.taskName}] (${n.displayName || n.type || "-"}):`);
if (n.statusA !== n.statusB) {
lines.push(` 状态对比: ${n.statusA || "(未执行)"} -> ${n.statusB || "(未执行)"}`);
}
if (n.errorB || n.errorA) {
if (n.errorA) lines.push(` Job A 报错: ${JSON.stringify(n.errorA)}`);
if (n.errorB) lines.push(` Job B 报错: ${JSON.stringify(n.errorB)}`);
}
if (n.inputsDiff && n.inputsDiff.length > 0) {
lines.push(` 入参差异 (inputs):`);
for (const diffItem of n.inputsDiff) {
lines.push(` ~ ${diffItem.field}: ${JSON.stringify(diffItem.from)} -> ${JSON.stringify(diffItem.to)}`);
}
}
if (n.outputsDiff && n.outputsDiff.length > 0) {
lines.push(` 出参差异 (outputs):`);
for (const diffItem of n.outputsDiff) {
lines.push(` ~ ${diffItem.field}: ${JSON.stringify(diffItem.from)} -> ${JSON.stringify(diffItem.to)}`);
}
}
}
}
return {
stdout: lines.join("\n") + "\n",
stderr: "",
exitCode: 0,
};
}
+14 -10
View File
@@ -38,10 +38,14 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
});
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
const isJobError = (job: any): boolean => {
if (job.hasError === true || job.hasError === "存在" || job.hasError === "true") return true;
if (typeof job.errorTaskCount === "number" && job.errorTaskCount > 0) return true;
if (job.state === "FAILED" || job.status === "FAILED") return true;
return false;
};
const filteredJobList = hasErrorFilter
? rawResult.jobList.filter(
(job) => job.hasError === true || job.errorTaskCount > 0 || job.state === "FAILED"
)
? rawResult.jobList.filter(isJobError)
: rawResult.jobList;
const result = hasErrorFilter
? { ...rawResult, jobList: filteredJobList }
@@ -49,15 +53,15 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
const rows = result.jobList.map((job, idx) => [
const rows = result.jobList.map((job: any, idx) => [
idx + 1,
job.id,
job.state,
job.successTaskCount,
job.errorTaskCount,
job.hasError || job.errorTaskCount > 0 ? "⚠️ 是 (true)" : "否 (false)",
job.jobId || job.id || "-",
job.status || (job.state === 0 ? "COMPLETED" : String(job.state ?? "-")),
job.successTaskCount ?? 0,
job.errorTaskCount ?? 0,
isJobError(job) ? "⚠️ 包含错误" : "正常",
job.durationTime ?? "-",
job.startTime || "-",
job.executeTime || job.startTime || "-",
]);
const tableStr = rows.length
? printTable(
+16 -1
View File
@@ -6,6 +6,8 @@ import { handleHistory, handleLogs } from "./history.js";
import { handleJob } from "./job.js";
import { handleCheck } from "./check.js";
import { handleAnalyze } from "./analyze.js";
import { handleWorkflowDiff, handleWorkflowDiffJob } from "./diff.js";
import { handleWorkflowTest } from "./test.js";
export async function handleWorkflowCommand(
parsed: CliParsedArgs,
@@ -59,10 +61,23 @@ export async function handleWorkflowCommand(
case "analyze":
case "analyse":
return handleAnalyze(parsed, runtime);
case "diff":
case "diff-snapshot":
case "diff-snapshots":
case "compare":
return handleWorkflowDiff(parsed, runtime);
case "diff-job":
case "diff-jobs":
case "compare-job":
return handleWorkflowDiffJob(parsed, runtime);
case "test":
case "debug":
case "run-test":
return handleWorkflowTest(parsed, runtime);
default:
return {
stdout: "",
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, check\n`,
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, debug\n`,
exitCode: 1,
};
}
+152 -24
View File
@@ -1,10 +1,15 @@
import {
extractFailureExecutions,
findExecutionNode,
flattenExecutionTree,
getExecutionLogs,
getJob,
getJobExecutionLevel,
getJobExecutionTree,
getJobFailedExecutions,
isTaskExecutionFailed,
listPlatforms,
explainConditionBranches,
} from "../../../domains/platform/services.js";
import type { WorkflowTaskExecution } from "../../../domains/platform/types.js";
import { stringOption, numberOption, booleanOption } from "../../parser.js";
@@ -101,7 +106,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
if (!jobId) {
return {
stdout: "",
stderr: "用法: hose-use workflow job <jobId> [--failed] [--parent=<executionId>] [--logs=<executionId>]\n",
stderr: "用法: hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose] [--parent=<executionId>] [--logs=<executionId>]\n",
exitCode: 1,
};
}
@@ -111,7 +116,9 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 100;
const logsExecutionId = stringOption(parsed.options, ["logs", "log", "execution-logs"]);
const parentExecutionId = stringOption(parsed.options, ["parent", "parent-id", "parentId"]);
const nodeQuery = stringOption(parsed.options, ["node", "task", "node-id", "nodeId"]);
const onlyFailed = booleanOption(parsed.options, ["failed", "fail", "errors"]);
const verbose = booleanOption(parsed.options, ["verbose", "v"]);
// 1. --logs=<executionId>
if (logsExecutionId) {
@@ -208,21 +215,100 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
};
}
// 3. --failed
// 3. --node=<name|id>
if (nodeQuery) {
const tree = await getJobExecutionTree(client, jobId);
const matchedNode = findExecutionNode(tree, nodeQuery);
if (!matchedNode) {
return {
stdout: "",
stderr: `未在 Job [${jobId}] 的执行树中找到匹配 "${nodeQuery}" 的节点。请核对节点名称或 Execution ID。\n`,
exitCode: 1,
};
}
if (runtime.jsonMode) {
return {
stdout: printJson({ jobId, node: matchedNode }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const anyNode = matchedNode as any;
const inputPayload = anyNode.inputs ?? anyNode.form ?? anyNode.params;
const outputPayload = anyNode.outputs ?? anyNode.output ?? anyNode.details;
const lines = [
`====== 工作流节点执行详情 [${matchedNode.id}] (Job: ${jobId}) ======`,
printKeyValue({
"Execution ID": matchedNode.id,
"Parent ID": matchedNode.parentId || "-",
"节点标识 (name)": matchedNode.name || "-",
"节点名称": matchedNode.displayName || matchedNode.label || "-",
"节点类型 (type)": matchedNode.type || "-",
"执行状态 (status)": matchedNode.status || anyNode.state || "-",
"耗时(ms)": String(matchedNode.executionTime ?? anyNode.durationTime ?? "-"),
"开始时间": String(matchedNode.startTime || anyNode.createTime || "-"),
"结束时间": String(matchedNode.endTime || "-"),
"循环路径": matchedNode.currentLoopPath || "-",
...(matchedNode.error?.message ? { "错误信息": matchedNode.error.message } : {}),
}),
];
if (matchedNode.error?.message) {
lines.push("");
lines.push("── ❌ 错误堆栈 / 原因 ──");
lines.push(matchedNode.error.message);
if (anyNode.error?.stack) {
lines.push(anyNode.error.stack);
}
}
if (inputPayload !== undefined) {
lines.push("");
lines.push("── 📥 节点入参报文 (inputs / form) ──");
lines.push(typeof inputPayload === "string" ? inputPayload : JSON.stringify(inputPayload, null, 2));
}
if (outputPayload !== undefined) {
lines.push("");
lines.push("── 📤 节点出参 / 响应结果 (outputs) ──");
lines.push(typeof outputPayload === "string" ? outputPayload : JSON.stringify(outputPayload, null, 2));
}
lines.push("");
return {
stdout: `${lines.join("\n")}\n`,
stderr: "",
exitCode: 0,
};
}
// 4. --failed
if (onlyFailed) {
const [job, failedPage] = await Promise.all([
const [job, tree, failedPage] = await Promise.all([
getJob(client, jobId).catch(() => undefined),
getJobFailedExecutions(client, jobId),
getJobExecutionTree(client, jobId).catch(() => []),
getJobFailedExecutions(client, jobId).catch(() => ({
number: 1,
size: 100,
totalPages: 0,
totalItems: 0,
items: [] as WorkflowTaskExecution[],
})),
]);
const enrichedItems = await enrichFailedExecutions(client, jobId, failedPage.items);
const rawFailed = extractFailureExecutions(tree, failedPage.items);
const enrichedItems = await enrichFailedExecutions(client, jobId, rawFailed);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
jobId,
job: job ?? null,
totalItems: failedPage.totalItems,
items: enrichedItems,
totalFailed: enrichedItems.length,
failedNodes: enrichedItems,
},
runtime.outputOptions
),
@@ -231,34 +317,53 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
};
}
const rows = enrichedItems.map((item, idx) => [
const rows = enrichedItems.map((item: any, idx) => [
idx + 1,
item.id,
item.parentId || "-",
item.name || "-",
item.type || "-",
item.status || "-",
item.currentLoopPath || "-",
item.error?.message || "-",
item.displayName || item.label || item.type || "-",
item.status || item.state || "-",
String(item.executionTime ?? item.durationTime ?? "-"),
item.error?.message || item.errorMessage || item.outputs?.error || "-",
]);
const formSummaries: string[] = [];
const nodeDetailBlocks: string[] = [];
const shouldExpand = verbose || enrichedItems.length <= 5;
for (const item of enrichedItems) {
if (item.error?.message || item.form !== undefined) {
formSummaries.push(
`\n── ⚠️ 异常节点 [${item.id}] (${item.name || "-"} | status=${item.status} | loop=${item.currentLoopPath || "-"}) ──`
const anyItem = item as any;
const errMsg = item.error?.message || anyItem.errorMessage || anyItem.outputs?.error;
const inputPayload = anyItem.inputs ?? anyItem.form ?? anyItem.params;
const outputPayload = anyItem.outputs ?? anyItem.output ?? anyItem.details;
if (errMsg || inputPayload !== undefined || outputPayload !== undefined) {
nodeDetailBlocks.push(
`\n── ⚠️ 异常节点 [${item.id}] (${item.name || "-"} | ${item.displayName || item.label || item.type || "-"} | status=${item.status || anyItem.state}) ──`
);
if (item.error?.message) {
formSummaries.push(` 错误详情: ${item.error.message}`);
if (errMsg) {
nodeDetailBlocks.push(` ❌ 错误原因: ${errMsg}`);
}
if (item.form !== undefined) {
formSummaries.push(` 表单入参 (form): ${JSON.stringify(item.form)}`);
if (shouldExpand) {
if (inputPayload !== undefined) {
const inStr = typeof inputPayload === "string" ? inputPayload : JSON.stringify(inputPayload, null, 2);
nodeDetailBlocks.push(` 📥 节点入参 (inputs/form):\n${inStr.split("\n").map((l: string) => " " + l).join("\n")}`);
}
if (outputPayload !== undefined) {
const outStr = typeof outputPayload === "string" ? outputPayload : JSON.stringify(outputPayload, null, 2);
nodeDetailBlocks.push(` 📤 节点出参 (outputs/details):\n${outStr.split("\n").map((l: string) => " " + l).join("\n")}`);
}
} else {
if (inputPayload !== undefined) {
nodeDetailBlocks.push(` 📥 节点入参: [已省略,使用 --verbose 查看完整 JSON]`);
}
}
}
}
return {
stdout: [
`====== Job 异常/跳过执行节点明细 (Job: ${jobId}) ======`,
`====== Job 异常/失败执行节点透视 (Job: ${jobId}) ======`,
job
? printKeyValue({
"Job ID": job.id,
@@ -266,16 +371,17 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
"Job 状态": job.state ?? job.status,
"开始时间": job.startTime || "-",
"耗时(ms)": String(job.durationTime ?? "-"),
"失败节点数": enrichedItems.length,
})
: "",
"",
rows.length
? printTable(
["#", "Execution ID", "Parent ID", "节点标识 (name)", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因 (error.message)"],
["#", "Execution ID", "Parent ID", "节点标识 (name)", "节点名称/类型", "状态", "耗时(ms)", "错误原因"],
rows
)
: "未发现异常或报错跳过的执行节点",
...formSummaries,
: "✅ 未发现任何异常或报错失败的执行节点",
...nodeDetailBlocks,
"",
].filter(Boolean).join("\n"),
stderr: "",
@@ -297,6 +403,8 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
]);
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
const conditionDiagnoses = explainConditionBranches(tree);
if (runtime.jsonMode) {
return {
stdout: printJson(
@@ -305,6 +413,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
job,
executionTree: tree,
failedExecutions,
conditionDiagnoses,
},
runtime.outputOptions
),
@@ -368,6 +477,25 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
);
}
if (conditionDiagnoses.length > 0) {
outLines.push("");
outLines.push("── 💡 条件分支跳过诊断 (为什么没有走内部子任务?) ──");
for (const diag of conditionDiagnoses) {
outLines.push(` ⚠️ [${diag.conditionNodeName}] ${diag.conditionNodeLabel} (Execution ID: ${diag.conditionNodeId})`);
outLines.push(` • 判定结论: ${diag.summary}`);
outLines.push(` • 未执行子任务: ${diag.skippedTaskNames.join(", ")}`);
if (diag.rules.length > 0) {
outLines.push(" • 规则比对明细:");
for (const r of diag.rules) {
const statusIcon = r.matched ? "✅" : "❌";
const missTag = r.isMissing ? " [⚠️ 属性缺失]" : "";
outLines.push(` ${statusIcon} ${r.leftLabel} ${r.operatorLabel} ${JSON.stringify(r.expectedValue)}${missTag}`);
outLines.push(` ↳ ${r.detail}`);
}
}
}
}
return {
stdout: `${outLines.join("\n")}\n`,
stderr: "",
+33 -2
View File
@@ -17,11 +17,42 @@ export async function createWorkflowDetailClient(
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
let platformId = explicit;
if (!platformId) {
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
platformId = all.workflows.find((workflow) => workflow.id === pipelineId)?.platformId;
try {
const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id;
const { listPlatforms } = await import("../../../domains/platform/services.js");
const platforms = await listPlatforms(clients.ekbClient, corpId);
const firstActive = platforms.find((p) => p.active) ?? platforms[0];
platformId = firstActive?.id;
} catch {
// Fall back to easoClient
}
}
return {
client: platformId ? await createPiperClientForCorp(runtime.selectedCorp!, platformId) : clients.easoClient,
clients,
};
}
export async function createJobPiperClient(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<Awaited<ReturnType<typeof createPiperClientForCorp>>> {
const corp = runtime.selectedCorp!;
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
if (explicit) {
return createPiperClientForCorp(corp, explicit);
}
const clients = await createClientsForCorp(corp);
try {
const corpId = corp.corpId || corp.id;
const { listPlatforms } = await import("../../../domains/platform/services.js");
const platforms = await listPlatforms(clients.ekbClient, corpId);
const firstActive = platforms.find((p) => p.active) ?? platforms[0];
if (firstActive?.id) {
return await createPiperClientForCorp(corp, firstActive.id);
}
} catch {
// Fall back to default easoClient
}
return clients.easoClient;
}
+135
View File
@@ -0,0 +1,135 @@
import {
getWorkflowDebugSource,
runWorkflowDebugTest,
} from "../../../domains/platform/services.js";
import { stringOption, booleanOption, numberOption } from "../../parser.js";
import { printJson, printTable, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createWorkflowDetailClient } from "./shared.js";
export async function handleWorkflowTest(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipeline-id", "pipelineId"]);
if (!pipelineId) {
return {
stdout: "",
stderr: "用法: hose-use workflow test <pipelineId> --flow=<单号|单据ID> [--auto-publish] [--timeout=<ms>]\n别名: hose-use workflow debug <pipelineId> --flow=<单号>\n",
exitCode: 1,
};
}
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const flowCodeOrId = stringOption(parsed.options, ["flow", "code", "flow-code", "flowCode", "bill", "entity", "id"]);
const autoPublish = booleanOption(parsed.options, ["auto-publish", "autoPublish", "publish"]);
const timeoutMs = numberOption(parsed.options, ["timeout", "timeout-ms", "timeoutMs"]) || 15000;
// 如果没有传入 --flow,先列出当前可用的调试数据源供用户参考
if (!flowCodeOrId) {
try {
const source = await getWorkflowDebugSource(client, pipelineId, { page: 1, pageSize: 5 });
if (runtime.jsonMode) {
return {
stdout: printJson(source, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const rows = source.items.map((it, idx) => [
idx + 1,
it.id,
it.title || "-",
it.flowState || "-",
]);
const out = [
`⚠️ 未指定测试单号,请通过 --flow=<单号> 传入测试单据。`,
"",
`── 工作流 [${pipelineId}] 最近可用测试数据源 (${source.label || "候选单据"}) ──`,
rows.length ? printTable(["#", "单据编号 (ID)", "单据名称 (Title)", "状态 (Status)"], rows) : "暂无可用测试单据",
"",
`示例: hose-use workflow test ${pipelineId} --flow=${source.items[0]?.id || "ZJ-xxxx"}`,
].join("\n");
return { stdout: `${out}\n`, stderr: "", exitCode: 1 };
} catch (err: any) {
return {
stdout: "",
stderr: `未指定测试单号 (--flow=<单号>),且拉取候选单据失败: ${err.message || String(err)}\n`,
exitCode: 1,
};
}
}
// 执行端到端调试测试
const report = await runWorkflowDebugTest(client, pipelineId, {
flowCodeOrId,
autoPublish,
timeoutMs,
});
if (runtime.jsonMode) {
return {
stdout: printJson(report, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const treeRows = report.executionTree.map((node, idx) => [
idx + 1,
node.id,
node.name || "-",
node.label || (node as any).displayName || "-",
node.type || "-",
node.status || "-",
String((node as any).durationTime ?? node.executionTime ?? "-"),
node.error?.message || "-",
]);
const outLines = [
`====== 工作流自动化调测报告 [${pipelineId}] ======`,
printKeyValue({
"工作流 ID (pipelineId)": pipelineId,
"生成 Job ID": report.jobId,
"测试目标单据": report.targetEntityId,
"执行结果状态": report.status,
"运行模式": report.runType,
"总耗时(ms)": String(report.durationTime ?? "-"),
"节点执行总数": report.executionTree.length,
"异常/跳过节点数": report.failedExecutions.length,
}),
"",
"── 顶层节点执行树 ──",
treeRows.length
? printTable(
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "耗时(ms)", "错误信息"],
treeRows
)
: "暂无顶层节点执行记录",
];
if (report.conditionDiagnoses.length > 0) {
outLines.push("");
outLines.push("── 💡 条件分支跳过诊断 (为什么没有走内部子任务?) ──");
for (const diag of report.conditionDiagnoses) {
outLines.push(` ⚠️ [${diag.conditionNodeName}] ${diag.conditionNodeLabel} (Execution ID: ${diag.conditionNodeId})`);
outLines.push(` • 判定结论: ${diag.summary}`);
outLines.push(` • 未执行子任务: ${diag.skippedTaskNames.join(", ")}`);
if (diag.rules.length > 0) {
outLines.push(" • 规则比对明细:");
for (const r of diag.rules) {
const statusIcon = r.matched ? "✅" : "❌";
const missTag = r.isMissing ? " [⚠️ 属性缺失]" : "";
outLines.push(` ${statusIcon} ${r.leftLabel} ${r.operatorLabel} ${JSON.stringify(r.expectedValue)}${missTag}`);
outLines.push(` ↳ ${r.detail}`);
}
}
}
}
return {
stdout: `${outLines.join("\n")}\n`,
stderr: "",
exitCode: report.status === "FAILED" ? 1 : 0,
};
}
+1 -1
View File
@@ -41,7 +41,7 @@ export const HELP_REGISTRY: Record<string, HelpTopic> = {
config: { summary: "全局运行模式与路径配置", usage: "hose-use config <子命令>", commands: { paths: "诊断配置目录链", get: "查看全局配置", mode: "切换 stateful/stateless", set: "更新指定配置项" } },
workflow: { summary: "工作流查询、草稿、运行排障与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流(含禁用/SKIP/联动覆盖检查)", job: "查看单次运行实例树、报错节点与MVEL日志", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作", "--file=<workflow.json> 指定工作流快照", "--failed 只看失败节点", "--parent=<executionId> 展开循环/分支子节点", "--logs=<executionId> 查看节点执行日志"] },
bill: { summary: "单据检索、表单规格诊断与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", spec: "查看单据模板字段配置与联动覆盖规则", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
platform: { summary: "自建应用、业务对象、全量记录安全更新与台账体检", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录(支持 --all 全量拉取)", record: "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)", audit: "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)", permissions: "查看权限", imports: "查看导入任务" }, options: ["--all 自动翻页拉取全量记录", "--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作", "--raw 跳过安全合并直接发送原始补丁"] },
platform: { summary: "自建应用、业务对象、全量记录安全更新与台账体检", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录(支持 --all / --ndjson 流式 / --stats 画像)", record: "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)", audit: "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)", permissions: "查看权限", imports: "查看导入任务" }, options: ["--all 自动翻页拉取全量记录", "--ndjson 流式逐行下发 JSON Lines ($O(1)内存)", "--flat 剥离底层实体动态字段前缀并提取引用", "--stats 输出总数/启停/重名/编码规则聚类画像", "--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作", "--raw 跳过安全合并直接发送原始补丁"] },
feetype: { summary: "费用类型全生命周期管理与模板规格查询", usage: "hose-use feetype <子命令> [参数]", commands: { list: "查看费用类型树", get: "查看详情与字段", spec: "查看单据/申请模板字段与联动规则", create: "新建费用类型", update: "修改属性", disable: "停用", enable: "启用", move: "移动层级", fields: "查看字段配置" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
rule: { summary: "本地审批规约管理", usage: "hose-use rule <子命令> [参数]", commands: { scopes: "列出适用场景", scope: "查看场景明细", list: "列出规则", get: "查看规则详情", add: "新增规则", delete: "删除规则" }, options: ["--dry-run 只预览增删", "--yes/--confirm 确认增删"] },
approval: { summary: "确定性审批网关与要点仲裁", usage: "hose-use approval audit <子命令> [单号]", commands: { points: "查看审核要点", checklist: "查看核验清单", review: "核验事实", decide: "生成或执行仲裁决定" }, options: ["--apply --yes 执行真实审批流转"] },
+58
View File
@@ -7,6 +7,8 @@ import {
protectLargeOutput,
printJson,
redactSensitiveText,
formatSourceLabel,
formatExpiresAt,
} from "./printer.js";
describe("cli/printer - 上下文防爆与敏感脱敏", () => {
@@ -114,4 +116,60 @@ describe("cli/printer - 上下文防爆与敏感脱敏", () => {
expect(savedContent[0].id).toBe("id-0");
});
});
describe("formatSourceLabel 4大凭证类别规范格式化", () => {
test("企业开放接口 (OpenAPI 密钥)", () => {
expect(formatSourceLabel("openapi")).toBe("企业开放接口 (OpenAPI 密钥)");
expect(formatSourceLabel("account", true)).toBe("企业开放接口 (OpenAPI 密钥)");
expect(formatSourceLabel("link", true)).toBe("企业开放接口 (OpenAPI 密钥)");
});
test("个人账号凭证 (手机号)", () => {
expect(formatSourceLabel("account")).toBe("个人账号凭证 (手机号)");
});
test("合思协助平台授权链接 (协助链接)", () => {
expect(formatSourceLabel("link")).toBe("合思协助平台授权链接 (协助链接)");
expect(formatSourceLabel("assist")).toBe("合思协助平台授权链接 (协助链接)");
});
test("网页临时抓包凭证 (Cookie)", () => {
expect(formatSourceLabel("curl")).toBe("网页临时抓包凭证 (Cookie)");
expect(formatSourceLabel("browser")).toBe("网页临时抓包凭证 (Cookie)");
expect(formatSourceLabel("f12")).toBe("网页临时抓包凭证 (Cookie)");
});
test("兜底处理", () => {
expect(formatSourceLabel("manual")).toBe("手动配置");
expect(formatSourceLabel("other")).toBe("其他 (other)");
expect(formatSourceLabel(undefined)).toBe("未知来源");
});
});
describe("formatExpiresAt 过期状态精准描述", () => {
test("长期有效凭据", () => {
expect(formatExpiresAt(undefined, true, "openapi")).toBe("长期有效 (OpenAPI 密钥)");
expect(formatExpiresAt(0, false)).toBe("长期有效 / 服务端未显式限制");
});
test("已过期但具备自动续期能力的凭据", () => {
const pastTime = Date.now() - 3600000;
expect(formatExpiresAt(pastTime, true, "account")).toContain("(🔄 随主账号自动换票)");
expect(formatExpiresAt(pastTime, true, "openapi")).toContain("(🔄 OpenAPI 密钥自动续期)");
expect(formatExpiresAt(pastTime, true)).toContain("(🔄 自动续期)");
});
test("已过期且不可续期的凭据精准告警", () => {
const pastTime = Date.now() - 3600000;
expect(formatExpiresAt(pastTime, false, "link")).toContain("(⚠️ 协助授权已失效)");
expect(formatExpiresAt(pastTime, false, "curl")).toContain("(⚠️ Cookie 已失效)");
expect(formatExpiresAt(pastTime, false, "manual")).toContain("(⚠️ 已过期)");
});
test("未来有效期的剩余提示", () => {
const futureMins = Date.now() + 30 * 60000;
expect(formatExpiresAt(futureMins, true, "account")).toContain("支持主账号自动换票");
expect(formatExpiresAt(futureMins, true, "openapi")).toContain("支持 OpenAPI 密钥自动续期");
});
});
});
+58 -18
View File
@@ -42,48 +42,88 @@ export function printJson(data: unknown, options: OutputOptions = {}): string {
}
export function formatSourceLabel(source?: string, persistentOpenApi?: boolean): string {
const suffix = persistentOpenApi && source !== "openapi" ? " + OpenAPI 持久化密钥" : "";
if (persistentOpenApi || source === "openapi") {
return "企业开放接口 (OpenAPI 密钥)";
}
switch (source) {
case "openapi":
return "开放平台持久化密钥 (OpenAPI AppKey)";
case "assist":
return `官方协助/代客平台 (Assist Platform)${suffix}`;
case "account":
return `统一认证中心 (IDP 账密/短信)${suffix}`;
case "browser":
return `浏览器会话同步 (WebBridge)${suffix}`;
return "个人账号凭证 (手机号)";
case "assist":
case "link":
return `协助/免密链接导入 (Assistance Link)${suffix}`;
return "合思协助平台授权链接 (协助链接)";
case "browser":
case "curl":
case "f12":
return `cURL 抓包导入 (cURL/F12)${suffix}`;
return "网页临时抓包凭证 (Cookie)";
case "manual":
return `手动配置${suffix}`;
return "手动配置";
default:
return (source || "未知来源") + suffix;
return source ? `其他 (${source})` : "未知来源";
}
}
export function formatExpiresAt(expiresAt?: number | null, persistent?: boolean): string {
if (!expiresAt || expiresAt <= 0) return "长期有效 / 服务端未显式限制";
export function formatExpiresAt(
expiresAt?: number | null,
persistent?: boolean,
source?: string
): string {
if (!expiresAt || expiresAt <= 0) {
if (source === "openapi") {
return "长期有效 (OpenAPI 密钥)";
}
return "长期有效 / 服务端未显式限制";
}
const diffMs = expiresAt - Date.now();
const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false });
if (diffMs <= 0) {
if (persistent) {
return `${dateStr} (🔄 持久化密钥自动续期)`;
if (source === "account") {
return `${dateStr} (🔄 随主账号自动换票)`;
}
if (source === "openapi") {
return `${dateStr} (🔄 OpenAPI 密钥自动续期)`;
}
return `${dateStr} (🔄 自动续期)`;
}
if (source === "link" || source === "assist") {
return `${dateStr} (⚠️ 协助授权已失效)`;
}
if (source === "curl" || source === "browser" || source === "f12") {
return `${dateStr} (⚠️ Cookie 已失效)`;
}
return `${dateStr} (⚠️ 已过期)`;
}
const diffMins = Math.floor(diffMs / 60000);
if (diffMins < 60) {
return `${dateStr} (约剩余 ${diffMins} 分钟${persistent ? ",支持自动续期" : ""})`;
const renewSuffix = persistent
? source === "account"
? ",支持主账号自动换票"
: source === "openapi"
? ",支持 OpenAPI 密钥自动续期"
: ",支持自动续期"
: "";
return `${dateStr} (约剩余 ${diffMins} 分钟${renewSuffix})`;
}
const diffHours = (diffMs / 3600000).toFixed(1);
if (Number(diffHours) < 24) {
return `${dateStr} (约剩余 ${diffHours} 小时${persistent ? ",支持自动续期" : ""})`;
const renewSuffix = persistent
? source === "account"
? ",支持主账号自动换票"
: source === "openapi"
? ",支持 OpenAPI 密钥自动续期"
: ",支持自动续期"
: "";
return `${dateStr} (约剩余 ${diffHours} 小时${renewSuffix})`;
}
const diffDays = Math.floor(diffMs / 86400000);
return `${dateStr} (约剩余 ${diffDays} 天)`;
const renewSuffix = persistent
? source === "account"
? ",支持主账号自动换票"
: source === "openapi"
? ",支持 OpenAPI 密钥自动续期"
: ""
: "";
return `${dateStr} (约剩余 ${diffDays} 天${renewSuffix})`;
}
export function printKeyValue(pairs: Record<string, unknown>): string {
+6
View File
@@ -11,6 +11,7 @@ import { handleMcpCommand } from "./commands/mcp.js";
import { handleUpdateCommand } from "./commands/update/index.js";
import { handleOpenApiCommand } from "./commands/openapi.js";
import { handleBillCommand } from "./commands/bill/index.js";
import { handleFlowCommand } from "./commands/flow.js";
import { handleContactCommand } from "./commands/contact.js";
import { handleServiceCommand } from "./commands/service.js";
import { handleHttpCommand } from "./commands/http.js";
@@ -81,6 +82,11 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
aliases: ["bills", "fee", "fees", "invoice", "invoices"],
handler: (parsed, runtime) => handleBillCommand(parsed, runtime),
},
{
area: "flow",
aliases: ["flows", "trace"],
handler: (parsed, runtime) => handleFlowCommand(parsed, runtime),
},
{
area: "contact",
aliases: ["contacts", "staff", "staffs"],
+17 -6
View File
@@ -401,6 +401,9 @@ export async function getCorpProvisionalAuthLink(
force?: boolean;
syncLocalSession?: boolean;
enterprisesDir?: string;
staffId?: string;
staffName?: string;
persistStaff?: boolean;
} = {}
): Promise<{
corpId: string;
@@ -418,7 +421,8 @@ export async function getCorpProvisionalAuthLink(
const expiresIn = parseExpiresInSeconds(explicitDuration, 7200);
const pageType = options.pageType || "home";
const corpId = corp.corpId || corp.credentials.corpId;
const staffId = corp.staffId || corp.credentials.staffId;
const targetStaffId = options.staffId || corp.staffId || corp.credentials.staffId;
const targetStaffName = options.staffName || (options.staffId ? undefined : corp.staffName || corp.session?.staffName);
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
// 1. 若尚未配置 appKey/appSecurity,先确保会话有效并尝试自动提权提取密钥
@@ -446,7 +450,7 @@ export async function getCorpProvisionalAuthLink(
baseUrl,
openapiToken,
corpId,
staffId,
staffId: targetStaffId,
expiresIn,
pageType,
});
@@ -458,6 +462,13 @@ export async function getCorpProvisionalAuthLink(
if (corp.session) {
corp.session.expTime = provisional.expiresAt;
}
if (options.persistStaff && options.staffId) {
corp.staffId = options.staffId;
corp.credentials.staffId = options.staffId;
if (options.staffName) {
corp.staffName = options.staffName;
}
}
saveCorpConfig(corp, options.enterprisesDir);
invalidateCorpSubdomainTokenCaches(corp);
}
@@ -465,8 +476,8 @@ export async function getCorpProvisionalAuthLink(
return {
corpId,
corpName: corp.name,
staffId: provisional.uid,
staffName: corp.staffName || corp.session?.staffName || undefined,
staffId: provisional.uid || targetStaffId,
staffName: targetStaffName || corp.staffName || corp.session?.staffName || undefined,
url: provisional.url,
token: provisional.token,
expiresIn: provisional.expiresIn,
@@ -511,8 +522,8 @@ export async function getCorpProvisionalAuthLink(
return {
corpId,
corpName: corp.name,
staffId,
staffName: corp.staffName || corp.session?.staffName || undefined,
staffId: targetStaffId,
staffName: targetStaffName || corp.staffName || corp.session?.staffName || undefined,
url,
token: corp.credentials.accessToken,
expiresIn: Math.max(1, Math.round((expMs - Date.now()) / 1000)),
+1 -44
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, statSync, utimesSync } from "node:fs";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
@@ -11,8 +11,6 @@ import {
loadGlobalConfig,
saveGlobalConfig,
resolveGlobalConfigFile,
syncLegacyEnterprisesDir,
syncLegacyGlobalConfig,
} from "./loader.js";
import { saveAccount, loadAccountStore, resolveAccountCachePath } from "../auth/account-store.js";
import type { CorpConfig } from "./types.js";
@@ -174,47 +172,6 @@ describe("core/config/loader", () => {
expect(updated.defaultCorpId).toBe("test-corp-123");
});
test("syncLegacyEnterprisesDir copies legacy credentials and removes stale legacy directory", () => {
const primary = join(tempDir, "primary");
const legacy = join(tempDir, "legacy");
mkdirSync(legacy, { recursive: true });
writeFileSync(join(legacy, "corp-old.json"), JSON.stringify(createMockCorp("corp-old", "旧企业")));
const old = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);
utimesSync(join(legacy, "corp-old.json"), old, old);
utimesSync(legacy, old, old);
const result = syncLegacyEnterprisesDir(primary, legacy);
expect(result.copied).toEqual(["corp-old.json"]);
expect(result.deletedLegacyDir).toBe(true);
expect(existsSync(join(primary, "corp-old.json"))).toBe(true);
expect(existsSync(legacy)).toBe(false);
});
test("syncLegacyEnterprisesDir preserves a recently modified legacy directory", () => {
const primary = join(tempDir, "primary-recent");
const legacy = join(tempDir, "legacy-recent");
mkdirSync(legacy, { recursive: true });
writeFileSync(join(legacy, "corp-recent.json"), JSON.stringify(createMockCorp("corp-recent", "近期企业")));
const result = syncLegacyEnterprisesDir(primary, legacy);
expect(result.deletedLegacyDir).toBe(false);
expect(existsSync(legacy)).toBe(true);
});
test("syncLegacyGlobalConfig migrates and removes a stale legacy config", () => {
const primary = join(tempDir, "config", "config.json");
const legacy = join(tempDir, "legacy-config.json");
writeFileSync(legacy, JSON.stringify({ stateful: false }));
const old = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);
utimesSync(legacy, old, old);
const result = syncLegacyGlobalConfig(primary, legacy);
expect(result.copied).toBe(true);
expect(result.deletedLegacyFile).toBe(true);
expect(JSON.parse(readFileSync(primary, "utf8")).stateful).toBe(false);
expect(existsSync(legacy)).toBe(false);
});
test("saveCorpConfig and saveAccount enforce 0o600 file permissions and respect HOSE_ACCOUNTS_FILE", () => {
const targetDir = join(tempDir, "secure-corps");
const corpFile = saveCorpConfig(createMockCorp("sec-1", "安全测试企业"), targetDir);
+2 -75
View File
@@ -1,4 +1,4 @@
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema, normalizeCorpConfig } from "./types.js";
@@ -8,13 +8,9 @@ const USER_DIR_ENV = "HOSE_USER_ENTERPRISES_DIR";
const GLOBAL_CONFIG_ENV = "HOSE_CONFIG_FILE";
export const PRIMARY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "hose-use", "enterprises");
export const LEGACY_USER_ENTERPRISES_DIR = join(homedir(), ".cache", "ekb-mcp", "enterprises");
export const USER_ENTERPRISES_DIR = PRIMARY_USER_ENTERPRISES_DIR;
export const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "hose-use", "config.json");
export const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".cache", "ekb-mcp", "config.json");
const LEGACY_CLEANUP_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
function ensureDir(dir: string): void {
mkdirSync(dir, { recursive: true, mode: 0o700 });
@@ -40,14 +36,7 @@ export function resolveEnterprisesDirs(): string[] {
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
const userDirs = configuredUserDir
? (existsSync(configuredUserDir) ? [configuredUserDir] : [])
: (() => {
try {
syncLegacyEnterprisesDir();
} catch {
// Legacy migration must never prevent normal CLI startup.
}
return [PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
})();
: [PRIMARY_USER_ENTERPRISES_DIR];
const globalConfig = loadGlobalConfig();
const testDir = globalConfig.testEnterprisesDir?.trim();
@@ -82,77 +71,15 @@ export function getEnterprisesDirCandidates(): string[] {
`${CONFIG_ENV}=<path>`,
...(testDir ? [`testEnterprisesDir: ${testDir}`] : []),
PRIMARY_USER_ENTERPRISES_DIR,
LEGACY_USER_ENTERPRISES_DIR,
];
}
export function resolveGlobalConfigFile(): string {
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
if (configured) return configured;
try {
syncLegacyGlobalConfig();
} catch {
// Legacy migration must never prevent normal CLI startup.
}
if (existsSync(PRIMARY_GLOBAL_CONFIG_FILE)) return PRIMARY_GLOBAL_CONFIG_FILE;
if (existsSync(LEGACY_GLOBAL_CONFIG_FILE)) return LEGACY_GLOBAL_CONFIG_FILE;
return PRIMARY_GLOBAL_CONFIG_FILE;
}
export function syncLegacyEnterprisesDir(
primaryDir: string = PRIMARY_USER_ENTERPRISES_DIR,
legacyDir: string = LEGACY_USER_ENTERPRISES_DIR
): { copied: string[]; deletedLegacyDir: boolean } {
if (!existsSync(legacyDir)) return { copied: [], deletedLegacyDir: false };
mkdirSync(primaryDir, { recursive: true, mode: 0o700 });
const copied: string[] = [];
const files = readdirSync(legacyDir).filter((file) => file.endsWith(".json"));
for (const file of files) {
const legacyPath = join(legacyDir, file);
const primaryPath = join(primaryDir, file);
if (!existsSync(primaryPath) || statSync(legacyPath).mtimeMs > statSync(primaryPath).mtimeMs) {
copyFileSync(legacyPath, primaryPath);
copied.push(file);
}
}
const now = Date.now();
const hasRecentEntry = readdirSync(legacyDir).some((file) => now - statSync(join(legacyDir, file)).mtimeMs < LEGACY_CLEANUP_GRACE_MS);
const hasNewerLegacyFile = files.some((file) => {
const legacyPath = join(legacyDir, file);
const primaryPath = join(primaryDir, file);
return existsSync(primaryPath) && statSync(legacyPath).mtimeMs > statSync(primaryPath).mtimeMs;
});
const directoryIsRecent = now - statSync(legacyDir).mtimeMs < LEGACY_CLEANUP_GRACE_MS;
const deletedLegacyDir = !hasRecentEntry && !hasNewerLegacyFile && !directoryIsRecent;
if (deletedLegacyDir) rmSync(legacyDir, { recursive: true, force: true });
return { copied, deletedLegacyDir };
}
export function syncLegacyGlobalConfig(
primaryFile: string = PRIMARY_GLOBAL_CONFIG_FILE,
legacyFile: string = LEGACY_GLOBAL_CONFIG_FILE
): { copied: boolean; deletedLegacyFile: boolean } {
if (!existsSync(legacyFile)) return { copied: false, deletedLegacyFile: false };
mkdirSync(dirname(primaryFile), { recursive: true, mode: 0o700 });
let copied = false;
if (!existsSync(primaryFile) || statSync(legacyFile).mtimeMs > statSync(primaryFile).mtimeMs) {
copyFileSync(legacyFile, primaryFile);
copied = true;
}
const oldEnough = Date.now() - statSync(legacyFile).mtimeMs >= LEGACY_CLEANUP_GRACE_MS;
const safeToDelete = existsSync(primaryFile) && statSync(legacyFile).mtimeMs <= statSync(primaryFile).mtimeMs && oldEnough;
if (safeToDelete) {
rmSync(legacyFile, { force: true });
return { copied, deletedLegacyFile: true };
}
return { copied, deletedLegacyFile: false };
}
export function loadGlobalConfig(): GlobalConfig {
const file = resolveGlobalConfigFile();
try {
+2
View File
@@ -20,6 +20,7 @@ export interface CorpSummary {
current: boolean;
expiresAt?: number;
persistent?: boolean;
hasOpenApi?: boolean;
}
export function resolveCorpConfig(
@@ -172,6 +173,7 @@ export class CorpContext {
current: corp.id === this.current?.id,
expiresAt: getCorpExpiresAt(corp),
persistent: hasOpenApiKeys || hasAccountBinding,
hasOpenApi: hasOpenApiKeys,
};
});
}
+3 -3
View File
@@ -1,6 +1,6 @@
import { Database } from "bun:sqlite";
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { closeApprovalDatabase, getApprovalDatabase } from "./db.js";
import { closeDatabase, getDatabase } from "../../core/db/index.js";
import { ApprovalRepository } from "./repository.js";
import { ApprovalService } from "./service.js";
import { ApprovalRuleValidationError } from "./types.js";
@@ -11,12 +11,12 @@ describe("Approval Domain - SQLite 持久化与规约仓储", () => {
beforeEach(() => {
// 每次测试使用独立的内存数据库,隔离状态
db = getApprovalDatabase(":memory:");
db = getDatabase(":memory:");
repo = new ApprovalRepository(db);
});
afterEach(() => {
closeApprovalDatabase();
closeDatabase();
});
test("数据库初始化时自动种子化默认偏好配置", () => {
-35
View File
@@ -1,35 +0,0 @@
import type { Database } from "bun:sqlite";
import {
DEFAULT_DB_PATH,
closeDatabase,
getDatabase,
resolveDatabasePath,
runMigrations,
} from "../../core/db/index.js";
export const DEFAULT_APPROVAL_DB_PATH = DEFAULT_DB_PATH;
export function resolveApprovalDbPath(): string {
return resolveDatabasePath();
}
/**
* 获取或创建 SQLite 数据库连接单例(兼容原接口,底层使用 core/db)
*/
export function getApprovalDatabase(customPath?: string): Database {
return getDatabase(customPath);
}
/**
* 关闭并清理当前数据库连接
*/
export function closeApprovalDatabase(): void {
closeDatabase();
}
/**
* 初始化表结构与默认数据(兼容原接口,委托给 runMigrations)
*/
export function initDatabaseSchema(db: Database): void {
runMigrations(db);
}
-1
View File
@@ -1,6 +1,5 @@
export * from "./types.js";
export * from "./parser.js";
export * from "./db.js";
export * from "./repository.js";
export * from "./service.js";
export * from "./gateway.js";
+7 -1
View File
@@ -41,5 +41,11 @@ src/domains/bill/
- `transferBill` 与 `addNodeBill` 共用 backlog 动作接口,分别使用 `SHIFT_NODE`、`PRE_ADD_NODE`/`AFT_ADD_NODE`;
- `commentBill` 调用 `POST /api/flow/v1/flows/comment/$<flowId>`,使用 `freeflow.comment`,保留参与人和私密评论参数;
- 动作执行前从审批详情解析 backlog ID、流程 ID、当前节点 ID,并可依据 `flow.actions` 校验当前身份是否具备该动作权限。
8. **全域单据穿透与待办诊断 (`traceBillFlowDetail`)**:
- 跨 `backlogs/search`、`flows/my`、`flows/approved`、`carbonCopy/search` 与 `backlogs/id` 多通道穿透检索单据流程实例;
- 智能提取单据金额、提报人、提报时间、归属部门、当前驻留节点与待办审批人列表;
- 内置待办根因诊断引擎,智能判定流转阶段(`DRAFT`、`APPROVING`、`PAYING`、`PAID`、`REJECTED`):
- 识别“待出纳支付/打款”节点(如 `PAYING` 或节点名包含“打款/出纳/支付”),精准提示不可审批及自动化工作流调用报错 400(无待办审批事项)的根本原因与排障建议;
- 结构化还原流转时间线轨迹(Timeline),自动标记 Ebot 智能审批与自动跳过节点。
CLI 入口为 `hose-use bill approve|reject|transfer|add-node|comment <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。
CLI 入口为 `hose-use bill approve|reject|transfer|add-node|comment <单号|ID>`,以及 `hose-use flow [get|trace] <单号|ID>` / `hose-use bill trace <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。
+73 -27
View File
@@ -63,12 +63,16 @@ export async function getRawBillFlow(
corpId: string,
target: string
): Promise<Record<string, unknown> | undefined> {
const cleanTarget = target.trim();
let match: Record<string, unknown> | undefined;
const filters = [
`(id==${quoted(target)})||((flowId.id==${quoted(target)})||(flowId.form.code==${quoted(target)}))`,
// 通道 1: api/flow/v2/backlogs/search 精准单号与 ID 匹配
const searchFilters = [
`(id==${quoted(cleanTarget)})||((flowId.id==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)}))`,
`(flowId.form.code==${quoted(cleanTarget)})`,
`(state.in("APPROVING","PROCESSED","REJECTED","DRAFT"))`,
];
for (const filterBy of filters) {
for (const filterBy of searchFilters) {
try {
const lookup = await client.post("api/flow/v2/backlogs/search", {
searchParams: { corpId },
@@ -82,36 +86,78 @@ export async function getRawBillFlow(
match = (lookupJson.items ?? []).find((item) => {
const flow = item.flowId && typeof item.flowId === "object" ? item.flowId as Record<string, unknown> : {};
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
return item.id === target || flow.id === target || form.code === target;
return item.id === cleanTarget || flow.id === cleanTarget || form.code === cleanTarget;
});
if (match) break;
} catch {
// Fall through to the broad status lookup or direct detail request.
// 继续尝试其他检索
}
}
const backlogId = typeof match?.id === "string" ? match.id : target;
const detail = await client.post("api/flow/v2/backlogs/id", {
searchParams: (() => {
const params = new URLSearchParams({ corpId });
for (const join of [
"flowId.form.submitterId,submitterId,/v1/organization/staffs?join=defaultDepartment,defaultDepartment,/v1/organization/departments",
"flowId.form.ownerId,ownerId,/v1/organization/staffs?select=id,name,code",
"flowId.form.expenseDepartment,expenseDepartment,/v1/organization/departments",
"flowId.logs.operatorId,operatorId,/v1/organization/staffs?select=id,name,code",
"flowId.logs.nextOperatorId,nextOperatorId,/v1/organization/staffs?select=id,name,code",
"flowId.plan.nodes.approverId,approverId,/v1/organization/staffs?select=id,name,code",
"flowId.plan.nodes.counterSigners.signerId,signerId,/v1/organization/staffs?select=id,name,code",
]) params.append("join", join);
return params;
})(),
json: {
filterBy: `(id==${quoted(backlogId)})`,
select: flowDetailSelect(),
},
});
const json = (await detail.json()) as { value?: Record<string, unknown>; items?: Record<string, unknown>[] };
return json.value ?? json.items?.[0];
// 通道 2: 尝试从我发起的流程与已审批单据中检索 (flows/my & flows/approved)
if (!match) {
const endpoints = ["api/flow/v1/flows/my", "api/flow/v1/flows/approved", "api/flow/v2/carbonCopy/search"];
for (const ep of endpoints) {
try {
const res = await client.post(ep, {
searchParams: { corpId },
json: {
limit: { start: 0, count: 50 },
filterBy: `(form.code==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)})`,
},
});
const json = (await res.json()) as { items?: Record<string, unknown>[] };
const found = (json.items ?? []).find((item) => {
const flow = item.flowId && typeof item.flowId === "object" ? item.flowId as Record<string, unknown> : {};
const form = (flow.form ?? item.form) as Record<string, unknown> | undefined;
return item.id === cleanTarget || flow.id === cleanTarget || form?.code === cleanTarget;
});
if (found) {
match = found;
break;
}
} catch {
// 忽略通道异常
}
}
}
const backlogId = typeof match?.id === "string" ? match.id : cleanTarget;
const flowIdFromMatch = match?.flowId && typeof match.flowId === "object" && typeof (match.flowId as any).id === "string"
? (match.flowId as any).id
: undefined;
// 通道 3: 调用 api/flow/v2/backlogs/id 获取完整结构化详情
try {
const filterByCond = flowIdFromMatch
? `(id==${quoted(backlogId)})||(flowId.id==${quoted(flowIdFromMatch)})`
: `(id==${quoted(backlogId)})||((flowId.id==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)}))`;
const detail = await client.post("api/flow/v2/backlogs/id", {
searchParams: (() => {
const params = new URLSearchParams({ corpId });
for (const join of [
"flowId.form.submitterId,submitterId,/v1/organization/staffs?join=defaultDepartment,defaultDepartment,/v1/organization/departments",
"flowId.form.ownerId,ownerId,/v1/organization/staffs?select=id,name,code",
"flowId.form.expenseDepartment,expenseDepartment,/v1/organization/departments",
"flowId.logs.operatorId,operatorId,/v1/organization/staffs?select=id,name,code",
"flowId.logs.nextOperatorId,nextOperatorId,/v1/organization/staffs?select=id,name,code",
"flowId.plan.nodes.approverId,approverId,/v1/organization/staffs?select=id,name,code",
"flowId.plan.nodes.counterSigners.signerId,signerId,/v1/organization/staffs?select=id,name,code",
]) params.append("join", join);
return params;
})(),
json: {
filterBy: filterByCond,
select: flowDetailSelect(),
},
});
const json = (await detail.json()) as { value?: Record<string, unknown>; items?: Record<string, unknown>[] };
return json.value ?? json.items?.[0] ?? match;
} catch (err) {
if (match) return match;
throw err;
}
}
export interface BillActionTarget {
+126
View File
@@ -17,6 +17,7 @@ import {
normalizeSearchFields,
buildServerBillFilterBy,
searchAndFormatBills,
traceBillFlowDetail,
} from "./tools.js";
import { RawBillItemSchema, EntitySchema } from "./types.js";
@@ -712,5 +713,130 @@ describe("Bill Domain", () => {
expect(resDefault.items.map((b) => b.billId)).toEqual(["bill-2", "bill-3"]);
});
});
describe("traceBillFlowDetail 全域穿透诊断与待办根因分析", () => {
it("待审批状态:精准解析提报人、金额、当前节点与待办审批人,判定可审批", async () => {
const mockRawFlow = {
id: "backlog-101",
state: "APPROVING",
flowId: {
id: "flow-101",
state: "APPROVING",
form: {
code: "BX-20261014-001",
title: "差旅费用报销单",
expenseMoney: { amount: "1280.50" },
submitDate: 1781682826000,
submitterId: { id: "staff-1", name: "张三", code: "ZS01" },
expenseDepartment: { name: "研发部" },
specificationId: { id: "spec-bx", name: "日常报销单" },
},
plan: {
nextNodeId: "node-2",
nodes: [
{ id: "node-1", name: "提单", state: "PROCESSED" },
{ id: "node-2", name: "直属主管审批", state: "APPROVING", approverId: { id: "staff-2", name: "李主管", code: "LZ01" } },
],
},
logs: [
{
action: "SUBMIT",
time: 1781682826000,
operatorId: { id: "staff-1", name: "张三" },
attributes: { nodeName: "提单", comment: "请领导审批" },
},
],
},
};
const client = {
post: async (path: string) => {
if (path.includes("backlogs/search")) {
return new Response(JSON.stringify({ items: [mockRawFlow] }));
}
if (path.includes("backlogs/id")) {
return new Response(JSON.stringify({ value: mockRawFlow }));
}
return new Response(JSON.stringify({ items: [] }));
},
} as any;
const report = await traceBillFlowDetail(client, "test-corp", "BX-20261014-001");
expect(report.found).toBe(true);
expect(report.billCode).toBe("BX-20261014-001");
expect(report.amount).toBe("¥ 1280.50");
expect(report.submitter?.name).toBe("张三");
expect(report.department).toBe("研发部");
expect(report.state).toBe("审批中");
expect(report.currentNode?.name).toBe("直属主管审批");
expect(report.pendingApprovers).toHaveLength(1);
expect(report.pendingApprovers[0].name).toBe("李主管");
expect(report.diagnostic.stage).toBe("APPROVING");
expect(report.diagnostic.canApprove).toBe(true);
expect(report.diagnostic.summary).toContain("待办审批人: 李主管");
expect(report.timeline).toHaveLength(1);
expect(report.timeline[0].action).toBe("SUBMIT");
});
it("待出纳打款节点 (PAYING):精准识别并诊断 400 根因与排障建议", async () => {
const mockRawFlow = {
id: "backlog-paying-01",
state: "APPROVING",
nodeName: "出纳打款",
flowId: {
id: "flow-paying-01",
state: "PAYING",
form: {
code: "ZJ-20261014-999",
title: "对公转账调拨",
payMoney: "50000.00",
specificationId: { id: "spec-zj", name: "资金调拨单" },
},
plan: {
nodes: [
{ id: "n1", name: "财务复核", state: "PROCESSED" },
{ id: "n2", name: "出纳打款", state: "APPROVING" },
],
},
logs: [
{
action: "AGREE",
time: 1781683000000,
operatorId: { id: "ebot_system", name: "ebot" },
attributes: { isEbotNode: true, nodeName: "智能审核", comment: "风控核验通过" },
},
],
},
};
const client = {
post: async () => new Response(JSON.stringify({ value: mockRawFlow })),
} as any;
const report = await traceBillFlowDetail(client, "test-corp", "ZJ-20261014-999");
expect(report.found).toBe(true);
expect(report.diagnostic.stage).toBe("PAYING");
expect(report.diagnostic.canApprove).toBe(false);
expect(report.diagnostic.stageLabel).toBe("待支付 / 出纳打款");
expect(report.diagnostic.summary).toContain("出纳打款");
expect(report.diagnostic.advice).toContain("400");
expect(report.timeline[0].operator?.name).toBe("Ebot (智能审批)");
expect(report.timeline[0].automatic).toBe(true);
});
it("单据不存在时返回友好未找到诊断报告", async () => {
const client = {
post: async () => new Response(JSON.stringify({ items: [] })),
} as any;
const report = await traceBillFlowDetail(client, "test-corp", "NOT-EXIST-999");
expect(report.found).toBe(false);
expect(report.target).toBe("NOT-EXIST-999");
expect(report.diagnostic.canApprove).toBe(false);
expect(report.diagnostic.stage).toBe("UNKNOWN");
expect(report.diagnostic.advice).toContain("请核对单号是否准确");
});
});
});
+254
View File
@@ -55,6 +55,8 @@ import {
type BillRelationsReport,
type BillAttachment,
type BillAttachmentReport,
type BillFlowTimelineItem,
type BillFlowTraceDiagnostic,
type FormSpecification,
type FormSpecificationComponent,
type FormPriorityItem,
@@ -960,6 +962,258 @@ export async function getBillFlow(
};
}
function resolveFlowStage(
rawState: string,
nodeName?: string
): "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN" {
const s = rawState.toUpperCase();
const n = (nodeName || "").toLowerCase();
if (s.includes("REJECT") || s === "TERMINATED") return "REJECTED";
if (s === "PAID" || s === "COMPLETED" || s === "PROCESSED") return "PAID";
if (s.includes("PAY") || n.includes("打款") || n.includes("出纳") || n.includes("支付")) return "PAYING";
if (s.includes("APPROV") || s === "PENDING" || s === "SENDING") return "APPROVING";
if (s.includes("DRAFT")) return "DRAFT";
return "UNKNOWN";
}
function buildDiagnosticReport(
stage: "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN",
rawState: string,
currentNodeName?: string,
pendingApprovers: { id?: string; name?: string; code?: string }[] = []
): {
canApprove: boolean;
stage: "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN";
stageLabel: string;
summary: string;
advice: string;
} {
const approverNames = pendingApprovers.map((p) => p.name || p.id).filter(Boolean).join("、");
switch (stage) {
case "PAYING":
return {
canApprove: false,
stage,
stageLabel: "待支付 / 出纳打款",
summary: `单据已通过全部分级审批流转,当前停留在【${currentNodeName || "出纳打款"}】环节`,
advice: "该单据当前无待办审批任务,若调用自动审批接口必报 400(无待办审批事项)。出纳打款后单据即闭环;若属于自动化打款流水,请检查工作流触发器是否误推了待支付单据,建议增加条件【审批状态 等于 APPROVING】进行拦截。",
};
case "APPROVING":
return {
canApprove: true,
stage,
stageLabel: "审批中 (待办审批)",
summary: `单据当前停留在【${currentNodeName || "审批"}】节点${approverNames ? `,待办审批人: ${approverNames}` : ""}`,
advice: "单据处于正常待办审批状态,当前待办人员或工作流自动化可正常执行同意 (agree) 或驳回 (reject) 操作。",
};
case "REJECTED":
return {
canApprove: false,
stage,
stageLabel: "已驳回 / 已终止",
summary: "单据已流转至驳回或终止状态",
advice: "单据已终止流转,无法执行审批同意。请联系提报人员根据驳回意见重新修改并提交新单据。",
};
case "PAID":
return {
canApprove: false,
stage,
stageLabel: "已闭环 / 已打款",
summary: "单据全流程已审批并通过出纳打款闭环",
advice: "单据已结束流转,无需任何人工或自动化操作。",
};
case "DRAFT":
return {
canApprove: false,
stage,
stageLabel: "草稿未提交",
summary: "单据尚未正式提交进入审批流",
advice: "请提报人完成单据填写后点击提交。",
};
default:
return {
canApprove: false,
stage,
stageLabel: rawState || "未知状态",
summary: `单据当前处于状态: ${rawState || "未知"}`,
advice: "请通过 Web 后台或联系管理员核对单据流转配置。",
};
}
}
/**
* 全域单据穿透诊断与待办全貌洞察
*/
export async function traceBillFlowDetail(
client: KyInstance,
corpId: string,
targetQuery: string
): Promise<BillFlowTraceDiagnostic> {
const cleanTarget = targetQuery.trim();
if (!cleanTarget) {
throw new ValidationError("请提供要穿透查询的单号或单据 ID");
}
// 1. 尝试直接获取流程全貌
let rawFlow = await getRawBillFlow(client, corpId, cleanTarget);
// 2. 如果直接流程未命中,尝试通过传统单据索引反查
if (!rawFlow) {
try {
const bills = await getBillByCodeOrId(client, corpId, cleanTarget);
if (bills.length > 0) {
const firstBill = bills[0];
const candidateId = firstBill.billId || firstBill.billCode;
if (candidateId) {
rawFlow = await getRawBillFlow(client, corpId, candidateId);
}
}
} catch {
// 容错并继续
}
}
if (!rawFlow) {
return {
found: false,
target: cleanTarget,
pendingApprovers: [],
diagnostic: {
canApprove: false,
stage: "UNKNOWN",
stageLabel: "未找到",
summary: `在当前企业下未找到匹配 "${cleanTarget}" 的单据或流程实例`,
advice: "请核对单号是否准确,或确认当前账号是否具备该业务流程的查看权限。",
},
timeline: [],
};
}
const flow = rawFlow.flowId && typeof rawFlow.flowId === "object" ? (rawFlow.flowId as Record<string, unknown>) : {};
const form = flow.form && typeof flow.form === "object" ? (flow.form as Record<string, unknown>) : ((rawFlow.form as Record<string, unknown>) || {});
const spec = form.specificationId && typeof form.specificationId === "object" ? (form.specificationId as Record<string, unknown>) : {};
const nodeState = rawFlow.nodeState && typeof rawFlow.nodeState === "object" ? (rawFlow.nodeState as Record<string, unknown>) : {};
const plan = flow.plan && typeof flow.plan === "object" ? (flow.plan as Record<string, unknown>) : {};
const nodes = Array.isArray(plan.nodes) ? (plan.nodes as Record<string, unknown>[]) : [];
const logs = Array.isArray(flow.logs) ? (flow.logs as Record<string, unknown>[]) : [];
// 基础信息提取
const billCode = typeof form.code === "string" ? form.code : typeof rawFlow.code === "string" ? rawFlow.code : undefined;
const billId = typeof rawFlow.id === "string" ? rawFlow.id : typeof form.id === "string" ? form.id : undefined;
const flowId = typeof flow.id === "string" ? flow.id : undefined;
const backlogId = typeof rawFlow.id === "string" ? rawFlow.id : undefined;
const specificationName = typeof spec.name === "string" ? spec.name : undefined;
const specificationId = typeof spec.id === "string" ? spec.id : undefined;
const title = typeof form.title === "string" ? form.title : typeof form.name === "string" ? form.name : undefined;
// 金额提取
let amountStr: string | undefined;
const rawMoney = form.expenseMoney || form.payMoney || form.loanMoney || form.requisitionMoney || form.amount;
if (rawMoney && typeof rawMoney === "object") {
const std = (rawMoney as any).standard ?? (rawMoney as any).amount;
if (std !== undefined) amountStr = `¥ ${std}`;
} else if (typeof rawMoney === "string" || typeof rawMoney === "number") {
amountStr = `¥ ${rawMoney}`;
}
// 提交人与部门
const submitter = flowPerson(form.submitterId || flow.ownerId);
const deptObj = form.expenseDepartment || form.defaultDepartment;
const department = deptObj && typeof deptObj === "object" ? (deptObj as any).name : undefined;
const submitDate = typeof form.submitDate === "number" ? new Date(form.submitDate).toLocaleString("zh-CN", { hour12: false }) : undefined;
// 状态提取
const rawState = String(rawFlow.state || flow.state || form.state || "").toUpperCase();
const stateLabel = translateBillFlowState(rawState);
// 当前驻留节点提取
const nextNodeId = typeof plan.nextNodeId === "string" ? plan.nextNodeId : undefined;
const currentNodeName = typeof rawFlow.nodeName === "string" ? rawFlow.nodeName : typeof nodeState.nodeName === "string" ? nodeState.nodeName : undefined;
let activeNode = nodes.find((n) => (nextNodeId && n.id === nextNodeId) || (currentNodeName && n.name === currentNodeName));
if (!activeNode && nodes.length > 0) {
activeNode = nodes.find((n) => n.state === "APPROVING" || n.state === "approving" || n.status === "ACTIVE");
}
const currentNode = activeNode
? {
id: typeof activeNode.id === "string" ? activeNode.id : undefined,
name: typeof activeNode.name === "string" ? activeNode.name : currentNodeName,
type: typeof activeNode.type === "string" ? activeNode.type : undefined,
}
: currentNodeName
? { name: currentNodeName }
: undefined;
// 待办审批人提取
const pendingApprovers: { id?: string; name?: string; code?: string }[] = [];
if (activeNode) {
if (activeNode.approverId) {
const p = flowPerson(activeNode.approverId);
if (p) pendingApprovers.push(p);
}
if (Array.isArray(activeNode.counterSigners)) {
for (const signer of activeNode.counterSigners) {
const p = flowPerson(signer);
if (p) pendingApprovers.push(p);
}
}
}
// 诊断规则引擎
const stage = resolveFlowStage(rawState, currentNode?.name);
const diagnostic = buildDiagnosticReport(stage, rawState, currentNode?.name, pendingApprovers);
// 流转时间线
const timeline: BillFlowTimelineItem[] = logs.map((log, index) => {
const attrs = (log.attributes as Record<string, unknown>) || {};
const op = flowPerson(log.operatorId);
const isEbot = attrs.isEbotNode === true || `${op?.id || ""} ${op?.name || ""}`.toLowerCase().includes("ebot");
const labeledOp = isEbot ? { ...(op || { id: "ebot" }), name: "Ebot (智能审批)" } : op;
const timeNum = typeof log.time === "number" ? log.time : undefined;
return {
index: index + 1,
time: timeNum ? new Date(timeNum).toLocaleString("zh-CN", { hour12: false }) : undefined,
timestamp: timeNum,
action: translateBillFlowAction(typeof log.action === "string" ? log.action : undefined),
rawAction: typeof log.action === "string" ? log.action : undefined,
state: translateBillFlowState(typeof log.state === "string" ? log.state : undefined),
rawState: typeof log.state === "string" ? log.state : undefined,
nodeName: typeof attrs.nodeName === "string" ? attrs.nodeName : typeof attrs.nextName === "string" ? attrs.nextName : undefined,
operator: labeledOp,
comment: typeof attrs.comment === "string" ? attrs.comment.replace(/<[^>]+>/g, "").trim() : undefined,
automatic: attrs.isEbotNode === true || attrs.isAuto === true || !log.operatorId,
skipped: attrs.isSkip === true || attrs.skipped === true || log.state === "SKIPPED",
};
});
return {
found: true,
target: cleanTarget,
billCode,
billId,
flowId,
backlogId,
specificationName,
specificationId,
title,
amount: amountStr,
submitter,
department,
submitDate,
state: stateLabel,
rawState,
currentNode,
pendingApprovers,
diagnostic,
timeline,
raw: rawFlow,
};
}
function actionTarget(raw: Record<string, unknown>, fallback: string): BillActionTarget {
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> : {};
+49
View File
@@ -290,3 +290,52 @@ export interface BillAttachmentReport {
attachments: BillAttachment[];
raw: Record<string, unknown>;
}
// ── 流程单据全貌穿透与待办诊断模型 ──────────────────────────────────────────
export interface BillFlowTimelineItem {
index: number;
time?: string;
timestamp?: number;
durationMs?: number;
action?: string;
rawAction?: string;
state?: string;
rawState?: string;
nodeName?: string;
operator?: { id?: string; name?: string; code?: string };
nextOperators?: { id?: string; name?: string; code?: string }[];
comment?: string;
automatic?: boolean;
skipped?: boolean;
}
export interface BillFlowTraceDiagnostic {
found: boolean;
target: string;
billCode?: string;
billId?: string;
flowId?: string;
backlogId?: string;
specificationName?: string;
specificationId?: string;
title?: string;
amount?: string;
submitter?: { id?: string; name?: string; code?: string };
department?: string;
submitDate?: string;
state?: string;
rawState?: string;
currentNode?: { id?: string; name?: string; type?: string };
pendingApprovers: { id?: string; name?: string; code?: string }[];
diagnostic: {
canApprove: boolean;
stage: "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN";
stageLabel: string;
summary: string;
advice: string;
};
timeline: BillFlowTimelineItem[];
raw?: Record<string, unknown>;
}
+39 -4
View File
@@ -30,20 +30,55 @@ hose-use platform list
hose-use platform get <应用 ID|名称>
hose-use platform entities <应用 ID|名称>
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--all] [--keyword <关键词>] [--filter <表达式>] [--fields <字段列表>]
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--all] [--keyword <关键词>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats]
hose-use platform record get [<应用> <业务对象>] <记录ID>
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
hose-use platform record edit <应用> <业务对象> <记录ID> --data='{"field": "val"}' [--raw] [--dry-run|--yes]
hose-use platform record batch-edit <应用> <业务对象> [--ids=id1,id2|--filter=...] --data='{"field": "val"}' [--concurrency=8] [--dry-run|--yes]
hose-use platform record edit <应用> <业务对象> <记录ID> [--set="字段=值" | --data='{"field": "val"}'] [--raw] [--dry-run|--yes]
hose-use platform record update <应用> <业务对象> [--where="条件"] --set="字段=值" [--dry-run|--yes]
hose-use platform record batch-edit <应用> <业务对象> [--where="条件"|--ids=id1,id2|--filter=...] [--set="字段=值"|--data='{"field": "val"}'] [--concurrency=8] [--dry-run|--yes]
hose-use platform record recompute <应用> <业务对象> <记录ID> [--dry-run|--yes]
hose-use platform audit <应用 ID|名称> <对象 ID|名称> [--check-fields=字段1,字段2] [--active-only]
hose-use platform audit <应用 ID|名称> <对象 ID|名称> [--check-fields=字段1,字段2] [--active-only] [--check-continuous=序号字段] [--expect="字段 ~= 期望值 [+- 容差]"]
hose-use platform permissions <应用 ID|名称> [对象 ID|名称]
hose-use platform imports <应用 ID|名称> <对象 ID|名称>
```
也可以使用 `datalink` / `data-link` 作为同义命令域。
- `records --ndjson`(或 `--stream`):针对万级~十万级海量记录,采用 AsyncGenerator 分页流式生成,逐行向 `stdout` 发射 NDJSON。内存恒定为 $O(\text{pageSize})$,严防大报文撑爆内存或终端,无缝对接下游 `jq`、Python 处理流水线。
- `records --stats`(或 `records stats <应用> <对象>` / `records profile`):宏观结构与特征聚类画像。输出总记录数、启用/停用分布及占比、唯一标题数与重名分布、编码生成规则聚类(自动提取 `${groupIndex}-${formCode}-month-${idx}` 等动态模板分布)、最早与最新维护时间,毫秒级洞察数据特征。
- `records --flat`:自动剥离底层动态物理前缀(如 `E_<entityId>_`),提取关联引用对象的名称/编码,将复杂元数据规整为 `{ id, code, name, active, createTime, updateTime, fields }` 干净对象。
- `records --sum="字段1,字段2" [--group-by="分组字段"]`:台账数学聚合核算,自动解析纯数值、金额对象(`{ standard: 100 }`)与货币符号字符串(`¥12,500.00`),输出样本数、总合计(SUM)、均值(AVG)、最小值(MIN)、最大值(MAX)以及指定字段的分组小计。
- `records --where="条件"`:支持在客户端按字段中文标签或物理名做声明式组合过滤(支持 `==`, `!=`, `>`, `<`, `>=`, `<=`, `in (...)`, 以及 `&&` 联合条件)。
- `audit --check-continuous="序号字段"`:台账连续性体检,精准识别期数序号序列中的断层缺失(MISSING)与重号重复(DUPLICATE)。
- `audit --expect="字段 ~= 期望值 [+- 容差]"`:基线数值离群诊断,自动识别并列出偏离基准值的异常记录明细与差额。
- `record update <应用> <业务对象> [--where="条件"] --set="字段=值" [--dry-run] [--yes]`:声明式原地批量修改,支持中文字段标签解析与智能类型转换,通过 `--dry-run` 预览拟更新记录与合并后字段,追加 `--yes` 真正执行。
- `record get` 支持直传 `<记录ID>` 免传应用与业务对象。
- `record edit` 与 `record batch-edit` 默认启用 **Read-Modify-Write 安全全量合并**(保留全部 `E_<entityId>_*` 字段、将嵌套引用对象归一化为字符串 ID、保留 `active` 与 `visibility` 结构,支持字段短名/中文标签映射);仅当显式传入 `--raw` 时才直接透传原始补丁。
- `records --all` 自动按 `500` 条/页循环拉取全量台账记录。
- `audit` 一键巡检必填/指定字段缺失、引用已停用档案以及跨台账同名字段同步差异,并输出 `suggestedPatches`。
## 公共 SDK (`hose-use/sdk`)
对于需要针对十万级业务记录编写个性化业务循环、分析或报表导出的脚本,直接通过 `hose-use/sdk` 引入标准公共 API,彻底告别依赖 CLI 内部文件路径:
```typescript
import {
initCorpRuntime,
resolvePlatform,
resolveEntity,
iterateAllEntityRecords,
normalizeDatalinkRecord,
calculateEntityRecordStats,
} from "hose-use/sdk";
const runtime = await initCorpRuntime();
const platform = await resolvePlatform(runtime.clients.ekbClient, "新转转集团");
const entity = await resolveEntity(runtime.clients.ekbClient, platform.id, "合同");
// 1. 万级海量数据 $O(1)$ 内存流式遍历
for await (const rawRecord of iterateAllEntityRecords(runtime.clients.ekbClient, runtime.corpId, entity.id, { pageSize: 200 })) {
const record = normalizeDatalinkRecord(rawRecord, entity);
// 执行业务逻辑...
}
```
+251
View File
@@ -11,10 +11,18 @@ import {
toggleRecordState,
} from "./api.js";
import {
aggregateRecordFields,
auditEntityRecords,
auditLedgerContinuityAndBaseline,
batchSafeEditRecords,
buildKeywordFilter,
calculateEntityRecordStats,
fetchAllEntityRecords,
filterRecordsByPredicate,
iterateAllEntityRecords,
normalizeDatalinkRecord,
parseExpectClause,
parseSetClause,
selectRecordFields,
} from "./services.js";
@@ -386,5 +394,248 @@ describe("DataLink Domain - 应用、业务对象与记录查询", () => {
expect(results[0]?.status).toBe("preview");
expect(results[0]?.payload?.form.E_e1_company).toBe("ID01RnG3b79daL");
});
test("aggregateRecordFields 准确统计数值、金额对象、货币字符串并支持分组", () => {
const entity = {
id: "e_lease",
name: "租金台账",
fields: [
{ name: "E_e_lease_period", label: "期数", type: "number" },
{ name: "E_e_lease_rent", label: "租赁费用", type: "money" },
{ name: "E_e_lease_status", label: "状态", type: "text" },
],
actions: [],
importMethod: [],
};
const records = [
{ id: "1", E_e_lease_period: 1, E_e_lease_rent: { standard: 10000 }, E_e_lease_status: "已摊销" },
{ id: "2", E_e_lease_period: 2, E_e_lease_rent: 15000, E_e_lease_status: "已摊销" },
{ id: "3", E_e_lease_period: 3, E_e_lease_rent: "¥20,000.00", E_e_lease_status: "待摊销" },
];
const report = aggregateRecordFields(records as any, entity as any, {
fields: ["租赁费用"],
groupBy: "状态",
});
expect(report.totalRecords).toBe(3);
const rentStats = report.overall["租赁费用"];
expect(rentStats).toBeDefined();
expect(rentStats?.count).toBe(3);
expect(rentStats?.sum).toBe(45000);
expect(rentStats?.avg).toBe(15000);
expect(rentStats?.min).toBe(10000);
expect(rentStats?.max).toBe(20000);
expect(report.groups).toHaveLength(2);
const amortizedGroup = report.groups?.find((g) => g.groupValue === "已摊销");
expect(amortizedGroup?.count).toBe(2);
expect(amortizedGroup?.aggregates["租赁费用"]?.sum).toBe(25000);
});
test("auditLedgerContinuityAndBaseline 精准诊断台账序号断层、重号以及离群异常", () => {
const entity = {
id: "e_lease",
name: "租金台账",
fields: [
{ name: "E_e_lease_seq", label: "摊销序号", type: "number" },
{ name: "E_e_lease_fee", label: "租金金额", type: "money" },
],
actions: [],
importMethod: [],
};
const records = [
{ id: "r-1", E_e_lease_seq: 1, E_e_lease_fee: 78787.55 },
{ id: "r-2a", E_e_lease_seq: 2, E_e_lease_fee: 78787.55 },
{ id: "r-2b", E_e_lease_seq: 2, E_e_lease_fee: 0 }, // 离群 + 重号
// 缺少序号 3
{ id: "r-4", E_e_lease_seq: 4, E_e_lease_fee: 78787.55 },
];
const report = auditLedgerContinuityAndBaseline(records as any, entity as any, {
sequenceField: "摊销序号",
expectedValues: [{ field: "租金金额", targetValue: 78787.55, tolerance: 0.1 }],
});
expect(report.sequenceSummary).toBeDefined();
expect(report.sequenceSummary?.min).toBe(1);
expect(report.sequenceSummary?.max).toBe(4);
expect(report.sequenceSummary?.missing).toEqual([3]);
expect(report.sequenceSummary?.duplicates).toEqual([2]);
expect(report.outliers).toHaveLength(1);
expect(report.outliers[0]?.recordId).toBe("r-2b");
expect(report.outliers[0]?.value).toBe(0);
expect(report.outliers[0]?.expectedValue).toBe(78787.55);
const missingIssue = report.issues.find((i) => i.type === "MISSING_SEQUENCE");
expect(missingIssue?.message).toContain("缺少第 [3] 期记录");
const dupIssue = report.issues.find((i) => i.type === "DUPLICATE_SEQUENCE");
expect(dupIssue?.message).toContain("第 [2] 期存在 2 条重复记录");
});
test("parseExpectClause 解析各种容差与期望表达式", () => {
const res1 = parseExpectClause("租赁费用 ~= 78787.55");
expect(res1).toEqual([{ field: "租赁费用", targetValue: 78787.55, tolerance: undefined }]);
const res2 = parseExpectClause("租赁费用 = 78787.55 +- 0.05, 日折旧费 ~= 2626.25");
expect(res2).toEqual([
{ field: "租赁费用", targetValue: 78787.55, tolerance: 0.05 },
{ field: "日折旧费", targetValue: 2626.25, tolerance: undefined },
]);
});
test("filterRecordsByPredicate 支持比较操作符与 in 语法", () => {
const entity = {
id: "e_item",
name: "资产",
fields: [
{ name: "E_e_item_amount", label: "金额", type: "number" },
{ name: "E_e_item_status", label: "状态", type: "text" },
],
actions: [],
importMethod: [],
};
const records = [
{ id: "1", E_e_item_amount: 100, E_e_item_status: "ACTIVE" },
{ id: "2", E_e_item_amount: 0, E_e_item_status: "INACTIVE" },
{ id: "3", E_e_item_amount: 250, E_e_item_status: "ACTIVE" },
];
const matchZero = filterRecordsByPredicate(records as any, "金额 == 0", entity as any);
expect(matchZero.map((r) => r.id)).toEqual(["2"]);
const matchActiveGt100 = filterRecordsByPredicate(records as any, "状态 == 'ACTIVE' && 金额 > 100", entity as any);
expect(matchActiveGt100.map((r) => r.id)).toEqual(["3"]);
const matchIn = filterRecordsByPredicate(records as any, "状态 in (ACTIVE, PENDING)", entity as any);
expect(matchIn.map((r) => r.id)).toEqual(["1", "3"]);
});
test("parseSetClause 解析声明式更新赋值并映射到实体字段名", () => {
const entity = {
id: "e_item",
name: "资产",
fields: [
{ name: "E_e_item_amount", label: "租赁费用", type: "number" },
{ name: "E_e_item_status", label: "状态", type: "text" },
],
actions: [],
importMethod: [],
};
const patch = parseSetClause("租赁费用 = 78787.55, 状态 = '待摊销', active = true", entity as any);
expect(patch).toEqual({
E_e_item_amount: 78787.55,
E_e_item_status: "待摊销",
active: true,
});
});
test("normalizeDatalinkRecord 自动提取主键 ID、名称、编码并剥离动态前缀", () => {
const entity = {
id: "e816139ba5e1cd4ae3c0",
name: "摊销明细",
fields: [
{ name: "E_e816139ba5e1cd4ae3c0_code", label: "编码", type: "text" },
{ name: "E_e816139ba5e1cd4ae3c0_name", label: "名称", type: "text" },
{ name: "E_e816139ba5e1cd4ae3c0_rent", label: "当期租金", type: "money" },
{ name: "E_e816139ba5e1cd4ae3c0_vendor", label: "供应商", type: "ref" },
],
actions: [],
importMethod: [],
};
const rawRecord = {
dataLink: {
id: "ID01UsDobfXRRZ",
active: false,
createTime: 1780000000000,
updateTime: 1789000000000,
E_e816139ba5e1cd4ae3c0_code: "0-DT-2026-month-1",
E_e816139ba5e1cd4ae3c0_name: "使用权资产摊销-北京仓",
E_e816139ba5e1cd4ae3c0_rent: { standard: "42680.54", standardUnit: "元" },
E_e816139ba5e1cd4ae3c0_vendor: { name: "博展科技" },
},
};
const norm = normalizeDatalinkRecord(rawRecord as any, entity as any);
expect(norm.id).toBe("ID01UsDobfXRRZ");
expect(norm.active).toBe(false);
expect(norm.code).toBe("0-DT-2026-month-1");
expect(norm.name).toBe("使用权资产摊销-北京仓");
expect(norm.fields["当期租金"]).toBe("42680.54");
expect(norm.fields["供应商"]).toBe("博展科技");
});
test("calculateEntityRecordStats 准确统计启用率、重名交叉与编码结构聚类", () => {
const entity = {
id: "e_test",
name: "测试对象",
fields: [
{ name: "code", label: "编码", type: "text" },
{ name: "name", label: "名称", type: "text" },
],
actions: [],
importMethod: [],
};
const records = [
{ id: "1", code: "0-DT-20260831-0001-month-1", name: "北京仓", active: true, createTime: 1000, updateTime: 2000 },
{ id: "2", code: "0-DT-20260831-0001-month-2", name: "北京仓", active: true, createTime: 1000, updateTime: 3000 },
{ id: "3", code: "0-DT-20260831-0001-period-1", name: "北京仓", active: false, createTime: 1000, updateTime: 2500 },
{ id: "4", code: "0-DT-20260831-0002-month-1", name: "上海仓", active: false, createTime: 1200, updateTime: 2200 },
];
const stats = calculateEntityRecordStats(records as any, entity as any, 4);
expect(stats.total).toBe(4);
expect(stats.activeCount).toBe(2);
expect(stats.inactiveCount).toBe(2);
expect(stats.activeRate).toBe("50.0%");
expect(stats.uniqueNames).toBe(2);
expect(stats.duplicateNamesCount).toBe(1); // "北京仓" 出现 3 次
expect(stats.mixedStatusNamesCount).toBe(1); // "北京仓" 同时含启用与停用
expect(stats.codePatterns).toHaveLength(2);
expect(stats.codePatterns[0].count).toBe(3); // 3 条 month
expect(stats.codePatterns[1].count).toBe(1); // 1 条 period
});
test("iterateAllEntityRecords 支持跨页逐条流式下发", async () => {
let callCount = 0;
const mockClient = {
post: () => ({
json: async () => {
callCount++;
if (callCount === 1) {
return {
items: {
total: 3,
data: [{ id: "rec-1" }, { id: "rec-2" }],
},
};
}
return {
items: {
total: 3,
data: [{ id: "rec-3" }],
},
};
},
}),
};
const stream = iterateAllEntityRecords(mockClient as any, "corp-1", "entity-1", { pageSize: 2 });
const collected: string[] = [];
for await (const record of stream) {
collected.push(record.id!);
}
expect(collected).toEqual(["rec-1", "rec-2", "rec-3"]);
expect(callCount).toBe(2);
});
});
+678
View File
@@ -7,6 +7,13 @@ import type {
DatalinkRecord,
DatalinkRecordEditPayload,
DatalinkRecordPage,
AggregateFieldStats,
GroupAggregateResult,
LedgerAggregateReport,
ContinuityIssue,
LedgerContinuityReport,
NormalizedDatalinkRecord,
DatalinkRecordStats,
} from "./types.js";
export type { SafeRecordEditOptions } from "./api.js";
@@ -165,6 +172,247 @@ export async function fetchAllEntityRecords(
};
}
/**
* 流式异步迭代器:逐页拉取并逐条产出业务对象记录。
* 内存开销恒定为 O(pageSize),可直接支持 10 万+ 级海量数据的流式下发与外部管道消费。
*/
export async function* iterateAllEntityRecords(
client: KyInstance,
corpId: string,
entityId: string,
options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {}
): AsyncGenerator<DatalinkRecord, void, unknown> {
const pageSize = Math.max(1, Math.min(options.pageSize ?? 500, 1000));
let start = 0;
let total = 0;
let yielded = 0;
while (true) {
const page = await api.searchEntityRecords(client, corpId, entityId, {
start,
count: pageSize,
filterBy: options.filterBy,
orderBy: options.orderBy,
});
total = page.total;
if (page.data.length === 0) break;
for (const record of page.data) {
yield record;
yielded++;
}
start += page.data.length;
if (yielded >= total || page.data.length < pageSize) {
break;
}
}
}
/**
* 将数据互联原始报文规范化为标准、扁平、脱敏于动态前缀的结构。
* 彻底消除 r.id vs r.dataLink.id 以及 E_<entityId>_ 动态前缀的困扰。
*/
export function normalizeDatalinkRecord(
rawRecord: DatalinkRecord,
entity?: DatalinkEntity,
options: { includeRaw?: boolean } = {}
): NormalizedDatalinkRecord {
const dl =
rawRecord.dataLink && typeof rawRecord.dataLink === "object" && !Array.isArray(rawRecord.dataLink)
? (rawRecord.dataLink as Record<string, unknown>)
: (rawRecord as Record<string, unknown>);
const entityId = String(entity?.id ?? dl.entityId ?? rawRecord.entityId ?? "");
const bareEntityId = entityId.startsWith("$") ? entityId.slice(1) : entityId;
const id = String(dl.id ?? rawRecord.id ?? "");
const active = (dl.active ?? rawRecord.active) !== false;
const createTime = (dl.createTime ?? rawRecord.createTime ?? null) as number | null;
const updateTime = (dl.updateTime ?? rawRecord.updateTime ?? null) as number | null;
const nameField = entity?.fields.find(
(f) => f.label === "名称" || f.label === "标题" || f.name === `E_${bareEntityId}_name` || f.name.endsWith("_name")
);
const codeField = entity?.fields.find(
(f) => f.label === "编码" || f.name === `E_${bareEntityId}_code` || f.name.endsWith("_code")
);
const name = String(
dl.name ??
dl["名称"] ??
(nameField ? dl[nameField.name] : undefined) ??
(bareEntityId ? dl[`E_${bareEntityId}_name`] : undefined) ??
""
);
const code = String(
dl.code ??
dl["编码"] ??
(codeField ? dl[codeField.name] : undefined) ??
(bareEntityId ? dl[`E_${bareEntityId}_code`] : undefined) ??
""
);
const fields: Record<string, unknown> = {};
if (entity?.fields) {
for (const field of entity.fields) {
if (field.name === nameField?.name || field.name === codeField?.name) continue;
const keyCandidates = [
field.name,
bareEntityId ? `E_${bareEntityId}_${field.name}` : undefined,
field.label,
].filter(Boolean) as string[];
let val: unknown = undefined;
for (const key of keyCandidates) {
if (key in dl) {
val = dl[key];
break;
}
}
if (val !== undefined && val !== null) {
if (typeof val === "object" && !Array.isArray(val)) {
const obj = val as Record<string, unknown>;
if ("standard" in obj) {
val = obj.standard;
} else if ("name" in obj && typeof obj.name === "string" && obj.name) {
val = obj.name;
} else {
let targetDataLink: Record<string, unknown> | undefined = undefined;
if ("dataLink" in obj && typeof obj.dataLink === "object" && obj.dataLink) {
targetDataLink = obj.dataLink as Record<string, unknown>;
} else if ("data" in obj && typeof obj.data === "object" && obj.data && "dataLink" in (obj.data as Record<string, unknown>)) {
targetDataLink = (obj.data as Record<string, unknown>).dataLink as Record<string, unknown>;
}
if (targetDataLink) {
const form = (targetDataLink.form && typeof targetDataLink.form === "object" ? targetDataLink.form : {}) as Record<string, unknown>;
const combined = { ...targetDataLink, ...form };
let subDisplay: string | undefined = undefined;
for (const [k, v] of Object.entries(combined)) {
if (typeof v === "string" && v.trim() && (k === "name" || k === "title" || k === "名称" || k === "标题" || k.endsWith("_name") || k.endsWith("_title"))) {
subDisplay = v;
break;
}
}
if (!subDisplay) {
for (const [k, v] of Object.entries(combined)) {
if (typeof v === "string" && v.trim() && (k === "code" || k === "编码" || k.endsWith("_code") || k.includes("编号"))) {
subDisplay = v;
break;
}
}
}
val = subDisplay || (targetDataLink.id ? String(targetDataLink.id) : undefined) || (obj.id ? String(obj.id) : undefined);
} else if (obj.id && typeof obj.id === "string") {
val = obj.id;
}
}
}
fields[field.label || field.name] = val;
}
}
}
return {
id,
code,
name,
active,
createTime,
updateTime,
fields,
...(options.includeRaw ? { raw: rawRecord } : {}),
};
}
/**
* 计算业务对象记录的轻量级宏观分布画像(统计总数、启用/停用数、重名率、编码前缀聚类等)。
* 既可接收全量内存数组,也可配合流式生成器在 O(1) 内存下在线累加计算。
*/
export function calculateEntityRecordStats(
records: Iterable<DatalinkRecord>,
entity?: DatalinkEntity,
explicitTotal?: number
): DatalinkRecordStats {
let total = 0;
let activeCount = 0;
let inactiveCount = 0;
const namesMap = new Map<string, { total: number; active: number; inactive: number }>();
const patternsMap = new Map<string, { pattern: string; sample: string; count: number; activeCount: number; inactiveCount: number }>();
let earliestCreate: number | null = null;
let latestUpdate: number | null = null;
for (const raw of records) {
total++;
const norm = normalizeDatalinkRecord(raw, entity);
if (norm.active) activeCount++;
else inactiveCount++;
if (norm.createTime && typeof norm.createTime === "number") {
if (earliestCreate === null || norm.createTime < earliestCreate) earliestCreate = norm.createTime;
}
if (norm.updateTime && typeof norm.updateTime === "number") {
if (latestUpdate === null || norm.updateTime > latestUpdate) latestUpdate = norm.updateTime;
}
// 统计名称重名与状态交叉
if (norm.name) {
if (!namesMap.has(norm.name)) {
namesMap.set(norm.name, { total: 0, active: 0, inactive: 0 });
}
const nStats = namesMap.get(norm.name)!;
nStats.total++;
if (norm.active) nStats.active++;
else nStats.inactive++;
}
// 统计编码结构聚类
const code = norm.code || "EMPTY";
const pattern = code
.replace(/\d{8}/g, "YYYYMMDD")
.replace(/\d{6}/g, "SEQ6")
.replace(/\d+/g, "N");
if (!patternsMap.has(pattern)) {
patternsMap.set(pattern, { pattern, sample: code, count: 0, activeCount: 0, inactiveCount: 0 });
}
const pStats = patternsMap.get(pattern)!;
pStats.count++;
if (norm.active) pStats.activeCount++;
else pStats.inactiveCount++;
}
const finalTotal = explicitTotal !== undefined ? Math.max(explicitTotal, total) : total;
const activeRate = finalTotal > 0 ? `${((activeCount / finalTotal) * 100).toFixed(1)}%` : "0.0%";
let duplicateNamesCount = 0;
let mixedStatusNamesCount = 0;
for (const n of namesMap.values()) {
if (n.total > 1) duplicateNamesCount++;
if (n.active > 0 && n.inactive > 0) mixedStatusNamesCount++;
}
const codePatterns = Array.from(patternsMap.values()).sort((a, b) => b.count - a.count);
const formatDate = (ts: number | null) => (ts ? new Date(ts).toLocaleString("zh-CN", { hour12: false }) : null);
return {
total: finalTotal,
activeCount,
inactiveCount,
activeRate,
uniqueNames: namesMap.size,
duplicateNamesCount,
mixedStatusNamesCount,
codePatterns,
earliestCreateTime: formatDate(earliestCreate),
latestUpdateTime: formatDate(latestUpdate),
};
}
export interface DatalinkAuditIssue {
recordId: string;
recordCode: string;
@@ -612,3 +860,433 @@ export async function batchSafeEditRecords(
return results;
}
// ── 台账数学核对与声明式更新引擎 (Ledger Math & In-line Ops) ───────────────────
/**
* 根据字段名或标签模糊解析实体字段元数据
*/
export function resolveEntityField(
entity: DatalinkEntity,
query: string
): DatalinkField | undefined {
const q = query.trim().toLowerCase();
const bareQ = q.replace(/^e_[^_]+_/, "").replace(/^e_/, "");
return (
entity.fields.find(
(f) =>
f.name.toLowerCase() === q ||
f.label?.toLowerCase() === q ||
f.name.toLowerCase() === `e_${entity.id.toLowerCase()}_${bareQ}` ||
f.name.replace(/^e_[^_]+_/, "").toLowerCase() === bareQ
) ||
entity.fields.find((f) => f.label?.toLowerCase().includes(q))
);
}
/**
* 通用提取记录中某一字段的原始值
*/
export function extractRecordFieldValue(
record: DatalinkRecord,
field: DatalinkField | string
): unknown {
const source =
record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink)
? (record.dataLink as Record<string, unknown>)
: record;
const fieldName = typeof field === "string" ? field : field.name;
const fieldLabel = typeof field === "string" ? undefined : field.label;
let val = source[fieldName] ?? record[fieldName];
if (val === undefined && fieldLabel) {
val = source[fieldLabel] ?? record[fieldLabel];
}
if (val === undefined && record.form && typeof record.form === "object") {
val = (record.form as Record<string, unknown>)[fieldName];
if (val === undefined && fieldLabel) {
val = (record.form as Record<string, unknown>)[fieldLabel];
}
}
return val;
}
/**
* 提取记录中某一字段的数值(兼容数值、货币对象与格式化字符串)
*/
export function extractNumericFieldValue(
record: DatalinkRecord,
field: DatalinkField | string
): number | null {
const val = extractRecordFieldValue(record, field);
if (val === null || val === undefined || val === "") return null;
if (typeof val === "number" && !Number.isNaN(val)) return val;
if (typeof val === "object" && !Array.isArray(val)) {
const std = (val as any).standard ?? (val as any).amount;
if (typeof std === "number" && !Number.isNaN(std)) return std;
if (typeof std === "string") {
const parsed = parseFloat(std);
if (!Number.isNaN(parsed)) return parsed;
}
}
if (typeof val === "string") {
const clean = val.replace(/^[¥$¥\s,]+/, "").replace(/,/g, "");
const parsed = parseFloat(clean);
if (!Number.isNaN(parsed)) return parsed;
}
return null;
}
/**
* 对记录进行聚合统计(COUNT, SUM, AVG, MIN, MAX,可选分组)
*/
export function aggregateRecordFields(
records: DatalinkRecord[],
entity: DatalinkEntity,
options: {
fields: string[];
groupBy?: string;
}
): LedgerAggregateReport {
const resolvedFields = options.fields.map((f) => {
const resolved = resolveEntityField(entity, f);
return {
query: f,
field: resolved ?? { name: f, label: f, type: "number" },
};
});
const calcStats = (list: DatalinkRecord[]): Record<string, AggregateFieldStats> => {
const stats: Record<string, AggregateFieldStats> = {};
for (const { query, field } of resolvedFields) {
let count = 0;
let sum = 0;
let min = Infinity;
let max = -Infinity;
for (const r of list) {
const num = extractNumericFieldValue(r, field);
if (num !== null) {
count++;
sum += num;
if (num < min) min = num;
if (num > max) max = num;
}
}
stats[query] = {
field: field.name,
fieldLabel: field.label || field.name,
count,
sum: Math.round(sum * 100) / 100,
avg: count > 0 ? Math.round((sum / count) * 100) / 100 : 0,
min: count > 0 ? min : 0,
max: count > 0 ? max : 0,
};
}
return stats;
};
const overall = calcStats(records);
let groups: GroupAggregateResult[] | undefined;
if (options.groupBy) {
const groupField = resolveEntityField(entity, options.groupBy) ?? {
name: options.groupBy,
label: options.groupBy,
type: "text",
};
const groupMap = new Map<string, DatalinkRecord[]>();
for (const r of records) {
const gVal = String(extractRecordFieldValue(r, groupField) ?? "(未填写)");
const existing = groupMap.get(gVal);
if (existing) existing.push(r);
else groupMap.set(gVal, [r]);
}
groups = Array.from(groupMap.entries()).map(([groupValue, groupRecords]) => ({
groupValue,
count: groupRecords.length,
aggregates: calcStats(groupRecords),
}));
}
return {
totalRecords: records.length,
overall,
groups,
};
}
/**
* 台账序号连续性检查与期望基线数学核对
*/
export function auditLedgerContinuityAndBaseline(
records: DatalinkRecord[],
entity: DatalinkEntity,
options: {
sequenceField?: string;
expectedValues?: Array<{
field: string;
targetValue: number;
tolerance?: number;
}>;
}
): LedgerContinuityReport {
const issues: ContinuityIssue[] = [];
const outliers: LedgerContinuityReport["outliers"] = [];
let sequenceSummary: LedgerContinuityReport["sequenceSummary"] | undefined;
// 1. 序号连续性核查
if (options.sequenceField) {
const resolvedSeqField = resolveEntityField(entity, options.sequenceField) ?? {
name: options.sequenceField,
label: options.sequenceField,
type: "number",
};
const seqMap = new Map<number, string[]>();
const numbers: number[] = [];
for (const r of records) {
const num = extractNumericFieldValue(r, resolvedSeqField);
if (num !== null) {
const intVal = Math.round(num);
numbers.push(intVal);
const existing = seqMap.get(intVal);
const rId = r.id || String(r.recordId || "");
if (existing) existing.push(rId);
else seqMap.set(intVal, [rId]);
}
}
if (numbers.length > 0) {
const min = Math.min(...numbers);
const max = Math.max(...numbers);
const missing: number[] = [];
const duplicates: number[] = [];
for (let i = min; i <= max; i++) {
const count = seqMap.get(i)?.length ?? 0;
if (count === 0) {
missing.push(i);
issues.push({
type: "MISSING_SEQUENCE",
field: resolvedSeqField.name,
message: `台账序号断层:缺少第 [${i}] 期记录`,
expected: i,
actual: null,
});
} else if (count > 1) {
duplicates.push(i);
issues.push({
type: "DUPLICATE_SEQUENCE",
field: resolvedSeqField.name,
message: `台账序号重号:第 [${i}] 期存在 ${count} 条重复记录 (${seqMap.get(i)?.join(", ")})`,
expected: 1,
actual: count,
});
}
}
sequenceSummary = {
field: resolvedSeqField.name,
fieldLabel: resolvedSeqField.label || resolvedSeqField.name,
min,
max,
expectedCount: max - min + 1,
actualCount: numbers.length,
missing,
duplicates,
};
}
}
// 2. 基线离群异常核对
if (options.expectedValues && options.expectedValues.length > 0) {
for (const exp of options.expectedValues) {
const field = resolveEntityField(entity, exp.field) ?? {
name: exp.field,
label: exp.field,
type: "number",
};
const tolerance = exp.tolerance ?? 0.05;
for (const r of records) {
const val = extractNumericFieldValue(r, field);
if (val !== null) {
const diff = Math.abs(val - exp.targetValue);
if (diff > tolerance) {
const rId = r.id || String(r.recordId || "");
outliers.push({
recordId: rId,
field: field.name,
fieldLabel: field.label || field.name,
value: val,
expectedValue: exp.targetValue,
diff: Math.round(diff * 100) / 100,
});
issues.push({
type: "VALUE_OUTLIER",
recordId: rId,
field: field.name,
message: `记录 [${rId}] 字段 [${field.label || field.name}] 数值 [${val}] 偏离基线期望 [${exp.targetValue}] (差额: ${diff > 0 ? "+" : ""}${Math.round(diff * 100) / 100})`,
expected: exp.targetValue,
actual: val,
});
}
}
}
}
}
return {
totalRecords: records.length,
sequenceSummary,
issues,
outliers,
};
}
/**
* 客户端声明式筛选器(支持 ==, !=, >, >=, <, <=, in (...) 以及 && 组合)
*/
export function filterRecordsByPredicate(
records: DatalinkRecord[],
whereClause: string,
entity: DatalinkEntity
): DatalinkRecord[] {
if (!whereClause || !whereClause.trim()) return records;
const conditions = whereClause
.split(/\s+&&\s+/)
.map((c) => c.trim())
.filter(Boolean);
return records.filter((r) => {
return conditions.every((cond) => {
// 1. in 操作符: field in (v1, v2, v3)
const inMatch = cond.match(/^(.+?)\s+in\s*\((.+?)\)$/i);
if (inMatch) {
const fieldKey = inMatch[1].trim();
const rawValues = inMatch[2]
.split(",")
.map((v) => v.trim().replace(/^['"]|['"]$/g, ""));
const actualVal = String(extractRecordFieldValue(r, resolveEntityField(entity, fieldKey) ?? fieldKey) ?? "");
return rawValues.some((v) => v === actualVal);
}
// 2. 比较操作符: ==, !=, >=, <=, >, <, =
const compMatch = cond.match(/^(.+?)\s*(==|!=|>=|<=|>|<|=)\s*(.+)$/);
if (compMatch) {
const fieldKey = compMatch[1].trim();
const op = compMatch[2];
const rawTarget = compMatch[3].trim().replace(/^['"]|['"]$/g, "");
const actualRaw = extractRecordFieldValue(r, resolveEntityField(entity, fieldKey) ?? fieldKey);
// 数值比较
const actualNum = extractNumericFieldValue(r, resolveEntityField(entity, fieldKey) ?? fieldKey);
const targetNum = Number(rawTarget);
if (actualNum !== null && !Number.isNaN(targetNum)) {
switch (op) {
case "==":
case "=":
return actualNum === targetNum;
case "!=":
return actualNum !== targetNum;
case ">":
return actualNum > targetNum;
case ">=":
return actualNum >= targetNum;
case "<":
return actualNum < targetNum;
case "<=":
return actualNum <= targetNum;
}
}
// 字符串/布尔比较
const actualStr = String(actualRaw ?? "");
switch (op) {
case "==":
case "=":
return actualStr === rawTarget;
case "!=":
return actualStr !== rawTarget;
default:
return false;
}
}
return true;
});
});
}
/**
* 解析 --set 表达式为字段更新补丁: "租赁费用 = 78787.55, 状态 = 待摊销"
*/
export function parseSetClause(
setClause: string,
entity: DatalinkEntity
): Record<string, unknown> {
const result: Record<string, unknown> = {};
const assignments = setClause.split(",").map((s) => s.trim()).filter(Boolean);
for (const assign of assignments) {
const eqIdx = assign.indexOf("=");
if (eqIdx === -1) continue;
const rawKey = assign.slice(0, eqIdx).trim();
let rawVal = assign.slice(eqIdx + 1).trim();
// 去除外层引号
if ((rawVal.startsWith('"') && rawVal.endsWith('"')) || (rawVal.startsWith("'") && rawVal.endsWith("'"))) {
rawVal = rawVal.slice(1, -1);
}
const field = resolveEntityField(entity, rawKey);
const targetKey = field ? field.name : rawKey;
// 类型智能转换
if (rawVal === "true") {
result[targetKey] = true;
} else if (rawVal === "false") {
result[targetKey] = false;
} else if (rawVal === "null") {
result[targetKey] = null;
} else if (!Number.isNaN(Number(rawVal)) && rawVal !== "") {
result[targetKey] = Number(rawVal);
} else {
result[targetKey] = rawVal;
}
}
return result;
}
/**
* 解析 --expect 表达式为数值基线期望列表: "租赁费用 ~= 78787.55, 日折旧费 = 2626.25 +- 0.05"
*/
export function parseExpectClause(
expectClause: string
): Array<{ field: string; targetValue: number; tolerance?: number }> {
if (!expectClause || !expectClause.trim()) return [];
const parts = expectClause.split(/[,;]/).map((s) => s.trim()).filter(Boolean);
const results: Array<{ field: string; targetValue: number; tolerance?: number }> = [];
for (const part of parts) {
const match = part.match(
/^(.+?)\s*(?:~=|==|=|\:)\s*([0-9.-]+)(?:\s*(?:\+\-|\+\/\-|±|\~)\s*([0-9.]+))?$/
);
if (match) {
const field = match[1].trim();
const targetValue = parseFloat(match[2]);
const tolerance = match[3] ? parseFloat(match[3]) : undefined;
if (!Number.isNaN(targetValue)) {
results.push({ field, targetValue, tolerance });
}
}
}
return results;
}
+91
View File
@@ -119,3 +119,94 @@ export interface DatalinkRecordEditPayload {
};
[key: string]: unknown;
}
// ── 台账聚合统计与数学核对模型 ─────────────────────────────────────────────
export interface AggregateFieldStats {
field: string;
fieldLabel: string;
count: number;
sum: number;
avg: number;
min: number;
max: number;
}
export interface GroupAggregateResult {
groupValue: string;
count: number;
aggregates: Record<string, AggregateFieldStats>;
}
export interface LedgerAggregateReport {
totalRecords: number;
overall: Record<string, AggregateFieldStats>;
groups?: GroupAggregateResult[];
}
// ── 台账连续性与基线断层核对模型 ──────────────────────────────────────────
export interface ContinuityIssue {
type: "MISSING_SEQUENCE" | "DUPLICATE_SEQUENCE" | "VALUE_OUTLIER";
recordId?: string;
field: string;
message: string;
expected?: unknown;
actual?: unknown;
}
export interface LedgerContinuityReport {
totalRecords: number;
sequenceSummary?: {
field: string;
fieldLabel: string;
min: number;
max: number;
expectedCount: number;
actualCount: number;
missing: number[];
duplicates: number[];
};
issues: ContinuityIssue[];
outliers: Array<{
recordId: string;
field: string;
fieldLabel: string;
value: number;
expectedValue: number;
diff: number;
}>;
}
// ── 归一化记录与统计画像模型 ───────────────────────────────────────────────
export interface NormalizedDatalinkRecord {
id: string;
code: string;
name: string;
active: boolean;
createTime?: number | null;
updateTime?: number | null;
fields: Record<string, unknown>;
raw?: DatalinkRecord;
}
export interface DatalinkRecordStats {
total: number;
activeCount: number;
inactiveCount: number;
activeRate: string;
uniqueNames: number;
duplicateNamesCount: number;
mixedStatusNamesCount: number;
codePatterns: Array<{
pattern: string;
sample: string;
count: number;
activeCount: number;
inactiveCount: number;
}>;
earliestCreateTime?: string | null;
latestUpdateTime?: string | null;
}
+5 -1
View File
@@ -19,7 +19,11 @@ hose-use workflow list [--platform-id=<id>|--app-id=<id>]
hose-use workflow get <pipelineId>
hose-use workflow analyze <pipelineId> [--json]
hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
hose-use workflow job <jobId> [--failed] [--parent=<executionId>] [--logs=<executionId>]
hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose]
hose-use workflow diff <snapshotId1> <snapshotId2> [--pipelineId=<id>]
hose-use workflow diff-job <jobId1> <jobId2> [--json]
hose-use workflow test <pipelineId> --flow=<单号|单据ID> [--auto-publish]
hose-use workflow debug <pipelineId> --flow=<单号>
```
## 详细文档
+54
View File
@@ -111,4 +111,58 @@ describe("Workflow static analysis", () => {
expect(codes).toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
expect(codes).toContain("LINKAGE_PRIORITY_OVERRIDE");
});
it("detects DEADLOCK_TRIGGER_STATE_FILTER when trigger specifies state APPROVING", () => {
const wf = {
id: "wf-trigger-deadlock",
label: "资金调拨自动审批",
state: 1,
version: "1",
tasks: [
{
name: "trigger_1",
type: "ekuaibao-flowform-trigger",
label: "单据审批事件触发器",
combineFilters: {
filters: [
{
filters: [
{ key: "formSpecification", value: "ID01RUq5zrhZTh", compare: "eq" },
{ key: "state", value: "APPROVING", compare: "eq" },
],
condition: "and",
},
],
condition: "or",
},
},
],
};
const result = analyzeWorkflow(wf as any);
const codes = result.diagnostics.map((d) => d.code);
expect(codes).toContain("DEADLOCK_TRIGGER_STATE_FILTER");
expect(result.diagnostics.find((d) => d.code === "DEADLOCK_TRIGGER_STATE_FILTER")?.severity).toBe("error");
});
it("detects MISSING_BACKLOG_DATA_BRACKETS on backlog openapi http task", () => {
const wf = {
id: "wf-http-no-brackets",
label: "自动审批",
state: 1,
version: "1",
tasks: [
{
name: "action_1",
type: "http",
label: "审批接口调用",
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/ID01X4mbLfjvpt",
},
],
};
const result = analyzeWorkflow(wf as any);
const codes = result.diagnostics.map((d) => d.code);
expect(codes).toContain("MISSING_BACKLOG_DATA_BRACKETS");
expect(result.diagnostics.find((d) => d.code === "MISSING_BACKLOG_DATA_BRACKETS")?.severity).toBe("warning");
});
});
+42
View File
@@ -66,6 +66,12 @@ const KNOWN_TYPES = new Set([
"ekuaibao-datalink-create",
"ekuaibao-datalink-edit",
"ekuaibao-datalink-delete",
"ekuaibao-flowform-trigger",
"ekuaibao-ebot-trigger",
"ekuaibao-datalink-create-trigger",
"ekuaibao-datalink-time-trigger",
"ekuaibao-datalink-edit-trigger",
"ekuaibao-datalink-delete-trigger",
"data-convert",
"flow-create-task",
]);
@@ -380,6 +386,42 @@ export function analyzeWorkflow(
}
}
// 诊断 4: 触发器节点配置了无效的单据审批状态过滤 (DEADLOCK_TRIGGER_STATE_FILTER)
if (
(task.type === "ekuaibao-flowform-trigger" || task.type === "ekuaibao-ebot-trigger") &&
(task as Record<string, unknown>).combineFilters
) {
const rawFilters = JSON.stringify((task as Record<string, unknown>).combineFilters);
if (
rawFilters.includes('"key":"state"') &&
(rawFilters.includes('"APPROVING"') || rawFilters.includes('"approving"'))
) {
diagnostics.push({
severity: "error",
code: "DEADLOCK_TRIGGER_STATE_FILTER",
path,
message: `触发器节点 [${task.label || task.name}] (${task.name}) 配置了 state == APPROVING 状态过滤条件。合思单据审批出站事件属于动作事件(如 backlog.approving),事件载荷中不携带大写 APPROVING 状态字段,该过滤会导致出站事件被 100% 静默丢弃,下游审批流程永久无法触发!建议移除 state 过滤,改用后置条件节点判断审批人。`,
});
}
}
// 诊断 5: HTTP 自动审批节点 URL 与中括号校验 (MISSING_BACKLOG_DATA_BRACKETS)
if (task.type === "http") {
const url = String((task as Record<string, unknown>).url || "");
if (url.includes("api/openapi/v1/backlog/data")) {
const match = url.match(/api\/openapi\/v1\/backlog\/data\/([^?#]+)/);
const segment = match ? match[1] : "";
if (segment && (!segment.startsWith("[") || !segment.includes("]"))) {
diagnostics.push({
severity: "warning",
code: "MISSING_BACKLOG_DATA_BRACKETS",
path,
message: `HTTP 自动审批节点 [${task.label || task.name}] 的 URL 路径参数缺少合思 OpenAPI 规范的方括号(规范要求: /api/openapi/v1/backlog/data/[{flowId}]),缺少方括号将导致服务端直接返回 404 Not Found。`,
});
}
}
}
visit(task.tasks || [], path, insideEvery || task.type === "every");
});
};
+59
View File
@@ -7,6 +7,7 @@ import {
WorkflowStatsSchema,
WorkflowChargeSchema,
WorkflowDetailSchema,
WorkflowSnapshotSchema,
WorkflowSnapshotPageSchema,
WorkflowLogPageSchema,
WorkflowJobSchema,
@@ -18,6 +19,7 @@ import {
StaffSchema,
WebhookInfoSchema,
WorkflowSampleDataSchema,
WorkflowDebugSourceResultSchema,
} from "./types.js";
import type { WorkflowState } from "./types.js";
@@ -140,6 +142,23 @@ export async function listWorkflowSnapshots(
return unwrap(response, WorkflowSnapshotPageSchema);
}
export async function getWorkflowSnapshot(
client: KyInstance,
snapshotId: string,
pipelineId?: string
): Promise<import("./types.js").WorkflowSnapshot> {
try {
const response = await client.get(`api/easo/snapshots/${snapshotId}`);
return unwrap(response, WorkflowSnapshotSchema);
} catch (err) {
if (pipelineId) {
const response = await client.get(`api/easo/pipelines/${pipelineId}/snapshots/${snapshotId}`);
return unwrap(response, WorkflowSnapshotSchema);
}
throw err;
}
}
export async function listWorkflowLogs(
client: KyInstance,
pipelineId: string,
@@ -307,3 +326,43 @@ export async function sampleWorkflowData(
return WorkflowSampleDataSchema.parse(await response.json());
}
// ── 调试数据源与发起调试(Piper)─────────────────────────────────────────────
export async function getWorkflowDebugSource(
client: KyInstance,
pipelineId: string,
options: { page?: number; pageSize?: number; keywords?: string } = {}
): Promise<import("./types.js").WorkflowDebugSourceResult> {
const response = await client.post(`api/easo/pipelines/${pipelineId}/debugSource`, {
json: {
number: options.page ?? 1,
pageSize: options.pageSize ?? 20,
...(options.keywords ? { keywords: options.keywords } : {}),
},
});
return unwrap(response, WorkflowDebugSourceResultSchema);
}
export async function triggerWorkflowDebug(
client: KyInstance,
pipelineId: string,
options: { entityId: string; autoPublish?: boolean; dataLimit?: number }
): Promise<string> {
const response = await client.post("api/easo/jobs", {
json: {
pipelineId,
inputs: {
id: options.entityId,
$autoPublish: options.autoPublish ?? false,
},
dataLimit: options.dataLimit ?? 20,
},
});
const data = await unwrap(response, z.union([z.string(), z.number(), z.record(z.string(), z.any())]));
if (typeof data === "string") return data;
if (typeof data === "number") return String(data);
if (data && typeof data === "object" && "id" in data) return String(data.id);
if (data && typeof data === "object" && "jobId" in data) return String(data.jobId);
return String(data);
}
+533
View File
@@ -1,13 +1,21 @@
import { KyInstance } from "ky";
import { CorpConfig } from "../../core/config/types.js";
import * as api from "./api.js";
import { explainConditionBranches } from "./workflow-branch.js";
import {
Platform,
WorkflowSummary,
WorkflowListAllError,
WorkflowTask,
WorkflowTaskExecution,
WorkflowWithMatches,
TaskMatch,
WorkflowSnapshot,
WorkflowSnapshotDiff,
TaskConfigDiff,
WorkflowJobDetail,
WorkflowJobDiff,
NodeExecutionDiff,
} from "./types.js";
export interface PlatformClients {
@@ -44,6 +52,10 @@ export function listWorkflowSnapshots(...args: Parameters<typeof api.listWorkflo
return api.listWorkflowSnapshots(...args);
}
export function getWorkflowSnapshot(...args: Parameters<typeof api.getWorkflowSnapshot>) {
return api.getWorkflowSnapshot(...args);
}
export function listWorkflowLogs(...args: Parameters<typeof api.listWorkflowLogs>) {
return api.listWorkflowLogs(...args);
}
@@ -213,3 +225,524 @@ export async function findWorkflowsByTaskType(
return { workflows: matched, errors: [...all.errors, ...detailErrors] };
}
/**
* 递归扁平化执行树节点(展开 children / tasks / items 等嵌套数组)
*/
export function flattenExecutionTree(nodes: WorkflowTaskExecution[]): WorkflowTaskExecution[] {
const result: WorkflowTaskExecution[] = [];
function visit(node: any) {
if (!node || typeof node !== "object") return;
result.push(node as WorkflowTaskExecution);
const children = node.children || node.tasks || node.subTasks || node.items;
if (Array.isArray(children)) {
for (const child of children) {
visit(child);
}
}
}
for (const node of nodes) {
visit(node);
}
return result;
}
/**
* 精准判定某个节点是否执行异常或报错
*/
export function isTaskExecutionFailed(node: WorkflowTaskExecution): boolean {
if (!node) return false;
const anyNode = node as any;
if (node.error?.message || anyNode.errorMessage) return true;
if (node.status === "FAILED" || anyNode.state === "FAILED" || anyNode.state === 2) return true;
if (typeof anyNode.errorTaskCount === "number" && anyNode.errorTaskCount > 0) return true;
if (anyNode.outputs && typeof anyNode.outputs === "object" && anyNode.outputs.error) return true;
if (anyNode.output && typeof anyNode.output === "object" && anyNode.output.error) return true;
return false;
}
/**
* 提取并去重执行树中的全部异常失败节点
*/
export function extractFailureExecutions(
tree: WorkflowTaskExecution[],
failedItems: WorkflowTaskExecution[] = []
): WorkflowTaskExecution[] {
const flattened = flattenExecutionTree(tree);
const map = new Map<string, WorkflowTaskExecution>();
for (const item of failedItems) {
if (item?.id) {
map.set(item.id, item);
}
}
for (const node of flattened) {
if (node?.id && isTaskExecutionFailed(node)) {
const existing = map.get(node.id);
if (!existing) {
map.set(node.id, node);
} else {
map.set(node.id, {
...node,
...existing,
error: existing.error ?? node.error,
inputs: existing.inputs ?? (node as any).inputs,
outputs: existing.outputs ?? (node as any).outputs,
});
}
}
}
return Array.from(map.values());
}
/**
* 按 ID、name、displayName 或 label 查找节点
*/
export function findExecutionNode(
tree: WorkflowTaskExecution[],
query: string
): WorkflowTaskExecution | undefined {
const flattened = flattenExecutionTree(tree);
const q = query.trim().toLowerCase();
if (!q) return undefined;
// 1. 精确匹配 ID 或 name
const exact = flattened.find(
(n) =>
n.id?.toLowerCase() === q ||
n.name?.toLowerCase() === q ||
n.displayName?.toLowerCase() === q
);
if (exact) return exact;
// 2. 包含匹配 name、label、displayName
return flattened.find(
(n) =>
n.name?.toLowerCase().includes(q) ||
n.label?.toLowerCase().includes(q) ||
n.displayName?.toLowerCase().includes(q)
);
}
// ── 工作流快照与 Job 差异比对核心算法 ──────────────────────────────────────────
/**
* 递归展开工作流配置节点(包括 condition 与 every 内嵌的子节点)
*/
export function flattenWorkflowTasks(tasks?: WorkflowTask[] | null): WorkflowTask[] {
if (!tasks || !Array.isArray(tasks)) return [];
const result: WorkflowTask[] = [];
function walk(list: WorkflowTask[]) {
for (const t of list) {
if (!t) continue;
result.push(t);
if (Array.isArray(t.tasks) && t.tasks.length > 0) {
walk(t.tasks);
}
}
}
walk(tasks);
return result;
}
/**
* 快速生成标准 Unified Diff 文本
*/
export function generateTextDiff(a: string, b: string, labelA = "from", labelB = "to"): string {
if (a === b) return "";
const linesA = a.split(/\r?\n/);
const linesB = b.split(/\r?\n/);
const output: string[] = [`--- ${labelA}`, `+++ ${labelB}`];
let start = 0;
while (start < linesA.length && start < linesB.length && linesA[start] === linesB[start]) {
start++;
}
let endA = linesA.length - 1;
let endB = linesB.length - 1;
while (endA >= start && endB >= start && linesA[endA] === linesB[endB]) {
endA--;
endB--;
}
const hunkStart = Math.max(0, start - 2);
const hunkEndA = Math.min(linesA.length, endA + 3);
const hunkEndB = Math.min(linesB.length, endB + 3);
output.push(`@@ -${hunkStart + 1},${hunkEndA - hunkStart} +${hunkStart + 1},${hunkEndB - hunkStart} @@`);
for (let i = hunkStart; i < start; i++) {
output.push(` ${linesA[i]}`);
}
for (let i = start; i <= endA; i++) {
output.push(`- ${linesA[i]}`);
}
for (let i = start; i <= endB; i++) {
output.push(`+ ${linesB[i]}`);
}
for (let i = endA + 1; i < hunkEndA; i++) {
output.push(` ${linesA[i]}`);
}
return output.join("\n");
}
/**
* 对比两个历史快照的节点、脚本代码(MVEL/JS)与参数配置差异
*/
export function diffWorkflowSnapshots(
snapshotA: WorkflowSnapshot,
snapshotB: WorkflowSnapshot
): WorkflowSnapshotDiff {
const tasksA = flattenWorkflowTasks(snapshotA.tasks);
const tasksB = flattenWorkflowTasks(snapshotB.tasks);
const mapA = new Map<string, WorkflowTask>();
for (const t of tasksA) {
if (t?.name) mapA.set(t.name, t);
}
const mapB = new Map<string, WorkflowTask>();
for (const t of tasksB) {
if (t?.name) mapB.set(t.name, t);
}
const addedTasks: string[] = [];
const removedTasks: string[] = [];
const modifiedTasks: TaskConfigDiff[] = [];
// 1. 查找新增节点
for (const [name, tB] of mapB) {
if (!mapA.has(name)) {
addedTasks.push(name);
modifiedTasks.push({
taskName: name,
displayName: tB.displayName || tB.label,
type: tB.type,
changeType: "ADDED",
configChanges: [],
});
}
}
// 2. 查找删除与修改节点
for (const [name, tA] of mapA) {
const tB = mapB.get(name);
if (!tB) {
removedTasks.push(name);
modifiedTasks.push({
taskName: name,
displayName: tA.displayName || tA.label,
type: tA.type,
changeType: "REMOVED",
configChanges: [],
});
continue;
}
// 两者均存在,深度比较配置与代码
const configChanges: Array<{ field: string; from?: unknown; to?: unknown }> = [];
let codeDiff: { from?: string; to?: string; unifiedDiff?: string } | undefined;
let filterDiff: { from?: unknown; to?: unknown } | undefined;
// 代码脚本比较
const codeA = typeof (tA as any).code === "string" ? (tA as any).code : undefined;
const codeB = typeof (tB as any).code === "string" ? (tB as any).code : undefined;
if (codeA !== codeB) {
codeDiff = {
from: codeA,
to: codeB,
unifiedDiff: generateTextDiff(
codeA || "",
codeB || "",
`${snapshotA.version || snapshotA.id}`,
`${snapshotB.version || snapshotB.id}`
),
};
}
// 过滤条件比较 (combineFilters / filters)
const filtersA = (tA as any).combineFilters ?? (tA as any).filters;
const filtersB = (tB as any).combineFilters ?? (tB as any).filters;
if (JSON.stringify(filtersA) !== JSON.stringify(filtersB)) {
filterDiff = { from: filtersA, to: filtersB };
}
// 关键字段变动比较
const checkFields = [
"type",
"url",
"method",
"entityId",
"specificationId",
"flowCode",
"formState",
"subType",
"itemType",
"targetType",
"orderMode",
"orderKey",
"batch",
"batchSize",
];
for (const f of checkFields) {
const valA = (tA as any)[f];
const valB = (tB as any)[f];
if (JSON.stringify(valA) !== JSON.stringify(valB)) {
configChanges.push({ field: f, from: valA, to: valB });
}
}
if (codeDiff || filterDiff || configChanges.length > 0) {
modifiedTasks.push({
taskName: name,
displayName: tB.displayName || tB.label || tA.displayName || tA.label,
type: tB.type || tA.type,
changeType: "MODIFIED",
codeDiff,
filterDiff,
configChanges,
});
}
}
return {
snapshotA: {
id: snapshotA.id,
version: snapshotA.version,
updateTime: snapshotA.updateTime,
staffName: snapshotA.staffName || snapshotA.staffId || undefined,
},
snapshotB: {
id: snapshotB.id,
version: snapshotB.version,
updateTime: snapshotB.updateTime,
staffName: snapshotB.staffName || snapshotB.staffId || undefined,
},
addedTasks,
removedTasks,
modifiedTasks,
summary: {
totalA: tasksA.length,
totalB: tasksB.length,
changedCount: modifiedTasks.length,
},
};
}
/**
* 对比两个 Job 的执行分支、入参 Payload、下游输出及报错信息
*/
export function diffWorkflowJobs(
jobA: WorkflowJobDetail,
treeA: WorkflowTaskExecution[],
jobB: WorkflowJobDetail,
treeB: WorkflowTaskExecution[]
): WorkflowJobDiff {
const flatA = flattenExecutionTree(treeA);
const flatB = flattenExecutionTree(treeB);
const allNames = Array.from(
new Set([
...flatA.map((n) => n.name).filter(Boolean),
...flatB.map((n) => n.name).filter(Boolean),
])
) as string[];
const nodes: NodeExecutionDiff[] = [];
let divergedNodesCount = 0;
let statusDiffCount = 0;
for (const name of allNames) {
const nodeA = flatA.find((n) => n.name === name);
const nodeB = flatB.find((n) => n.name === name);
const statusA = nodeA?.status;
const statusB = nodeB?.status;
const isStatusDiff = statusA !== statusB;
if (isStatusDiff) statusDiffCount++;
// 比较 inputs
const inputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = [];
const inA = (nodeA?.inputs as Record<string, unknown>) || {};
const inB = (nodeB?.inputs as Record<string, unknown>) || {};
const inputKeys = Array.from(new Set([...Object.keys(inA), ...Object.keys(inB)]));
for (const k of inputKeys) {
if (JSON.stringify(inA[k]) !== JSON.stringify(inB[k])) {
inputsDiff.push({ field: k, from: inA[k], to: inB[k] });
}
}
// 比较 outputs
const outputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = [];
const outA = (nodeA?.outputs as Record<string, unknown>) || {};
const outB = (nodeB?.outputs as Record<string, unknown>) || {};
const outputKeys = Array.from(new Set([...Object.keys(outA), ...Object.keys(outB)]));
for (const k of outputKeys) {
if (JSON.stringify(outA[k]) !== JSON.stringify(outB[k])) {
outputsDiff.push({ field: k, from: outA[k], to: outB[k] });
}
}
const isDiverged =
!nodeA ||
!nodeB ||
isStatusDiff ||
Boolean(nodeB.error && !nodeA.error) ||
inputsDiff.length > 0;
if (isDiverged) divergedNodesCount++;
nodes.push({
taskName: name,
displayName: (nodeB?.displayName || nodeA?.displayName || nodeB?.label || nodeA?.label) ?? undefined,
type: nodeB?.type || nodeA?.type,
statusA,
statusB,
durationMsA: nodeA?.executionTime,
durationMsB: nodeB?.executionTime,
errorA: nodeA?.error,
errorB: nodeB?.error,
inputsDiff,
outputsDiff,
diverged: isDiverged,
});
}
return {
jobA: {
id: jobA.id,
pipelineId: jobA.pipelineId,
state: typeof jobA.state === "string" || typeof jobA.state === "number" ? jobA.state : undefined,
startTime: jobA.startTime ? String(jobA.startTime) : undefined,
durationTime: typeof jobA.durationTime === "number" ? jobA.durationTime : undefined,
hasError: Boolean(jobA.hasError),
errorCount: typeof (jobA as any).errorTaskCount === "number" ? (jobA as any).errorTaskCount : undefined,
},
jobB: {
id: jobB.id,
pipelineId: jobB.pipelineId,
state: typeof jobB.state === "string" || typeof jobB.state === "number" ? jobB.state : undefined,
startTime: jobB.startTime ? String(jobB.startTime) : undefined,
durationTime: typeof jobB.durationTime === "number" ? jobB.durationTime : undefined,
hasError: Boolean(jobB.hasError),
errorCount: typeof (jobB as any).errorTaskCount === "number" ? (jobB as any).errorTaskCount : undefined,
},
nodes,
summary: {
totalNodesA: flatA.length,
totalNodesB: flatB.length,
divergedNodesCount,
statusDiffCount,
},
};
}
export function getWorkflowDebugSource(...args: Parameters<typeof api.getWorkflowDebugSource>) {
return api.getWorkflowDebugSource(...args);
}
export function triggerWorkflowDebug(...args: Parameters<typeof api.triggerWorkflowDebug>) {
return api.triggerWorkflowDebug(...args);
}
export async function runWorkflowDebugTest(
client: import("ky").KyInstance,
pipelineId: string,
options: {
flowCodeOrId: string;
autoPublish?: boolean;
timeoutMs?: number;
pollIntervalMs?: number;
}
): Promise<import("./types.js").WorkflowTestReport> {
let targetEntityId = options.flowCodeOrId;
const isDirectCode = options.flowCodeOrId.includes("-") || options.flowCodeOrId.startsWith("ID01");
if (!isDirectCode) {
try {
const source = await api.getWorkflowDebugSource(client, pipelineId, {
page: 1,
pageSize: 10,
keywords: options.flowCodeOrId,
});
const matched = source.items.find(
(item) => item.id === options.flowCodeOrId || item.title.includes(options.flowCodeOrId)
);
if (matched) {
targetEntityId = matched.id;
}
} catch {
// 关键字搜索超时或失败时直接回退使用传入值
}
}
const jobId = await api.triggerWorkflowDebug(client, pipelineId, {
entityId: targetEntityId,
autoPublish: options.autoPublish ?? false,
});
const timeoutMs = options.timeoutMs ?? 15000;
const pollIntervalMs = options.pollIntervalMs ?? 500;
const start = Date.now();
let finalJob: import("./types.js").WorkflowJobDetail | undefined;
while (Date.now() - start < timeoutMs) {
try {
const job = await api.getJob(client, jobId);
const state = (job.status || (job as any).state || "").toUpperCase();
if (state === "COMPLETED" || state === "FAILED" || state === "STOP") {
finalJob = job;
break;
}
} catch {
// 任务刚创建可能存在短延时,继续轮询
}
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
}
if (!finalJob) {
finalJob = await api.getJob(client, jobId);
}
const [tree, failedPage] = await Promise.all([
api.getJobExecutionTree(client, jobId).catch(() => []),
api.getJobFailedExecutions(client, jobId).catch(() => ({
number: 1,
size: 100,
totalPages: 0,
totalItems: 0,
items: [],
})),
]);
const rawFailed = extractFailureExecutions(tree, failedPage.items);
const conditionDiagnoses = explainConditionBranches(tree);
return {
jobId,
pipelineId,
status: finalJob.status || (finalJob as any).state || "UNKNOWN",
runType: finalJob.runType || "DEBUG",
durationTime: typeof (finalJob as any).durationTime === "number" ? (finalJob as any).durationTime : undefined,
targetEntityId,
executionTree: tree,
failedExecutions: rawFailed,
conditionDiagnoses,
};
}
export {
explainConditionBranches,
type ConditionBranchExplanation,
type ConditionRuleExplanation,
} from "./workflow-branch.js";
+133
View File
@@ -507,3 +507,136 @@ export type WorkflowListAllError = z.infer<typeof WorkflowListAllErrorSchema>;
export type TaskMatch = z.infer<typeof TaskMatchSchema>;
export type WorkflowWithMatches = z.infer<typeof WorkflowWithMatchesSchema>;
// ── 工作流快照与 Job 差异比对模型 ──────────────────────────────────────────
export interface TaskConfigDiff {
taskName: string;
displayName?: string;
type: string;
changeType: "ADDED" | "REMOVED" | "MODIFIED";
codeDiff?: {
from?: string;
to?: string;
unifiedDiff?: string;
};
filterDiff?: {
from?: unknown;
to?: unknown;
};
configChanges: Array<{
field: string;
from?: unknown;
to?: unknown;
}>;
}
export interface WorkflowSnapshotDiff {
snapshotA: {
id: string;
version?: string;
updateTime?: string;
staffName?: string;
};
snapshotB: {
id: string;
version?: string;
updateTime?: string;
staffName?: string;
};
addedTasks: string[];
removedTasks: string[];
modifiedTasks: TaskConfigDiff[];
summary: {
totalA: number;
totalB: number;
changedCount: number;
};
}
export interface NodeExecutionDiff {
taskName: string;
displayName?: string;
type?: string;
statusA?: string;
statusB?: string;
durationMsA?: number;
durationMsB?: number;
errorA?: unknown;
errorB?: unknown;
inputsDiff?: Array<{
field: string;
from?: unknown;
to?: unknown;
}>;
outputsDiff?: Array<{
field: string;
from?: unknown;
to?: unknown;
}>;
diverged: boolean;
}
export interface WorkflowJobDiff {
jobA: {
id: string;
pipelineId?: string;
state?: string | number;
startTime?: string;
durationTime?: number;
hasError?: boolean;
errorCount?: number;
};
jobB: {
id: string;
pipelineId?: string;
state?: string | number;
startTime?: string;
durationTime?: number;
hasError?: boolean;
errorCount?: number;
};
nodes: NodeExecutionDiff[];
summary: {
totalNodesA: number;
totalNodesB: number;
divergedNodesCount: number;
statusDiffCount: number;
};
}
// ── 调试数据源与测试结果 ───────────────────────────────────────────────────────
export const WorkflowDebugSourceItemSchema = z
.object({
id: z.string(),
title: z.string().default(""),
flowState: z.string().default(""),
})
.passthrough();
export const WorkflowDebugSourceResultSchema = z
.object({
type: z.string().default(""),
total: z.number().default(0),
items: z.array(WorkflowDebugSourceItemSchema).default([]),
fields: z.array(z.object({ key: z.string(), label: z.string() })).default([]),
label: z.string().default(""),
})
.passthrough();
export type WorkflowDebugSourceItem = z.infer<typeof WorkflowDebugSourceItemSchema>;
export type WorkflowDebugSourceResult = z.infer<typeof WorkflowDebugSourceResultSchema>;
export interface WorkflowTestReport {
jobId: string;
pipelineId: string;
status: string;
runType: string;
durationTime?: number;
targetEntityId: string;
executionTree: WorkflowTaskExecution[];
failedExecutions: WorkflowTaskExecution[];
conditionDiagnoses: import("./workflow-branch.js").ConditionBranchExplanation[];
}
@@ -0,0 +1,141 @@
import { describe, expect, it } from "bun:test";
import { explainConditionBranches } from "./workflow-branch.js";
import type { WorkflowTaskExecution } from "./types.js";
describe("Workflow Condition Branch Diagnosis", () => {
it("diagnoses missing upstream property when property is absent from outputs", () => {
const tree: WorkflowTaskExecution[] = [
{
id: "exec-trigger",
name: "trigger_1",
label: "单据审批事件触发器",
type: "ekuaibao-flowform-trigger",
status: "COMPLETED",
output: { code: "ZJ-001" },
},
{
id: "exec-detail",
name: "action_detail",
label: "查询单据详情",
type: "flow-detail",
status: "COMPLETED",
output: {
approvers: ["ID_YANGJIE"],
},
},
{
id: "exec-condition",
name: "control_1",
label: "条件节点",
type: "condition",
status: "COMPLETED",
combineFilters: {
filters: [
{
filters: [
{
key: "@{choose('{\"key\":\"action_detail\",\"properties\":[{\"key\":\"currentApprovers\",\"label\":\"审批人\"}]}')}",
value: ["@{value('{\"key\":\"ID_YANGJIE\",\"label\":\"杨洁\"}')}"],
compare: "eq",
},
],
},
],
},
tasks: [
{
name: "action_http",
label: "自动审批",
type: "http",
},
],
} as any,
];
const res = explainConditionBranches(tree);
expect(res).toHaveLength(1);
expect(res[0].conditionNodeName).toBe("control_1");
expect(res[0].hasSkippedTasks).toBe(true);
expect(res[0].rules[0].isMissing).toBe(true);
expect(res[0].rules[0].upstreamProp).toBe("currentApprovers");
expect(res[0].summary).toContain("条件字段脱节");
});
it("diagnoses value mismatch when upstream property exists but values differ", () => {
const tree: WorkflowTaskExecution[] = [
{
id: "exec-trigger",
name: "trigger_1",
label: "单据审批事件触发器",
type: "ekuaibao-flowform-trigger",
status: "COMPLETED",
output: {
userInfo: "ID_ZANGKEXIN",
},
},
{
id: "exec-condition",
name: "control_1",
label: "条件节点",
type: "condition",
status: "COMPLETED",
combineFilters: {
filters: [
{
filters: [
{
key: "@{choose('{\"key\":\"trigger_1\",\"properties\":[{\"key\":\"userInfo\",\"label\":\"待处理人\"}]}')}",
value: "@{value('{\"key\":\"ID_YANGJIE\",\"label\":\"杨洁\"}')}",
compare: "eq",
},
],
},
],
},
tasks: [
{
name: "action_http",
label: "自动审批",
type: "http",
},
],
} as any,
];
const res = explainConditionBranches(tree);
expect(res).toHaveLength(1);
expect(res[0].hasSkippedTasks).toBe(true);
expect(res[0].rules[0].isMissing).toBe(false);
expect(res[0].rules[0].matched).toBe(false);
expect(res[0].rules[0].actualValue).toBe("ID_ZANGKEXIN");
});
it("returns empty diagnosis when child task was executed successfully", () => {
const tree: WorkflowTaskExecution[] = [
{
id: "exec-condition",
name: "control_1",
label: "条件节点",
type: "condition",
status: "COMPLETED",
tasks: [
{
name: "action_http",
label: "自动审批",
type: "http",
},
],
} as any,
{
id: "exec-http",
name: "action_http",
label: "自动审批",
type: "http",
status: "COMPLETED",
},
];
const res = explainConditionBranches(tree);
expect(res).toHaveLength(0);
});
});
+263
View File
@@ -0,0 +1,263 @@
import type { WorkflowTaskExecution } from "./types.js";
export interface ConditionRuleExplanation {
leftLabel: string;
upstreamNode: string;
upstreamProp: string;
operator: string;
operatorLabel: string;
expectedValue: any;
actualValue: any;
isMissing: boolean;
matched: boolean;
detail: string;
}
export interface ConditionBranchExplanation {
conditionNodeId: string;
conditionNodeName: string;
conditionNodeLabel: string;
hasSkippedTasks: boolean;
skippedTaskNames: string[];
rules: ConditionRuleExplanation[];
summary: string;
}
const OP_MAP: Record<string, string> = {
eq: "等于",
neq: "不等于",
include: "包含",
not_include: "不包含",
in: "在列表中",
not_in: "不在列表中",
gt: "大于",
gte: "大于等于",
lt: "小于",
lte: "小于等于",
empty: "为空",
not_empty: "不为空",
};
/**
* 尝试从 @{choose('...')} 标签中提取上游节点名、属性名与可读标签
*/
function parseChooseTag(tag: string): {
upstreamNode: string;
upstreamProp: string;
label: string;
} | null {
if (typeof tag !== "string") return null;
const match = tag.match(/@\{choose\('(.*)'\)\}/);
if (!match) return null;
try {
const parsed = JSON.parse(match[1]);
const upstreamNode = parsed.key || "";
const upstreamProp = parsed.properties?.[0]?.key || "";
const label = parsed.label || `${upstreamNode}.${upstreamProp}`;
return { upstreamNode, upstreamProp, label };
} catch {
return null;
}
}
/**
* 尝试从 @{value('...')} 中提取人类可读值
*/
function parseValueTag(val: any): any {
if (Array.isArray(val)) {
return val.map((v) => parseValueTag(v));
}
if (typeof val === "string") {
const match = val.match(/@\{value\('(.*)'\)\}/);
if (match) {
try {
const parsed = JSON.parse(match[1]);
return parsed.label ? `${parsed.label} (${parsed.key})` : parsed.key || parsed.value;
} catch {
return val;
}
}
}
return val;
}
/**
* 比较两个值是否匹配
*/
function evaluateRule(actual: any, expected: any, compare: string): boolean {
if (actual === undefined || actual === null) {
if (compare === "empty") return true;
if (compare === "not_empty") return false;
return false;
}
const actualStr = String(actual);
const expectedStr = typeof expected === "string" ? expected : JSON.stringify(expected);
switch (compare) {
case "eq":
if (Array.isArray(actual)) {
if (Array.isArray(expected)) {
return JSON.stringify(actual) === JSON.stringify(expected);
}
return actual.length === 1 && String(actual[0]) === expectedStr;
}
return actualStr === expectedStr;
case "neq":
return actualStr !== expectedStr;
case "include":
if (Array.isArray(actual)) {
return actual.some((item) => String(item).includes(expectedStr) || expectedStr.includes(String(item)));
}
return actualStr.includes(expectedStr);
case "not_include":
if (Array.isArray(actual)) {
return !actual.some((item) => String(item).includes(expectedStr));
}
return !actualStr.includes(expectedStr);
case "empty":
return Array.isArray(actual) ? actual.length === 0 : !actual;
case "not_empty":
return Array.isArray(actual) ? actual.length > 0 : Boolean(actual);
default:
return actualStr === expectedStr;
}
}
/**
* 分析 Job 执行树中的条件节点,诊断分支是否跳过及跳过的具体字段原因
*/
export function explainConditionBranches(
tree: WorkflowTaskExecution[]
): ConditionBranchExplanation[] {
const nodeMap = new Map<string, WorkflowTaskExecution>();
const executedNames = new Set<string>();
for (const node of tree) {
if (node.name) {
nodeMap.set(node.name, node);
executedNames.add(node.name);
}
if (node.id) {
nodeMap.set(node.id, node);
}
}
const explanations: ConditionBranchExplanation[] = [];
for (const node of tree) {
const rawNode = node as Record<string, any>;
if (rawNode.type !== "condition") continue;
const childTasks = Array.isArray(rawNode.tasks) ? rawNode.tasks : [];
if (childTasks.length === 0) continue;
// 检查子任务是否执行过
const childNames = childTasks.map((t: any) => t.name || t.id).filter(Boolean);
const anyExecuted = childNames.some((name: string) => executedNames.has(name));
if (anyExecuted) {
// 子分支正常执行,无需诊断跳过
continue;
}
const skippedTaskNames = childTasks.map((t: any) => `${t.name || t.id} (${t.label || t.displayName || t.type})`);
const rules: ConditionRuleExplanation[] = [];
// 解析 combineFilters
const rawFilters = rawNode.combineFilters?.filters;
if (Array.isArray(rawFilters)) {
for (const group of rawFilters) {
const subFilters = Array.isArray(group.filters) ? group.filters : [group];
for (const f of subFilters) {
const chooseInfo = parseChooseTag(f.key);
const rawExpected = f.value;
const parsedExpected = parseValueTag(rawExpected);
const op = f.compare || "eq";
const opLabel = OP_MAP[op] || op;
let upstreamNode = "";
let upstreamProp = "";
let leftLabel = String(f.key);
if (chooseInfo) {
upstreamNode = chooseInfo.upstreamNode;
upstreamProp = chooseInfo.upstreamProp;
leftLabel = chooseInfo.label;
} else if (typeof f.key === "string") {
upstreamProp = f.key;
}
// 从上游节点提取真实 outputs
const upstreamExecution = upstreamNode ? nodeMap.get(upstreamNode) : undefined;
const upstreamOutputs = upstreamExecution?.output ?? (upstreamExecution as any)?.outputs;
let actualVal: any = undefined;
let isMissing = false;
if (upstreamOutputs && typeof upstreamOutputs === "object") {
if (upstreamProp in upstreamOutputs) {
actualVal = upstreamOutputs[upstreamProp];
} else {
isMissing = true;
}
} else if (upstreamExecution) {
isMissing = true;
}
// 提取纯净 ID 比对
let cleanExpected = rawExpected;
if (typeof rawExpected === "string" && rawExpected.includes("@{value(")) {
const m = rawExpected.match(/"key":"([^"]+)"/);
if (m) cleanExpected = m[1];
} else if (Array.isArray(rawExpected) && rawExpected.length > 0 && typeof rawExpected[0] === "string") {
const m = rawExpected[0].match(/"key":"([^"]+)"/);
if (m) cleanExpected = m[1];
}
const matched = evaluateRule(actualVal, cleanExpected, op);
let detail = "";
if (isMissing) {
const availableKeys = upstreamOutputs ? Object.keys(upstreamOutputs).join(", ") : "无出参";
detail = `上游节点 [${upstreamNode}] 未返回该属性 [${upstreamProp}](字段名可能脱节,上游可用字段: ${availableKeys})➔ 解析值为 null`;
} else {
const actStr = typeof actualVal === "object" ? JSON.stringify(actualVal) : String(actualVal ?? "null");
const expStr = typeof parsedExpected === "object" ? JSON.stringify(parsedExpected) : String(parsedExpected);
detail = `实际值: ${actStr} 与期望值 [${expStr}] 比对结果为 ${matched ? "True" : "False"}`;
}
rules.push({
leftLabel,
upstreamNode,
upstreamProp,
operator: op,
operatorLabel: opLabel,
expectedValue: parsedExpected,
actualValue: actualVal,
isMissing,
matched,
detail,
});
}
}
}
let summary = `条件判定未通过 (False),子任务 [${skippedTaskNames.join(", ")}] 被跳过未执行`;
const missingRule = rules.find((r) => r.isMissing);
if (missingRule) {
summary = `条件字段脱节: 上游节点 [${missingRule.upstreamNode}] 缺少属性 [${missingRule.upstreamProp}],判定为 False,子任务被跳过`;
}
explanations.push({
conditionNodeId: node.id,
conditionNodeName: node.name || "-",
conditionNodeLabel: node.label || (node as any).displayName || "条件节点",
hasSkippedTasks: true,
skippedTaskNames,
rules,
summary,
});
}
return explanations;
}
@@ -22,6 +22,12 @@ import {
toggleWorkflow,
updateWorkflow,
} from "./api.js";
import {
extractFailureExecutions,
findExecutionNode,
flattenExecutionTree,
isTaskExecutionFailed,
} from "./services.js";
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
import { WorkflowAlertStore } from "./workflow-alert-store.js";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
@@ -302,4 +308,92 @@ describe("workflow draft state machine", () => {
const logs = await getExecutionLogs(client, "892809893789696012");
expect(logs[0]?.message).toBe("MVEL script executed");
});
describe("execution tree inspection & failure extraction helpers", () => {
const mockTree: any[] = [
{
id: "node_1",
name: "start_node",
type: "start",
status: "COMPLETED",
children: [
{
id: "node_2",
name: "loop_node",
type: "loop",
status: "COMPLETED",
tasks: [
{
id: "node_3",
name: "approve_node",
displayName: "资金调拨自动审批",
type: "flow-approval",
status: "FAILED",
error: { message: "400: 无待办审批事项" },
inputs: { formId: "ZJ-001368", action: "agree" },
},
],
},
],
},
{
id: "node_4",
name: "notice_node",
displayName: "钉钉通知",
type: "dingtalk",
status: "COMPLETED",
},
];
it("flattenExecutionTree flattens nested children and tasks recursively", () => {
const flattened = flattenExecutionTree(mockTree);
expect(flattened).toHaveLength(4);
expect(flattened.map((n) => n.id)).toEqual(["node_1", "node_2", "node_3", "node_4"]);
});
it("isTaskExecutionFailed identifies various failure indicators", () => {
expect(isTaskExecutionFailed({ id: "1", type: "x", status: "FAILED" })).toBe(true);
expect(
isTaskExecutionFailed({
id: "2",
type: "x",
status: "RUNNING",
error: { message: "timeout", stackTrace: [] },
})
).toBe(true);
expect(isTaskExecutionFailed({ id: "3", type: "x", status: "OK", outputs: { error: "reject" } } as any)).toBe(true);
expect(isTaskExecutionFailed({ id: "4", type: "x", status: "COMPLETED" })).toBe(false);
});
it("extractFailureExecutions merges failures from tree and failed items without duplicates", () => {
const failedPageItems: any[] = [
{
id: "node_3",
name: "approve_node",
status: "FAILED",
outputs: { details: "failed downstream" },
},
];
const failures = extractFailureExecutions(mockTree, failedPageItems);
expect(failures).toHaveLength(1);
expect(failures[0].id).toBe("node_3");
expect(failures[0].error?.message).toBe("400: 无待办审批事项");
expect((failures[0] as any).inputs?.formId).toBe("ZJ-001368");
expect((failures[0] as any).outputs?.details).toBe("failed downstream");
});
it("findExecutionNode matches by id, exact name, or partial display name", () => {
const byId = findExecutionNode(mockTree, "node_3");
expect(byId?.id).toBe("node_3");
const byName = findExecutionNode(mockTree, "approve_node");
expect(byName?.id).toBe("node_3");
const byDisplayName = findExecutionNode(mockTree, "资金调拨");
expect(byDisplayName?.id).toBe("node_3");
const notFound = findExecutionNode(mockTree, "non_existent");
expect(notFound).toBeUndefined();
});
});
});
+45
View File
@@ -0,0 +1,45 @@
/**
* hose-use SDK: 针对脚本编写、自动化批处理与外部 Agent 集成的标准公共 API 界面。
* 彻底消除外部脚本对内部私有路径和动态字段报文结构的直接依赖。
*/
export { initCorpRuntime, createClientsForCorp, requireSelectedCorp } from "./cli/helpers.js";
export { resolveCorpConfig } from "./core/config/manager.js";
// DataLink / 自建应用与业务对象能力
export {
listPlatforms,
listAllPlatforms,
getPlatform,
resolvePlatform,
listPlatformEntities,
resolveEntity,
searchEntityRecords,
fetchAllEntityRecords,
iterateAllEntityRecords,
normalizeDatalinkRecord,
calculateEntityRecordStats,
auditEntityRecords,
aggregateRecordFields,
filterRecordsByPredicate,
batchSafeEditRecords,
editRecord,
safeEditRecord,
getRecordDetail,
toggleRecordState,
} from "./domains/datalink/services.js";
export type {
DatalinkPlatformDetail,
DatalinkEntity,
DatalinkField,
DatalinkRecord,
NormalizedDatalinkRecord,
DatalinkRecordStats,
LedgerAggregateReport,
} from "./domains/datalink/types.js";
export type {
DatalinkAuditReport,
BatchEditTargetItem,
} from "./domains/datalink/services.js";