From 020e4a2761c3746da15c4c292226ad6661206cfc Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 10 Nov 2026 18:15:12 +0800 Subject: [PATCH] =?UTF-8?q?feat(workflow):=20=E6=96=B0=E5=A2=9E=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E5=87=BA=E7=AB=99=E6=B6=88=E6=81=AF=E8=A7=84=E5=88=99?= =?UTF-8?q?=E4=B8=8E=E6=97=A5=E5=BF=97=E9=80=8F=E8=A7=86=E5=91=BD=E4=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在 `domains/platform/workflow/transport/outbound/` 接入合思 `api/outbound/v1/message` 与 `api/outbound/v1/message/messageLog` 接口; - 在 `domains/platform/workflow/services.ts` 暴露 `getOutboundMessages` 与 `queryOutboundMessageLogs` 服务门面; - 新增 `hose-use workflow outbound (list|logs)` 命令与别名支持; - 在 `command-metadata.ts` 补齐对应子命令与 `--sn`、`--message-type`、`--start`、`--offset` 等参数校验契约; - 补齐单元测试并通过全量单测与类型检查。 --- src/cli/command-metadata.ts | 12 +- src/cli/commands/workflow/index.ts | 9 +- src/cli/commands/workflow/outbound.test.ts | 16 +++ src/cli/commands/workflow/outbound.ts | 113 ++++++++++++++++++ src/domains/platform/workflow/services.ts | 8 ++ .../workflow/transport/outbound/api.ts | 57 +++++++++ .../workflow/transport/outbound/index.ts | 2 + .../workflow/transport/outbound/types.ts | 60 ++++++++++ 8 files changed, 273 insertions(+), 4 deletions(-) create mode 100644 src/cli/commands/workflow/outbound.test.ts create mode 100644 src/cli/commands/workflow/outbound.ts create mode 100644 src/domains/platform/workflow/transport/outbound/api.ts create mode 100644 src/domains/platform/workflow/transport/outbound/index.ts create mode 100644 src/domains/platform/workflow/transport/outbound/types.ts diff --git a/src/cli/command-metadata.ts b/src/cli/command-metadata.ts index 76922e3..f8e0f24 100644 --- a/src/cli/command-metadata.ts +++ b/src/cli/command-metadata.ts @@ -277,8 +277,10 @@ export const COMMAND_METADATA: Record = { "lint-script": "静态检查 JavaScript / MVEL 脚本", "eval-script": "在本地沙箱中模拟执行脚本", "webhook": "向工作流 Webhook 触发器发送测试数据 (别名: webhook-send)", - "link": "生成工作流设计器 (Piper) 免密直达链接 (包含特权警告)" + "link": "生成工作流设计器 (Piper) 免密直达链接 (包含特权警告)", + "outbound": "查询合思系统出站消息规则与投递日志 (list|logs)" }, + "options": [ "--flow=<单号> 指定测试单据", "--file= 指定工作流快照", @@ -333,9 +335,13 @@ export const COMMAND_METADATA: Record = { "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": "单据检索、表单规格诊断与审批动作", diff --git a/src/cli/commands/workflow/index.ts b/src/cli/commands/workflow/index.ts index c033895..d02bd78 100644 --- a/src/cli/commands/workflow/index.ts +++ b/src/cli/commands/workflow/index.ts @@ -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, }; + } } diff --git a/src/cli/commands/workflow/outbound.test.ts b/src/cli/commands/workflow/outbound.test.ts new file mode 100644 index 0000000..b05c436 --- /dev/null +++ b/src/cli/commands/workflow/outbound.test.ts @@ -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("未选中企业"); + }); +}); + + diff --git a/src/cli/commands/workflow/outbound.ts b/src/cli/commands/workflow/outbound.ts new file mode 100644 index 0000000..0cb2e15 --- /dev/null +++ b/src/cli/commands/workflow/outbound.ts @@ -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 { + 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, + }; +} diff --git a/src/domains/platform/workflow/services.ts b/src/domains/platform/workflow/services.ts index 2dced12..b8f5195 100644 --- a/src/domains/platform/workflow/services.ts +++ b/src/domains/platform/workflow/services.ts @@ -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"; + diff --git a/src/domains/platform/workflow/transport/outbound/api.ts b/src/domains/platform/workflow/transport/outbound/api.ts new file mode 100644 index 0000000..7c1ad3b --- /dev/null +++ b/src/domains/platform/workflow/transport/outbound/api.ts @@ -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 { + 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 = { + 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 ?? [], + }; +} diff --git a/src/domains/platform/workflow/transport/outbound/index.ts b/src/domains/platform/workflow/transport/outbound/index.ts new file mode 100644 index 0000000..a7b74f7 --- /dev/null +++ b/src/domains/platform/workflow/transport/outbound/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/src/domains/platform/workflow/transport/outbound/types.ts b/src/domains/platform/workflow/transport/outbound/types.ts new file mode 100644 index 0000000..80f269d --- /dev/null +++ b/src/domains/platform/workflow/transport/outbound/types.ts @@ -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; +}