feat(platform,datalink,bill): add workflow job drilldown, safe record batch-edit, audit, and spec linkage diagnostics (v0.8.11)

This commit is contained in:
gitea committed 2026-09-29 20:00:55 +08:00
1 parent 2ec08033e0
commit a0ec7f95a7
37 files changed
+3958 -674

No files matched your search

+464 -31
View File
@@ -1,8 +1,18 @@
import { readFileSync } from "node:fs";
import * as api from "../../domains/datalink/api.js";
import { buildKeywordFilter, resolveEntity, resolvePlatform, selectRecordFields } from "../../domains/datalink/services.js";
import {
auditEntityRecords,
batchSafeEditRecords,
buildKeywordFilter,
fetchAllEntityRecords,
resolveEntity,
resolvePlatform,
selectRecordFields,
type BatchEditTargetItem,
} from "../../domains/datalink/services.js";
import { createClientsForCorp } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import { printJson, printKeyValue, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
@@ -61,10 +71,15 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
case "records":
case "data":
case "search": return handleRecords(parsed, runtime);
case "audit":
case "check":
case "health": return handleAudit(parsed, runtime);
case "record":
case "record-get":
case "record-toggle":
case "record-edit":
case "record-batch-edit":
case "batch-edit":
case "record-recompute": return handleRecordAction(parsed, runtime);
case "permissions":
case "permission":
@@ -72,7 +87,7 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
case "imports":
case "import-jobs": return handleImports(parsed, runtime);
default:
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, record, permissions, imports\n`, exitCode: 1 };
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, audit, record, permissions, imports\n`, exitCode: 1 };
}
}
@@ -126,12 +141,23 @@ async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promis
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 fetchAll = booleanOption(parsed.options, ["all", "a"], false);
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);
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
const page = await api.searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
const page = fetchAll
? await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize })
: await api.searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
const data = fields.length ? page.data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields)) : page.data;
const result = { platform: resolved.platform, entity: resolved.entity, query: { start, count, filterBy, fields }, total: page.total, returned: data.length, data };
const result = {
platform: resolved.platform,
entity: resolved.entity,
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, fields },
total: page.total,
returned: data.length,
data,
};
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
@@ -145,7 +171,89 @@ async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promis
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}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
}
async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const resolved = await resolveAppAndEntity(parsed, runtime);
if (!resolved.entity) {
throw new Error("请提供业务对象 ID、编码或名称: hose-use platform audit <应用> <业务对象> [--check-fields=字段1,字段2] [--active-only]");
}
const checkFields = splitFields(stringOption(parsed.options, ["check-fields", "checkFields", "fields"]));
const activeOnly = booleanOption(parsed.options, ["active-only", "activeOnly"], false);
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (activeOnly ? "(active==true)" : undefined);
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
const page = await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, {
filterBy,
pageSize,
});
const report = auditEntityRecords(page.data, resolved.entity, {
checkFields,
activeOnly,
total: page.total,
});
const output = {
platform: { id: resolved.platform.id, name: resolved.platform.name, code: resolved.platform.code },
entity: { id: resolved.entity.id, name: resolved.entity.name, code: resolved.entity.code },
...report,
};
if (runtime.jsonMode) {
return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const issueRows = report.issues.map((issue, idx) => [
idx + 1,
issue.recordId,
issue.recordCode || "-",
issue.recordName || "-",
issue.active ? "🟢 启用" : "🔴 停用",
issue.type,
issue.fieldLabel,
issue.message,
]);
const patchRows = report.suggestedPatches.map((patch, idx) => [
idx + 1,
patch.id,
patch.code || "-",
patch.name || "-",
JSON.stringify(patch.form),
patch.reason,
]);
const outLines = [
`====== 台账数据健康度体检: [${resolved.platform.name}] ${resolved.entity.name} (${resolved.entity.id}) ======`,
printKeyValue({
"总记录数": report.totalRecords,
"本次体检记录数": report.auditedRecords,
"健康记录数": report.healthyRecords,
"异常记录数": report.affectedRecordCount,
"总问题项数": report.issueCount,
"关键字段缺失 (MISSING_FIELD)": report.summary.missingFieldCount,
"引用对象已停用 (DISABLED_REFERENCE)": report.summary.disabledReferenceCount,
"跨表同名维度待回填 (CROSS_LEDGER_MISSING_SYNC)": report.summary.crossLedgerMissingSyncCount,
"跨表同名维度不一致 (CROSS_LEDGER_MISMATCH)": report.summary.crossLedgerMismatchCount,
}),
"",
"── 异常诊断明细 ──",
issueRows.length
? printTable(["#", "记录 ID", "编码", "名称", "状态", "问题类型", "字段", "详细说明"], issueRows)
: "✅ 未发现任何字段缺失、停用引用或跨表维度不一致问题",
];
if (patchRows.length > 0) {
outLines.push("");
outLines.push(`── 💡 建议自动回填修复清单 (共 ${patchRows.length} 条记录,可通过 platform record batch-edit 执行) ──`);
outLines.push(printTable(["#", "记录 ID", "编码", "名称", "建议 Patch Form", "依据"], patchRows));
}
return {
stdout: `${outLines.join("\n")}\n`,
stderr: "",
exitCode: 0,
};
}
async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
@@ -170,6 +278,291 @@ async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime): Promis
return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 };
}
function formatDirectRecordFieldValue(val: unknown): string {
if (val === undefined || val === null || val === "") return "";
if (typeof val === "object" && !Array.isArray(val)) {
const obj = val as Record<string, unknown>;
if ("standard" in obj) {
return `${obj.standard} ${obj.standardStrCode || obj.standardUnit || "CNY"}`;
}
const nestedDl =
obj.data && typeof obj.data === "object" && (obj.data as Record<string, unknown>).dataLink
? ((obj.data as Record<string, unknown>).dataLink as Record<string, unknown>)
: undefined;
if (nestedDl && typeof nestedDl === "object") {
const eId = String(nestedDl.entityId || "");
const title =
nestedDl[`E_${eId}_name`] ?? nestedDl.name ?? nestedDl[`E_${eId}_code`] ?? nestedDl.code ?? "";
return `${obj.id || nestedDl.id}${title ? ` (${title})` : ""}`;
}
if (typeof obj.id === "string" && (obj.name || obj.code)) {
return `${obj.name || obj.code} (${obj.id})`;
}
}
return cell(val);
}
async function handleDirectRecordGet(
recordId: string,
runtime: CliRuntime
): Promise<CliResult> {
const clients = await createClientsForCorp(runtime.selectedCorp!);
const corpId = runtime.selectedCorp!.credentials.corpId;
const detail = await api.getRecordDetail(clients.ekbClient, corpId, recordId);
if (runtime.jsonMode) {
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const record = (detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>;
const entityId = String(record.entityId || "");
const nameKey = entityId ? `E_${entityId}_name` : "name";
const codeKey = entityId ? `E_${entityId}_code` : "code";
const nameVal = record.name ?? record["名称"] ?? record[nameKey];
const codeVal = record.code ?? record["编码"] ?? record[codeKey];
const formatTime = (time: unknown) =>
typeof time === "number" ? new Date(time).toLocaleString("zh-CN", { hour12: false }) : cell(time);
const rows: Array<Array<string | number | boolean | null | undefined>> = [
["记录 ID", cell(record.id ?? recordId)],
["业务对象 ID (entityId)", entityId || "-"],
["名称", cell(nameVal)],
["编码", cell(codeVal)],
["状态", record.active === false ? "🔴 停用" : "🟢 启用"],
["创建时间", formatTime(record.createTime)],
["更新时间", formatTime(record.updateTime)],
];
const skipKeys = new Set([
"id",
"entityId",
"name",
"code",
nameKey,
codeKey,
"active",
"createTime",
"updateTime",
"visibility",
"form",
]);
for (const [k, v] of Object.entries(record)) {
if (skipKeys.has(k)) continue;
if (v !== undefined && v !== null && v !== "") {
const label = entityId && k.startsWith(`E_${entityId}_`) ? `${k.slice(`E_${entityId}_`.length)} (${k})` : k;
rows.push([label, formatDirectRecordFieldValue(v)]);
}
}
if (record.form && typeof record.form === "object" && !Array.isArray(record.form)) {
for (const [k, v] of Object.entries(record.form as Record<string, unknown>)) {
if (v !== undefined && v !== null && v !== "") {
rows.push([k, formatDirectRecordFieldValue(v)]);
}
}
}
return {
stdout: `====== 记录详情 (${recordId}) ======\n${printTable(["字段/属性", "值"], rows)}\n`,
stderr: "",
exitCode: 0,
};
}
function parseJsonDataOption(parsed: CliParsedArgs): Record<string, unknown> {
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
const filePath = stringOption(parsed.options, ["file", "f"]);
if (dataStr) {
try {
return JSON.parse(dataStr) as Record<string, unknown>;
} catch {
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
}
}
if (filePath) {
try {
return JSON.parse(readFileSync(filePath, "utf8")) as Record<string, unknown>;
} catch (error) {
throw new Error(`无法读取或解析 JSON 文件 [${filePath}]: ${error instanceof Error ? error.message : String(error)}`);
}
}
return {};
}
async function handleBatchEdit(
parsed: CliParsedArgs,
runtime: CliRuntime,
appIndex: number,
entityIndex: number
): Promise<CliResult> {
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
if (!resolved.entity) {
throw new Error(
"用法: hose-use platform record batch-edit <应用> <业务对象> (--ids=<id1,id2> | --filter=<expr>) (--data='<json>' | --file=<patch.json>) [--concurrency=8] [--dry-run] [--yes]"
);
}
const idsOpt = stringOption(parsed.options, ["ids", "id"]);
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]);
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
const filePath = stringOption(parsed.options, ["file", "f"]);
const concurrency = numberOption(parsed.options, ["concurrency", "c"], 8);
const activeOpt =
parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
if (!dataStr && !filePath) {
throw new Error("请通过 --data='<json>' 或 --file=<patch.json> 提供要批量更新的字段内容");
}
requireMutationConfirmation(
parsed,
runtime,
"批量编辑业务对象记录",
`hose-use platform record batch-edit ${resolved.platform.id} ${resolved.entity.id} --yes`
);
let fileContent: unknown;
if (filePath) {
try {
fileContent = JSON.parse(readFileSync(filePath, "utf8"));
} catch (error) {
throw new Error(`无法读取或解析 JSON 文件 [${filePath}]: ${error instanceof Error ? error.message : String(error)}`);
}
}
let uniformPatch: Record<string, unknown> | undefined;
if (dataStr) {
try {
uniformPatch = JSON.parse(dataStr) as Record<string, unknown>;
} catch {
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
}
} else if (
fileContent &&
typeof fileContent === "object" &&
!Array.isArray(fileContent) &&
!Object.values(fileContent as Record<string, unknown>).every(
(v) => v && typeof v === "object" && !Array.isArray(v) && !("standard" in (v as Record<string, unknown>))
)
) {
uniformPatch = fileContent as Record<string, unknown>;
}
const targets: BatchEditTargetItem[] = [];
if (Array.isArray(fileContent)) {
for (const entry of fileContent) {
if (!entry || typeof entry !== "object") continue;
const item = entry as Record<string, unknown>;
const recordId = String(item.id ?? item.recordId ?? item.dataLinkId ?? "").trim();
const patchForm =
(item.form as Record<string, unknown>) ??
(item.data as Record<string, unknown>) ??
uniformPatch ??
{};
if (recordId) {
targets.push({
recordId,
patchForm,
active: typeof item.active === "boolean" ? item.active : activeOpt,
});
}
}
} else if (!uniformPatch && fileContent && typeof fileContent === "object") {
for (const [recordId, patchVal] of Object.entries(fileContent as Record<string, unknown>)) {
if (patchVal && typeof patchVal === "object" && !Array.isArray(patchVal)) {
targets.push({
recordId,
patchForm: patchVal as Record<string, unknown>,
active: activeOpt,
});
}
}
}
if (targets.length === 0) {
if (!uniformPatch) {
throw new Error("未解析到有效的批量更新内容");
}
let recordIds = splitFields(idsOpt);
if (recordIds.length === 0 && filterBy) {
const page = await fetchAllEntityRecords(
resolved.clients.ekbClient,
resolved.corpId,
resolved.entity.id,
{ filterBy }
);
recordIds = page.data
.map((r) => {
const dl =
r.dataLink && typeof r.dataLink === "object"
? (r.dataLink as Record<string, unknown>)
: r;
return String(dl.id ?? r.id ?? "").trim();
})
.filter(Boolean);
}
if (recordIds.length === 0) {
throw new Error("请通过 --ids=<id1,id2,...> 或 --filter=<表达式> 指定要批量更新的目标记录");
}
for (const id of recordIds) {
targets.push({
recordId: id,
patchForm: uniformPatch,
active: activeOpt,
});
}
}
const dryRun = isDryRun(parsed, runtime);
const results = await batchSafeEditRecords(
resolved.clients.ekbClient,
resolved.corpId,
resolved.entity,
targets,
{ concurrency, dryRun }
);
const succeeded = results.filter((r) => r.status === "updated" || r.status === "preview").length;
const failed = results.filter((r) => r.status === "failed").length;
const summary = {
dryRun,
platformId: resolved.platform.id,
entityId: resolved.entity.id,
total: results.length,
succeeded,
failed,
items: results,
};
if (runtime.jsonMode) {
return {
stdout: printJson(summary, runtime.outputOptions),
stderr: "",
exitCode: failed > 0 ? 1 : 0,
};
}
const rows = results.map((item, idx) => [
idx + 1,
item.recordId,
item.status === "preview" ? "🔍 预览 (dry-run)" : item.status === "updated" ? "✅ 已更新" : "❌ 失败",
item.payload ? Object.keys(item.payload.form).length : "-",
item.error || "-",
]);
return {
stdout: [
`====== 批量安全编辑业务对象记录 (${dryRun ? "Dry-Run 预览" : "已执行"}) ======`,
`应用: ${resolved.platform.name} (${resolved.platform.id}) | 业务对象: ${resolved.entity.name} (${resolved.entity.id})`,
`总计: ${results.length} | 成功/预览: ${succeeded} | 失败: ${failed}`,
printTable(["#", "记录 ID", "状态", "合并后字段数", "错误信息"], rows),
"",
].join("\n"),
stderr: "",
exitCode: failed > 0 ? 1 : 0,
};
}
async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const action = parsed.action?.toLowerCase() || "record";
let subAction: string;
@@ -177,6 +570,10 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
let entityIndex: number;
let recordIdIndex: number;
if (action === "batch-edit" || action === "record-batch-edit") {
return handleBatchEdit(parsed, runtime, 0, 1);
}
if (action.startsWith("record-")) {
subAction = action.replace("record-", "");
appIndex = 0;
@@ -184,7 +581,20 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
recordIdIndex = 2;
} else {
const firstArg = parsed.args[0]?.toLowerCase();
if (["get", "show", "detail", "toggle", "state", "edit", "update", "recompute", "recalc"].includes(firstArg)) {
if (
[
"get",
"show",
"detail",
"toggle",
"state",
"edit",
"update",
"batch-edit",
"recompute",
"recalc",
].includes(firstArg)
) {
subAction = firstArg;
appIndex = 1;
entityIndex = 2;
@@ -197,6 +607,16 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
}
}
if (subAction === "batch-edit") {
return handleBatchEdit(parsed, runtime, appIndex, entityIndex);
}
// 支持 hose-use platform record get <recordId> 或 hose-use platform record <recordId> 免应用/实体直接查询
const remainingArgs = parsed.args.slice(appIndex);
if (["get", "show", "detail"].includes(subAction) && remainingArgs.length === 1) {
return handleDirectRecordGet(remainingArgs[0].trim(), runtime);
}
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform record <动作> <应用> <业务对象> <记录ID>");
const recordId = requiredTarget(parsed, recordIdIndex, "hose-use platform record <动作> <应用> <业务对象> <记录ID>");
@@ -283,37 +703,49 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
}
case "edit":
case "update": {
const dataStr = stringOption(parsed.options, ["data", "form", "d", "f"]);
let form: Record<string, unknown> = {};
if (dataStr) {
try {
form = JSON.parse(dataStr);
} catch {
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
}
}
const form = parseJsonDataOption(parsed);
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
const changes = {
dataLinkEntityId: resolved.entity.id,
dataLinkId: recordId,
form,
active: activeOpt ?? null,
};
const isRaw = booleanOption(parsed.options, ["raw"], false);
requireMutationConfirmation(
parsed,
runtime,
"编辑业务对象记录",
`hose-use platform record edit ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, changes);
let payload: api.SafeRecordEditOptions extends never ? never : ReturnType<typeof api.buildSafeRecordEditPayload>;
if (isRaw) {
payload = {
dataLinkEntityId: resolved.entity.id,
dataLinkId: recordId,
form,
active: activeOpt,
};
} else {
let detail: Record<string, unknown> = {};
try {
detail = await api.getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
} catch (error) {
// 在部分仅 mock 了 editRecord 的单元测试中,ekbClient.get 可能未定义,此时退化为空基础详情以兼容测试
if (typeof (resolved.clients.ekbClient as any)?.get === "function") {
throw error;
}
}
payload = api.buildSafeRecordEditPayload({
entityId: resolved.entity.id,
recordId,
detail,
fields: resolved.entity.fields,
patchForm: form,
active: activeOpt,
});
}
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, {
dataLinkEntityId: resolved.entity.id,
dataLinkId: recordId,
form,
active: activeOpt,
});
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, payload);
}
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, payload);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return {
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 字段更新成功。\n`,
@@ -345,6 +777,7 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
};
}
default:
throw new Error(`未知 record 动作: ${subAction}。支持: get, toggle, edit, recompute`);
throw new Error(`未知 record 动作: ${subAction}。支持: get, toggle, edit, batch-edit, recompute`);
}
}