Compare commits
7
Commits
v0.8.13
...
d37ebb7fcd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d37ebb7fcd | ||
|
|
ffec604ed9 | ||
|
|
7891959853 | ||
|
|
0c6a3ee660 | ||
|
|
0499ccb2cc | ||
|
|
f91a80f9dd | ||
|
|
95eb8ee676 |
No files matched your search
@@ -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 已封装,命令未实现)
|
||||
@@ -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` — 删除规则(接口待确认)
|
||||
@@ -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): 新增工作流控制及辅助工具
|
||||
@@ -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"]);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 <单号>`);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
@@ -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(
|
||||
{
|
||||
|
||||
@@ -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 的统一执行环境",
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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}`,
|
||||
``,
|
||||
|
||||
@@ -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 || "-",
|
||||
]);
|
||||
|
||||
|
||||
@@ -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("诊断提示");
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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} 个自建应用)` : "🔴 失败",
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
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] 的执行树中找到匹配 \"不存在的节点\" 的节点");
|
||||
});
|
||||
});
|
||||
@@ -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(
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import {
|
||||
extractFailureExecutions,
|
||||
findExecutionNode,
|
||||
flattenExecutionTree,
|
||||
getExecutionLogs,
|
||||
getJob,
|
||||
getJobExecutionLevel,
|
||||
getJobExecutionTree,
|
||||
getJobFailedExecutions,
|
||||
isTaskExecutionFailed,
|
||||
listPlatforms,
|
||||
} from "../../../domains/platform/services.js";
|
||||
import type { WorkflowTaskExecution } from "../../../domains/platform/types.js";
|
||||
@@ -101,7 +105,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 +115,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 +214,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 +316,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 +370,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: "",
|
||||
|
||||
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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"],
|
||||
|
||||
@@ -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,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);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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("数据库初始化时自动种子化默认偏好配置", () => {
|
||||
|
||||
@@ -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,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";
|
||||
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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("请核对单号是否准确");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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> : {};
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
WorkflowSummary,
|
||||
WorkflowListAllError,
|
||||
WorkflowTask,
|
||||
WorkflowTaskExecution,
|
||||
WorkflowWithMatches,
|
||||
TaskMatch,
|
||||
} from "./types.js";
|
||||
@@ -213,3 +214,109 @@ 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)
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user