feat(platform): support native server filterBy, workflow compact list and auto-corp credentials
This commit is contained in:
1 parent
deed5a5628
commit
975f76af74
10 files changed
+483
-28
No files matched your search
@@ -3,6 +3,7 @@ import { parseHeadersOrCurl } from "../../core/auth/login.js";
|
||||
import { resolveCorpCluster } from "../../core/http/unity-client.js";
|
||||
import { handleCorpsCommand } from "./corps/index.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
describe("core/auth/login > parseHeadersOrCurl & URL link parsing", () => {
|
||||
it("successfully parses standard thirdparty.html assistance links", () => {
|
||||
@@ -418,4 +419,86 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("通过 OpenAPI 持久化密钥接入企业");
|
||||
});
|
||||
|
||||
it("supports corps hose-staffs with auto-resolved corp credentials", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
try {
|
||||
globalThis.fetch = (async (input: unknown) => {
|
||||
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as { url: string }).url;
|
||||
if (urlStr.includes("/api/openapi/v1/auth/getAccessToken")) {
|
||||
return new Response(JSON.stringify({
|
||||
value: {
|
||||
accessToken: "mock-open-token",
|
||||
corporationId: "corpKeyed",
|
||||
corporation: { id: "corpKeyed", name: "已配密钥企业" },
|
||||
},
|
||||
}), { status: 200 });
|
||||
}
|
||||
if (urlStr.includes("/api/openapi/v1/roleDefGroups")) {
|
||||
return new Response(JSON.stringify({
|
||||
items: [
|
||||
{
|
||||
id: "g1",
|
||||
name: "默认组",
|
||||
roleDefs: [
|
||||
{ id: "corpKeyed:admin", name: "主管理员" },
|
||||
],
|
||||
},
|
||||
],
|
||||
}), { status: 200 });
|
||||
}
|
||||
if (urlStr.includes("/api/openapi/v1/roledefs/")) {
|
||||
return new Response(JSON.stringify({
|
||||
value: {
|
||||
id: "corpKeyed:admin",
|
||||
name: "主管理员",
|
||||
count: 1,
|
||||
contents: [{ staffs: ["corpKeyed:staff1"] }],
|
||||
},
|
||||
}), { status: 200 });
|
||||
}
|
||||
if (urlStr.includes("/api/openapi/v1/staffs/getStaffIds")) {
|
||||
return new Response(JSON.stringify({
|
||||
items: [
|
||||
{ id: "corpKeyed:staff1", name: "测试管理员", code: "001", active: true },
|
||||
],
|
||||
}), { status: 200 });
|
||||
}
|
||||
return new Response(JSON.stringify({}), { status: 200 });
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const corpWithKeys: CorpConfig = {
|
||||
id: "corpKeyed",
|
||||
name: "已配密钥企业",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "openapi",
|
||||
credentials: {
|
||||
accessToken: "token-x",
|
||||
corpId: "corpKeyed",
|
||||
staffId: "corpKeyed:STAFF",
|
||||
appKey: "my-key-123",
|
||||
appSecurity: "my-sec-456",
|
||||
},
|
||||
};
|
||||
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "hose-staffs",
|
||||
args: [],
|
||||
options: { role: "admin", json: true },
|
||||
raw: ["corps", "hose-staffs", "--role=admin", "--json"],
|
||||
},
|
||||
{ ...searchRuntime, selectedCorp: corpWithKeys, jsonMode: true }
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.roleName).toBe("主管理员");
|
||||
expect(data.staffs).toHaveLength(1);
|
||||
expect(data.staffs[0].name).toBe("测试管理员");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -43,15 +43,21 @@ export async function handleProbeHose(parsed: CliParsedArgs, runtime: CliRuntime
|
||||
}
|
||||
|
||||
export async function handleHoseStaffs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
|
||||
const domain = stringOption(parsed.options, ["domain", "base-url"]);
|
||||
let appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
let appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
|
||||
let domain = stringOption(parsed.options, ["domain", "base-url"]);
|
||||
const role = stringOption(parsed.options, ["role", "roleDefId"]);
|
||||
|
||||
if ((!appKey || !appSecurity) && runtime.selectedCorp?.credentials?.appKey && runtime.selectedCorp?.credentials?.appSecurity) {
|
||||
appKey = runtime.selectedCorp.credentials.appKey;
|
||||
appSecurity = runtime.selectedCorp.credentials.appSecurity;
|
||||
domain = domain || runtime.selectedCorp.baseUrl;
|
||||
}
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps hose-staffs --app-key=<key> --app-security=<secret> [--role=admin]\n",
|
||||
stderr: "用法: hose-use corps hose-staffs [--corp=<id>] [--app-key=<key> --app-security=<secret>] [--role=admin]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
auditEntityRecords,
|
||||
auditLedgerContinuityAndBaseline,
|
||||
buildKeywordFilter,
|
||||
buildServerFieldFilter,
|
||||
calculateEntityRecordStats,
|
||||
fetchAllEntityRecords,
|
||||
compileRecordPredicate,
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
searchEntityRecords,
|
||||
selectRecordFields,
|
||||
} from "../../../domains/datalink/services.js";
|
||||
import type { DatalinkRecord } from "../../../domains/datalink/types.js";
|
||||
import type { LedgerContinuityReport } from "../../../domains/datalink/types.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue, redactSensitiveText } from "../../printer.js";
|
||||
@@ -32,7 +34,17 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
|
||||
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
|
||||
const searchFields = splitFields(
|
||||
stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "searchField"])
|
||||
);
|
||||
const rawFilter = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]);
|
||||
let filterBy: string | undefined;
|
||||
if (rawFilter) {
|
||||
filterBy = buildServerFieldFilter(rawFilter, resolved.entity);
|
||||
} else if (keyword) {
|
||||
filterBy = buildKeywordFilter(keyword, { entity: resolved.entity, searchFields });
|
||||
}
|
||||
|
||||
const whereClause = stringOption(parsed.options, ["where"]);
|
||||
const predicate = whereClause ? compileRecordPredicate(whereClause, resolved.entity) : undefined;
|
||||
const sumOption = stringOption(parsed.options, ["sum", "aggregate"]);
|
||||
@@ -41,7 +53,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
const isFlat = booleanOption(parsed.options, ["flat", "normalize", "normalized"], false);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const groupBy = stringOption(parsed.options, ["group-by", "groupBy"]);
|
||||
const fetchAll = isAll || Boolean(whereClause || sumOption || isProfileStats);
|
||||
const fetchAll = isAll || Boolean(sumOption || isProfileStats);
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
||||
const count = numberOption(parsed.options, ["count", "limit"], 20);
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||
@@ -125,12 +137,36 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const page = fetchAll
|
||||
? await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize })
|
||||
: await searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
let data: DatalinkRecord[] = [];
|
||||
let total = 0;
|
||||
|
||||
let data = page.data;
|
||||
if (predicate) data = data.filter(predicate);
|
||||
if (fetchAll) {
|
||||
const page = await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize });
|
||||
total = page.total;
|
||||
data = page.data;
|
||||
if (predicate) data = data.filter(predicate);
|
||||
} else if (predicate) {
|
||||
// 客户端谓词早退机制:一旦匹配到 count 条记录,立即停止拉取后续页面,杜绝无限制全量扫描
|
||||
let matched = 0;
|
||||
const targetLimit = count ?? 20;
|
||||
for await (const record of iterateAllEntityRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity.id,
|
||||
{ filterBy, pageSize }
|
||||
)) {
|
||||
total++;
|
||||
if (predicate(record)) {
|
||||
data.push(record);
|
||||
matched++;
|
||||
if (matched >= targetLimit) break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const page = await searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
total = page.total;
|
||||
data = page.data;
|
||||
}
|
||||
|
||||
// 3. 数学聚合核算模式 (--sum="租赁费用,日折旧费")
|
||||
if (sumOption) {
|
||||
@@ -191,7 +227,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
platform: resolved.platform,
|
||||
entity: resolved.entity,
|
||||
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, where: whereClause, fields, flat: isFlat },
|
||||
total: page.total,
|
||||
total: total || data.length,
|
||||
returned: data.length,
|
||||
data,
|
||||
};
|
||||
@@ -209,7 +245,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
const formattedTime = typeof updateTime === "number" ? new Date(updateTime).toLocaleString("zh-CN", { hour12: false }) : cell(updateTime);
|
||||
return [i + 1, cell(id), cell(nameVal), cell(codeVal), active === false ? "停用" : "启用", formattedTime];
|
||||
});
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${total || data.length}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||
import * as helpers from "../helpers.js";
|
||||
import * as platformServices from "../../domains/platform/services.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
@@ -2169,3 +2170,127 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("CLI - workflow list 轻量化与名称搜索", () => {
|
||||
let spies: ReturnType<typeof spyOn>[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const spy of spies) {
|
||||
spy.mockRestore();
|
||||
}
|
||||
spies = [];
|
||||
});
|
||||
|
||||
const mockWorkflows = [
|
||||
{
|
||||
id: "wf_001",
|
||||
pipelineName: "待摊台账拆分计划",
|
||||
state: 1,
|
||||
runningCount: 0,
|
||||
errorCount: 0,
|
||||
updateTime: "2026-08-26 23:31:04",
|
||||
updateUser: "张三",
|
||||
platformId: "p_1",
|
||||
platformName: "合同台账",
|
||||
tasks: [
|
||||
{ name: "t1", type: "trigger", code: "long script 1..." },
|
||||
{ name: "t2", type: "code", code: "long script 2..." },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "wf_002",
|
||||
pipelineName: "费用报销审批同步",
|
||||
state: 0,
|
||||
runningCount: 0,
|
||||
errorCount: 0,
|
||||
updateTime: "2026-09-01 10:00:00",
|
||||
updateUser: "李四",
|
||||
platformId: "p_2",
|
||||
platformName: "费用应用",
|
||||
tasks: [{ name: "t1", type: "trigger", code: "long script 3..." }],
|
||||
},
|
||||
];
|
||||
|
||||
it("默认以轻量化模式输出 JSON,剥离庞大的 tasks 数组并提供 nodeCount", async () => {
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({} as any),
|
||||
spyOn(platformServices, "listAllWorkflows").mockResolvedValue({
|
||||
workflows: mockWorkflows as any,
|
||||
errors: [],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { json: true },
|
||||
raw: ["workflow", "list", "--json"],
|
||||
},
|
||||
{ ...mockRuntime, jsonMode: true }
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.workflows).toHaveLength(2);
|
||||
expect(data.workflows[0].tasks).toBeUndefined();
|
||||
expect(data.workflows[0].nodeCount).toBe(2);
|
||||
expect(data.workflows[1].nodeCount).toBe(1);
|
||||
expect(data.totalWorkflows).toBe(2);
|
||||
});
|
||||
|
||||
it("传入 --full 或 --with-tasks 时保留完整的 tasks 节点结构", async () => {
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({} as any),
|
||||
spyOn(platformServices, "listAllWorkflows").mockResolvedValue({
|
||||
workflows: mockWorkflows as any,
|
||||
errors: [],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { json: true, full: true },
|
||||
raw: ["workflow", "list", "--json", "--full"],
|
||||
},
|
||||
{ ...mockRuntime, jsonMode: true }
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.workflows[0].tasks).toHaveLength(2);
|
||||
expect(data.workflows[0].tasks[0].code).toBe("long script 1...");
|
||||
});
|
||||
|
||||
it("支持通过 --keyword 或 -q 过滤工作流名称", async () => {
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({} as any),
|
||||
spyOn(platformServices, "listAllWorkflows").mockResolvedValue({
|
||||
workflows: mockWorkflows as any,
|
||||
errors: [],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { keyword: "待摊", json: true },
|
||||
raw: ["workflow", "list", "--keyword=待摊", "--json"],
|
||||
},
|
||||
{ ...mockRuntime, jsonMode: true }
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.workflows).toHaveLength(1);
|
||||
expect(data.workflows[0].id).toBe("wf_001");
|
||||
expect(data.workflows[0].pipelineName).toBe("待摊台账拆分计划");
|
||||
expect(data.totalWorkflows).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,36 +14,62 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["pageSize", "size"]) || 50;
|
||||
const filterPlatformId = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
const isFull = booleanOption(parsed.options, ["full", "with-tasks", "withTasks"], false);
|
||||
|
||||
const rawResult = await listAllWorkflows(clients, { page, pageSize });
|
||||
const workflows = filterPlatformId
|
||||
let workflows = filterPlatformId
|
||||
? rawResult.workflows.filter(
|
||||
(wf) => wf.platformId === filterPlatformId || wf.platformName === filterPlatformId
|
||||
)
|
||||
: rawResult.workflows;
|
||||
const result = filterPlatformId
|
||||
? { ...rawResult, workflows, totalWorkflows: workflows.length }
|
||||
: rawResult;
|
||||
|
||||
if (keyword) {
|
||||
const kw = keyword.toLowerCase();
|
||||
workflows = workflows.filter(
|
||||
(wf) =>
|
||||
wf.pipelineName.toLowerCase().includes(kw) ||
|
||||
wf.id.toLowerCase().includes(kw) ||
|
||||
Boolean(wf.platformName && wf.platformName.toLowerCase().includes(kw))
|
||||
);
|
||||
}
|
||||
|
||||
// 默认轻量化模式:列表态剥离庞大的 tasks 节点树与代码脚本,只输出核心元数据和节点数统计
|
||||
const outputWorkflows = isFull
|
||||
? workflows
|
||||
: workflows.map(({ tasks, ...rest }) => ({
|
||||
...rest,
|
||||
nodeCount: tasks?.length ?? 0,
|
||||
}));
|
||||
|
||||
const result = {
|
||||
...rawResult,
|
||||
workflows: outputWorkflows,
|
||||
totalWorkflows: workflows.length,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (result.workflows.length === 0) {
|
||||
if (workflows.length === 0) {
|
||||
const emptyMsg = keyword
|
||||
? `企业 [${runtime.selectedCorp!.name}] 下未找到包含关键词 "${keyword}" 的工作流\n`
|
||||
: `企业 [${runtime.selectedCorp!.name}] 下暂无工作流\n`;
|
||||
return {
|
||||
stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无工作流\n`,
|
||||
stdout: emptyMsg,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = result.workflows.map((wf, i) => [
|
||||
const rows = workflows.map((wf, i) => [
|
||||
i + 1,
|
||||
wf.id,
|
||||
wf.pipelineName,
|
||||
wf.platformName || wf.platformId || "-",
|
||||
wf.state === 1 ? "🟢 启用" : "⚪ 停用",
|
||||
wf.tasks?.length ?? "-",
|
||||
wf.tasks?.length ?? (wf as any).nodeCount ?? "-",
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
@@ -51,8 +77,15 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
rows
|
||||
);
|
||||
|
||||
const filterDesc = [
|
||||
filterPlatformId ? `应用: ${filterPlatformId}` : "",
|
||||
keyword ? `关键词: "${keyword}"` : "",
|
||||
].filter(Boolean).join(", ");
|
||||
|
||||
const titleSuffix = filterDesc ? ` (过滤: ${filterDesc}, 共 ${workflows.length} 条)` : ` (共 ${workflows.length} 条)`;
|
||||
|
||||
return {
|
||||
stdout: `====== [${runtime.selectedCorp!.name}] 工作流列表 (共 ${result.workflows.length} 条) ======\n${table}\n`,
|
||||
stdout: `====== [${runtime.selectedCorp!.name}] 工作流列表${titleSuffix} ======\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user