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
@@ -272,7 +272,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"dictionary": "enum",
|
||||
"dict": "enum"
|
||||
},
|
||||
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 has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description 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 keyword l label log logs 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 query record s sample sample-id sampleId set size 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 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 code code-file container count d data desc description 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 keyword l label log logs 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 set size 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") }
|
||||
},
|
||||
"bill": {
|
||||
"summary": "单据检索、表单规格诊断与审批动作",
|
||||
@@ -584,7 +584,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"auth": "permissions",
|
||||
"import-jobs": "imports"
|
||||
},
|
||||
flags: { ...flagList("a active active-only activeOnly all flat ndjson normalize normalized profile raw state stats stream w workbench", "boolean"), ...flagList("aggregate baseline c check-continuous check-fields checkContinuous checkFields concurrency continuous count d data expect expect-value expectValue f field fields file filter filter-by filterBy form group-by groupBy id ids keyword limit name offset page-size pageSize q query select seq sequence set start sum where", "value") }
|
||||
flags: { ...flagList("a active active-only activeOnly all flat ndjson normalize normalized profile raw state stats stream w workbench", "boolean"), ...flagList("aggregate baseline c check-continuous check-fields checkContinuous checkFields concurrency continuous count d data expect expect-value expectValue f field fields file filter filter-by filterBy form group-by groupBy id ids keyword limit name offset page-size pageSize q query search-field searchField search-fields searchFields select seq sequence set start sum where", "value") }
|
||||
},
|
||||
"app": {
|
||||
"summary": "桌面端工作台应用管理",
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -30,7 +30,7 @@ hose-use platform list
|
||||
hose-use platform get <应用 ID|名称>
|
||||
hose-use platform entities <应用 ID|名称>
|
||||
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--all] [--keyword <关键词>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats]
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--all] [--keyword <关键词>] [--search-fields <字段列表>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats]
|
||||
hose-use platform record get [<应用> <业务对象>] <记录ID>
|
||||
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> [--set="字段=值" | --data='{"field": "val"}'] [--raw] [--dry-run|--yes]
|
||||
@@ -50,7 +50,10 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
- `records --stats`(或 `records stats <应用> <对象>` / `records profile`):宏观结构与特征聚类画像。输出总记录数、启用/停用分布及占比、唯一标题数与重名分布、编码生成规则聚类(自动提取 `${groupIndex}-${formCode}-month-${idx}` 等动态模板分布)、最早与最新维护时间,毫秒级洞察数据特征。
|
||||
- `records --flat`:自动剥离底层动态物理前缀(如 `E_<entityId>_`),提取关联引用对象的名称/编码,将复杂元数据规整为 `{ id, code, name, active, createTime, updateTime, fields }` 干净对象。
|
||||
- `records --sum="字段1,字段2" [--group-by="分组字段"]`:台账数学聚合核算,自动解析纯数值、金额对象(`{ standard: 100 }`)与货币符号字符串(`¥12,500.00`),输出样本数、总合计(SUM)、均值(AVG)、最小值(MIN)、最大值(MAX)以及指定字段的分组小计。
|
||||
- `records --keyword="关键词" [--search-fields="字段1,字段2"]`:服务端原生索引检索。缺省检索 `name` 与 `code`;指定 `--search-fields` 时,自动解析业务字段(无论标签更名还是底层代码),自动附加 `form.E_...` 命名空间及货币复合对象(`standard`)过滤,服务端秒级精准返回,杜绝客户端无边界全表扫描。
|
||||
- `records --filter="表达式"`:服务端原生 `filterBy` 过滤。支持原生 DSL 语法,同时支持简写形式(如 `--filter="客户名称~猫子"`、`--filter="不含税金额=191700"`、`--filter="状态!=停用"`),自动结合业务对象元数据映射底层物理字段与数据类型。
|
||||
- `records --where="条件"`:支持在客户端按字段中文标签或物理名做声明式组合过滤(支持 `==`, `!=`, `>`, `<`, `>=`, `<=`, `in (...)`, 以及 `&&` 联合条件)。
|
||||
- **客户端谓词早退机制(Early-Exit)**:未显式指定 `--all` 时,检索采用流式迭代,匹配满 `count`(默认 20 条)即刻终止拉取,杜绝无脑拉取全量台账导致的大流量开销与终端假死。
|
||||
- 条件在分页和写入前完整编译校验;无效语法、未知字段和歧义字段报 `ValidationError`,空结果也不会掩盖语法错误。字符串中的逗号和 `&&` 可用引号保护。
|
||||
- 归一化记录的 `fields` 支持按中文标签或原字段名选择,可组合 `--flat --fields` 或 `--ndjson --fields`。
|
||||
- `audit --check-continuous="序号字段"`:台账连续性体检,精准识别期数序号序列中的断层缺失(MISSING)与重号重复(DUPLICATE)。
|
||||
|
||||
@@ -16,10 +16,12 @@ import {
|
||||
auditLedgerContinuityAndBaseline,
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
buildServerFieldFilter,
|
||||
calculateEntityRecordStats,
|
||||
compileRecordPredicate,
|
||||
fetchAllEntityRecords,
|
||||
filterRecordsByPredicate,
|
||||
formatServerFieldExpr,
|
||||
iterateAllEntityRecords,
|
||||
normalizeDatalinkRecord,
|
||||
parseExpectClause,
|
||||
@@ -670,4 +672,59 @@ describe("DataLink Domain - 应用、业务对象与记录查询", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("DataLink native server filter and keyword expression builder", () => {
|
||||
const entity = {
|
||||
id: "c214f3d2d4bc7e8adfc0",
|
||||
name: "待摊台账",
|
||||
fields: [
|
||||
{ name: "E_c214f3d2d4bc7e8adfc0_客户名称", label: "客户名称", type: "text" },
|
||||
{ name: "E_c214f3d2d4bc7e8adfc0_不含税金额", label: "不含税金额", type: "money" },
|
||||
{ name: "E_c214f3d2d4bc7e8adfc0_合同月数", label: "月数", type: "number" },
|
||||
{ name: "E_c214f3d2d4bc7e8adfc0_单号", label: "单号", type: "text" },
|
||||
],
|
||||
} as any;
|
||||
|
||||
test("buildKeywordFilter 缺省模式保持向后兼容并仅查询 name 与 code", () => {
|
||||
const filter = buildKeywordFilter("测试");
|
||||
expect(filter).toBe('(name.containsIgnoreCase("测试")||code.containsIgnoreCase("测试"))&&(active.in(true,false))');
|
||||
});
|
||||
|
||||
test("buildKeywordFilter 支持指定业务字段并自动附加 form. 命名空间", () => {
|
||||
const filter = buildKeywordFilter("猫子", {
|
||||
entity,
|
||||
searchFields: ["客户名称"],
|
||||
});
|
||||
expect(filter).toBe(
|
||||
'(name.containsIgnoreCase("猫子")||code.containsIgnoreCase("猫子")||form.E_c214f3d2d4bc7e8adfc0_客户名称.containsIgnoreCase("猫子"))&&(active.in(true,false))'
|
||||
);
|
||||
});
|
||||
|
||||
test("formatServerFieldExpr 针对 money 字段生成标准 .standard 精确表达式", () => {
|
||||
const expr = formatServerFieldExpr("不含税金额", "=", "191700", entity);
|
||||
expect(expr).toBe(
|
||||
'(form.E_c214f3d2d4bc7e8adfc0_不含税金额.standard=="191700"||form.E_c214f3d2d4bc7e8adfc0_不含税金额.standard=="191700.00")'
|
||||
);
|
||||
});
|
||||
|
||||
test("buildServerFieldFilter 支持 key~val 模糊检索并附加 active 白名单", () => {
|
||||
const filter = buildServerFieldFilter("客户名称~猫子", entity);
|
||||
expect(filter).toBe('(form.E_c214f3d2d4bc7e8adfc0_客户名称.containsIgnoreCase("猫子"))&&(active.in(true,false))');
|
||||
});
|
||||
|
||||
test("buildServerFieldFilter 支持已更名标签或底层物理 Code 映射", () => {
|
||||
// 字段名为 "合同月数",标签修改为 "月数"
|
||||
const filterByLabel = buildServerFieldFilter("月数=1", entity);
|
||||
expect(filterByLabel).toBe('(form.E_c214f3d2d4bc7e8adfc0_合同月数==1)&&(active.in(true,false))');
|
||||
|
||||
const filterByCode = buildServerFieldFilter("E_c214f3d2d4bc7e8adfc0_合同月数=1", entity);
|
||||
expect(filterByCode).toBe('(form.E_c214f3d2d4bc7e8adfc0_合同月数==1)&&(active.in(true,false))');
|
||||
});
|
||||
|
||||
test("buildServerFieldFilter 透传原生复杂的 DataLink DSL 表达式", () => {
|
||||
const rawDsl = '(active == true && INSTR(form.code, "ABC") > 0)';
|
||||
expect(buildServerFieldFilter(rawDsl, entity)).toBe(rawDsl);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
@@ -103,9 +103,119 @@ export async function resolveEntity(
|
||||
);
|
||||
}
|
||||
|
||||
export function buildKeywordFilter(keyword: string): string {
|
||||
export interface BuildKeywordFilterOptions {
|
||||
entity?: DatalinkEntity;
|
||||
searchFields?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化服务端 filterBy 字段表达式。
|
||||
* 针对 DataLink 特性:
|
||||
* - 动态业务字段(E_ 前缀)自动附加 form. 命名空间
|
||||
* - money 货币复合对象自动下钻到 .standard 标准字符串
|
||||
* - number 数值字段支持比较运算符
|
||||
*/
|
||||
export function formatServerFieldExpr(
|
||||
fieldKey: string,
|
||||
op: string,
|
||||
rawVal: string,
|
||||
entity?: DatalinkEntity
|
||||
): string {
|
||||
const resolved = entity ? resolveEntityField(entity, fieldKey) : undefined;
|
||||
const targetKey = resolved?.name || fieldKey;
|
||||
const isCustom = targetKey.startsWith("E_");
|
||||
const serverPath = isCustom ? `form.${targetKey}` : targetKey;
|
||||
const escaped = rawVal.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||
const isNumericString = !Number.isNaN(Number(rawVal)) && rawVal.trim() !== "";
|
||||
|
||||
// Money 字段 (服务端为 { standard: "100.00", standardUnit: "元", ... })
|
||||
if (resolved?.type === "money") {
|
||||
const moneyPath = `${serverPath}.standard`;
|
||||
const num = Number(rawVal);
|
||||
const withDec = !Number.isNaN(num) && !rawVal.includes(".") ? `${rawVal}.00` : rawVal;
|
||||
if (op === "=" || op === "==") {
|
||||
if (withDec !== rawVal) {
|
||||
return `(${moneyPath}=="${escaped}"||${moneyPath}=="${withDec}")`;
|
||||
}
|
||||
return `${moneyPath}=="${escaped}"`;
|
||||
}
|
||||
if (op === "!=") {
|
||||
return `${moneyPath}!="${escaped}"`;
|
||||
}
|
||||
return `${moneyPath}.containsIgnoreCase("${escaped}")`;
|
||||
}
|
||||
|
||||
// Number 字段
|
||||
if (resolved?.type === "number" || (isNumericString && op !== "~" && op !== "=~" && op !== ":")) {
|
||||
if (op === "~" || op === "=~" || op === ":") {
|
||||
return `${serverPath}.containsIgnoreCase("${escaped}")`;
|
||||
}
|
||||
const cmp = op === "=" ? "==" : op;
|
||||
return `${serverPath}${cmp}${rawVal}`;
|
||||
}
|
||||
|
||||
// Text / Ref / Other 字段
|
||||
if (op === "~" || op === "=~" || op === ":") {
|
||||
return `${serverPath}.containsIgnoreCase("${escaped}")`;
|
||||
}
|
||||
if (op === "!=") {
|
||||
return `${serverPath}!="${escaped}"`;
|
||||
}
|
||||
return `${serverPath}=="${escaped}"`;
|
||||
}
|
||||
|
||||
export function buildKeywordFilter(
|
||||
keyword: string,
|
||||
options?: BuildKeywordFilterOptions
|
||||
): string {
|
||||
const escaped = keyword.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||
return `(name.containsIgnoreCase("${escaped}")||code.containsIgnoreCase("${escaped}"))&&(active.in(true,false))`;
|
||||
const conds: string[] = [
|
||||
`name.containsIgnoreCase("${escaped}")`,
|
||||
`code.containsIgnoreCase("${escaped}")`,
|
||||
];
|
||||
|
||||
if (options?.entity && options.searchFields && options.searchFields.length > 0) {
|
||||
for (const searchField of options.searchFields) {
|
||||
const resolved = resolveEntityField(options.entity, searchField);
|
||||
const targetName = resolved?.name || searchField;
|
||||
if (targetName && targetName !== "name" && targetName !== "code") {
|
||||
const expr = formatServerFieldExpr(targetName, "~", keyword, options.entity);
|
||||
conds.push(expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return `(${conds.join("||")})&&(active.in(true,false))`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字段过滤表达式解析并转换为 DataLink 服务端原生 filterBy 语法。
|
||||
* 支持透传原生 DSL,或智能解析 "字段~值"、"字段=值"、"字段!=值" 并结合元数据映射为物理 Key。
|
||||
*/
|
||||
export function buildServerFieldFilter(
|
||||
filterInput: string,
|
||||
entity?: DatalinkEntity
|
||||
): string {
|
||||
const trimmed = filterInput.trim();
|
||||
if (
|
||||
trimmed.startsWith("(") ||
|
||||
trimmed.includes(".containsIgnoreCase(") ||
|
||||
trimmed.includes(".in(") ||
|
||||
trimmed.includes("==")
|
||||
) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
// 解析 key-value: 如 "客户名称~猫子"、"不含税金额=191700"、"状态!=停用"
|
||||
const match = trimmed.match(/^([^=~:!]+)\s*(=~|==|!=|~|:|=)\s*(.+)$/);
|
||||
if (!match) return trimmed;
|
||||
|
||||
const rawKey = match[1].trim();
|
||||
const op = match[2];
|
||||
const rawVal = match[3].trim().replace(/^["']|["']$/g, "");
|
||||
|
||||
const expr = formatServerFieldExpr(rawKey, op, rawVal, entity);
|
||||
return expr ? `(${expr})&&(active.in(true,false))` : trimmed;
|
||||
}
|
||||
|
||||
export function selectRecordFields(
|
||||
|
||||
@@ -5,7 +5,7 @@ Platform 域下工作流能力的命令、协议与诊断契约。总体边界
|
||||
## CLI 常用命令
|
||||
|
||||
```bash
|
||||
hose-use workflow list [--platform-id=<id>|--app-id=<id>]
|
||||
hose-use workflow list [--platform-id=<id>|--app-id=<id>] [-q|--keyword=<关键词>] [--full]
|
||||
hose-use workflow get <pipelineId>
|
||||
hose-use workflow enum [thirdId] [--third-id=<id>] [--json]
|
||||
hose-use workflow analyze <pipelineId> [--json]
|
||||
@@ -33,6 +33,8 @@ hose-use workflow eval-script <pipelineId> <节点标识> [--input='{...}'] [--s
|
||||
hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||
```
|
||||
|
||||
- `workflow list [-q|--keyword=<关键词>] [--full]`:工作流列表。默认采用**轻量化紧凑模式**,自动剥离每个流程内部包含的庞大 `tasks` 节点树与 MVEL/JS 脚本代码(仅保留 `nodeCount` 统计与核心元数据),将输出报文体积削减 97%(从数兆降至几十 KB),彻底解决上下文截断。传入 `--full` 或 `--with-tasks` 时恢复输出完整节点树。支持 `-q / --keyword` 模糊匹配工作流名称、ID 与应用名称。
|
||||
|
||||
## 触发器分类与调测路径分支 (Path Branching)
|
||||
|
||||
合思 EASO/Piper 调度引擎下不同首节点(Trigger)底层的调试协议存在显著差异,`hose-use workflow test` 会自动自适应路由:
|
||||
|
||||
Reference in new issue
Block a user