Merge pull request #183 from yunyingk/feat/outbound-command
CI / validate (push) Canceled after 0s

feat: 新增工作流出站消息规则与日志透视命令
This commit is contained in:
yunyingk authored and GitHub committed 2026-11-10 18:16:38 +08:00
commit de88e218e7
8 files changed
+273 -4

No files matched your search

+9 -3
View File
@@ -277,8 +277,10 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"lint-script": "静态检查 JavaScript / MVEL 脚本",
"eval-script": "在本地沙箱中模拟执行脚本",
"webhook": "向工作流 Webhook 触发器发送测试数据 (别名: webhook-send)",
"link": "生成工作流设计器 (Piper) 免密直达链接 (包含特权警告)"
"link": "生成工作流设计器 (Piper) 免密直达链接 (包含特权警告)",
"outbound": "查询合思系统出站消息规则与投递日志 (list|logs)"
},
"options": [
"--flow=<单号> 指定测试单据",
"--file=<workflow.json> 指定工作流快照",
@@ -333,9 +335,13 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"webhook-send": "webhook",
"webhooks": "webhook",
"url": "link",
"web": "link"
"web": "link",
"outbounds": "outbound",
"outbound-message": "outbound"
},
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail is-test json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail is-test json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
},
"bill": {
"summary": "单据检索、表单规格诊断与审批动作",
+8 -1
View File
@@ -17,6 +17,8 @@ import { handleWorkflowLintScript, handleWorkflowEvalScript } from "./script.js"
import { handleWorkflowEnum } from "./enum.js";
import { handleWebhookCommand } from "./webhook.js";
import { handleWorkflowLink } from "./link.js";
import { handleOutboundCommand } from "./outbound.js";
export async function handleWorkflowCommand(
parsed: CliParsedArgs,
@@ -126,11 +128,16 @@ export async function handleWorkflowCommand(
case "url":
case "web":
return handleWorkflowLink(parsed, runtime);
case "outbound":
case "outbounds":
case "outbound-message":
return handleOutboundCommand(parsed, runtime);
default:
return {
stdout: "",
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook, link\n`,
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook, link, outbound\n`,
exitCode: 1,
};
}
}
@@ -0,0 +1,16 @@
import { describe, expect, it } from "bun:test";
import { handleOutboundCommand } from "./outbound.js";
import type { CliParsedArgs, CliRuntime } from "../../types.js";
describe("handleOutboundCommand", () => {
it("rejects when no corp selected", async () => {
const result = await handleOutboundCommand(
{ args: ["list"], options: {}, raw: [] },
{ selectedCorp: null, jsonMode: false } as unknown as CliRuntime
);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("未选中企业");
});
});
+113
View File
@@ -0,0 +1,113 @@
import { stringOption, numberOption } from "../../parser.js";
import { printJson, printTable } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createSessionClient } from "../../../core/http/session-client.js";
import { getOutboundMessages, queryOutboundMessageLogs } from "../../../domains/platform/workflow/services.js";
function formatTime(timestamp: number | undefined): string {
if (!timestamp) return "-";
const date = new Date(timestamp);
return date.toLocaleString("zh-CN", { hour12: false });
}
export async function handleOutboundCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) {
return {
stdout: "",
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
exitCode: 1,
};
}
const sub = parsed.args[0] || "list";
const corpId = corp.corpId || corp.id;
const client = await createSessionClient(corp);
if (sub === "list" || sub === "rules") {
const rules = await getOutboundMessages(client, corpId);
if (runtime.jsonMode) {
return {
stdout: printJson({ corpId, total: rules.length, items: rules }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "规则名称", "类型", "状态", "目标回调 URL", "监听事件"];
const rows = rules.map((r, i) => [
String(i + 1),
r.messageName || "-",
r.messageType || "-",
r.enable ? "🟢 启用" : "⚪ 停用",
r.callbackUrl || "-",
r.actionEvent && r.actionEvent.length ? r.actionEvent.join(", ") : "全部/默认",
]);
const title = `====== [${corp.name}] 出站消息规则列表 (共 ${rules.length} 条) ======\n`;
return {
stdout: title + (rules.length ? printTable(headers, rows) : " (暂无配置)\n"),
stderr: "",
exitCode: 0,
};
}
if (sub === "logs" || sub === "log") {
const code = stringOption(parsed.options, ["code", "sn", "flow", "bill"]) || (parsed.args[1] && !parsed.args[1].startsWith("-") ? parsed.args[1] : undefined);
const messageType = stringOption(parsed.options, ["type", "message-type"]) || "flow";
const start = numberOption(parsed.options, ["start", "offset"], 0) ?? 0;
const count = numberOption(parsed.options, ["count", "limit", "n"], 20) ?? 20;
const result = await queryOutboundMessageLogs(client, corpId, {
messageType,
code,
start,
count,
});
if (runtime.jsonMode) {
return {
stdout: printJson({ corpId, code, total: result.count, items: result.items }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "单号", "规则名", "动作/阶段", "状态", "投递时间", "目标 URL / 响应详情"];
const rows = result.items.map((item, i) => {
const sn = item.flowId?.form?.code || item.request?.code || "-";
const statusIcon = item.state === "SUCCESS" ? "✅ 成功" : item.state === "FAILED" ? "❌ 失败" : item.state;
const respPreview = typeof item.response === "object" && item.response !== null
? JSON.stringify(item.response).slice(0, 60)
: String(item.response ?? "-").slice(0, 60);
return [
String(i + 1),
sn,
item.name || "-",
`${item.type} (${item.nodeName || "-"})`,
statusIcon,
formatTime(item.createTime),
respPreview,
];
});
const filterDesc = code ? ` | 单号筛选: ${code}` : "";
const title = `====== [${corp.name}] 出站消息投递日志 (类型: ${messageType}${filterDesc} | 匹配: ${result.count} | 返回: ${result.items.length}) ======\n`;
return {
stdout: title + (result.items.length ? printTable(headers, rows) : " (暂无匹配日志)\n"),
stderr: "",
exitCode: 0,
};
}
return {
stdout: "",
stderr: `未知 outbound 子命令: ${sub}。支持: list (别名: rules), logs [单号] [--type=flow|message]\n`,
exitCode: 1,
};
}
@@ -82,3 +82,11 @@ export {
export * from "./index.js";
export { webhookTriggerUrl } from "./triggers/index.js";
export {
getOutboundMessages,
queryOutboundMessageLogs,
type OutboundMessageConfig,
type OutboundMessageLogItem,
type OutboundLogQueryOptions,
} from "./transport/outbound/index.js";
@@ -0,0 +1,57 @@
import type { KyInstance } from "ky";
import type { OutboundMessageConfig, OutboundMessageLogItem, OutboundLogQueryOptions } from "./types.js";
/**
* 传输层:查询指定企业配置的出站消息列表
* 对应合思底层接口:GET api/outbound/v1/message
*/
export async function getOutboundMessages(
client: KyInstance,
corpId: string
): Promise<OutboundMessageConfig[]> {
const response = await client.get("api/outbound/v1/message", {
searchParams: { corpId },
});
const json = (await response.json()) as { items?: unknown[] };
return (json.items ?? []) as OutboundMessageConfig[];
}
/**
* 传输层:分页查询出站消息投递执行日志
* 对应合思底层接口:POST api/outbound/v1/message/messageLog
*/
export async function queryOutboundMessageLogs(
client: KyInstance,
corpId: string,
options: OutboundLogQueryOptions = {}
): Promise<{ count: number; items: OutboundMessageLogItem[] }> {
const messageType = options.messageType ?? "flow";
const start = options.start ?? 0;
const count = options.count ?? 20;
const body: Record<string, unknown> = {
limit: { start, count },
orderBy: [{ value: "createTime", order: "DESC" }],
select: "id,name,flowId(id, form(code)),nodeName,type,request,response,state,type,createTime,messageType",
};
if (options.filterBy) {
body.filterBy = options.filterBy;
} else if (options.code) {
body.filterBy = `(flowId.form.code==("${options.code.replace(/"/g, '\\"')}"))`;
}
const response = await client.post("api/outbound/v1/message/messageLog", {
searchParams: {
messageType,
corpId,
},
json: body,
});
const json = (await response.json()) as { count?: number; items?: OutboundMessageLogItem[] };
return {
count: json.count ?? json.items?.length ?? 0,
items: json.items ?? [],
};
}
@@ -0,0 +1,2 @@
export * from "./api.js";
export * from "./types.js";
@@ -0,0 +1,60 @@
export interface OutboundMessageConfig {
id: string;
messageName?: string;
messageType?: "flow" | "message" | "InternalMessage" | "dataLink" | string;
enable?: boolean;
callbackUrl?: string;
signKey?: string;
actionEvent?: string[] | null;
formFields?: string[];
conditions?: Array<{
left?: string;
operator?: string;
right?: { type?: string; value?: unknown };
}> | null;
remark?: string | null;
corporationId?: string;
createTime?: number;
updateTime?: number;
[key: string]: unknown;
}
export interface OutboundMessageLogItem {
id: string;
name: string;
type: "INVOKING" | "CALLBACK" | string;
state: "SUCCESS" | "FAILED" | string;
flowId?: {
id?: string;
form?: {
code?: string;
};
};
nodeName?: string;
createTime: number;
messageType?: string;
request?: {
code?: string;
flowId?: string;
nodeId?: string;
messageId?: string;
corporationId?: string;
action?: string;
comment?: string;
signKey?: string;
formSpecification?: {
specificationId?: string;
specificationName?: string;
};
[key: string]: unknown;
};
response?: unknown;
}
export interface OutboundLogQueryOptions {
messageType?: string;
code?: string;
filterBy?: string;
start?: number;
count?: number;
}