Files
hose-use/src/cli/commands/platform/records.ts
T
gitea 7423e166a1 feat: 完善工作流工具链与大结果保护
- 工作流节点描述增加服务端托管黑名单,仅代码节点保留自定义 desc
- 工作流保存新增 --in-place,并改进版本冲突提示
- platform records 新增 --page 分页,--all 强制走 ndjson 文件流
- platform schema 展示 ownerId/submitterId 等系统字段
- 更新 Agent Skill 的代码节点 agent use 标记规范
- 补充对应测试与文档
2026-10-28 13:01:11 +08:00

394 lines
17 KiB
TypeScript

import {
aggregateRecordFields,
auditEntityRecords,
auditLedgerContinuityAndBaseline,
buildKeywordFilter,
buildServerFieldFilter,
calculateEntityRecordStats,
fetchAllEntityRecords,
compileRecordPredicate,
iterateAllEntityRecords,
normalizeDatalinkRecord,
parseExpectClause,
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";
import { usageError } from "../../errors.js";
import { open } from "node:fs/promises";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { cell, resolveAppAndEntity, splitFields } from "./shared.js";
export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const isStream = booleanOption(parsed.options, ["ndjson", "stream"], false);
if (isStream && !runtime.outputOptions?.outputFile && !runtime.writeStdout) {
throw usageError("当前调用入口不支持直接 NDJSON 流,请使用 --output-file <path> 保存,或在终端运行该命令。");
}
const isStatsSubcommand = parsed.args[0] === "stats" || parsed.action === "stats";
const appIndex = parsed.args[0] === "stats" ? 1 : 0;
const entityIndex = parsed.args[0] === "stats" ? 2 : 1;
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
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"]);
const isProfileStats = isStatsSubcommand || booleanOption(parsed.options, ["stats", "profile"], false);
const isRaw = booleanOption(parsed.options, ["raw"], false);
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(sumOption || isProfileStats);
const count = numberOption(parsed.options, ["count", "limit"], 20) ?? 20;
const page = Math.max(1, numberOption(parsed.options, ["page"], 1) ?? 1);
const start = numberOption(parsed.options, ["start", "offset"], (page - 1) * count) ?? 0;
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500) ?? 500;
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
// 全量 JSON/表格很容易把几十万条记录倒进 stdout 或内存;全量导出必须显式走文件流。
if (isAll && !isProfileStats && !sumOption) {
if (!isStream || !runtime.outputOptions?.outputFile) {
throw usageError(
"--all 不再直接返回全量 JSON/表格。请使用 --page/--count 分页查询,或使用 --ndjson --output-file <path> 流式导出;大范围检索建议交给脚本处理。"
);
}
}
// 1. 高性能流式下发模式 (--ndjson / --stream,内存开销 O(pageSize),专为海量数据外部脚本管道设计)
if (isStream) {
let streamCount = 0;
let bytes = 0;
const maxLimit = isAll ? Infinity : count ?? 20;
const outputFile = runtime.outputOptions?.outputFile;
const file = outputFile ? await open(outputFile, "w", 0o600) : undefined;
try {
if (maxLimit > 0) {
for await (const rawRecord of iterateAllEntityRecords(
resolved.clients.ekbClient,
resolved.corpId,
resolved.entity.id,
{ filterBy, pageSize }
)) {
if (predicate && !predicate(rawRecord)) continue;
let outputRecord: Record<string, unknown> = isRaw
? (rawRecord as Record<string, unknown>)
: (normalizeDatalinkRecord(rawRecord, resolved.entity) as unknown as Record<string, unknown>);
if (fields.length) {
outputRecord = selectRecordFields(outputRecord, fields, resolved.entity.fields);
}
const chunk = redactSensitiveText(JSON.stringify(outputRecord)) + "\n";
if (file) await file.writeFile(chunk);
else await runtime.writeStdout!(chunk);
bytes += Buffer.byteLength(chunk);
streamCount++;
if (maxLimit !== undefined && streamCount >= maxLimit) break;
}
}
} finally {
await file?.close();
}
return { stdout: outputFile ? printJson({ outputFile, bytes, records: streamCount }) : "", stderr: "", exitCode: 0 };
}
// 2. 宏观画像与统计模式 (--stats 或 platform records stats <应用> <对象>)
if (isProfileStats) {
const page = await fetchAllEntityRecords(
resolved.clients.ekbClient,
resolved.corpId,
resolved.entity.id,
{ filterBy, pageSize }
);
let records = page.data;
if (predicate) records = records.filter(predicate);
const stats = calculateEntityRecordStats(records, resolved.entity, page.total);
if (runtime.jsonMode) {
return { stdout: printJson(stats, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const patternRows: Array<Array<string | number>> = stats.codePatterns.map((p, idx) => [
idx + 1,
p.pattern,
p.sample,
p.count,
p.activeCount,
p.inactiveCount,
]);
const lines = [
`====== [${resolved.platform.name}] ${resolved.entity.name} 宏观状态与数据画像 (总数: ${stats.total}) ======`,
` - 状态分布: 🟢 启用 ${stats.activeCount} 条 (${stats.activeRate}) | 🔴 停用 ${stats.inactiveCount} 条`,
` - 名称画像: ${stats.uniqueNames} 个唯一名称 (其中 ${stats.duplicateNamesCount} 组存在重名,${stats.mixedStatusNamesCount} 组同时包含启用与停用)`,
` - 时间跨度: 最早创建 ${stats.earliestCreateTime || "-"} ~ 最晚更新 ${stats.latestUpdateTime || "-"}`,
"",
"── 编码结构与停用分布 ──",
printTable(["#", "编码模式", "样本", "总数", "启用数", "停用数"], patternRows),
];
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
}
let data: DatalinkRecord[] = [];
let total = 0;
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) {
const sumFields = splitFields(sumOption);
const aggReport = aggregateRecordFields(data, resolved.entity, { fields: sumFields, groupBy });
if (runtime.jsonMode) {
return { stdout: printJson(aggReport, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const statRows: Array<Array<string | number>> = Object.entries(aggReport.overall).map(([query, s]) => [
query,
s.fieldLabel,
s.count,
s.sum,
s.avg,
s.min,
s.max,
]);
const lines: string[] = [
`====== [${resolved.platform.name}] ${resolved.entity.name} 台账数学聚合核算 (统计样本: ${data.length} 条记录) ======`,
printTable(
["统计字段", "字段标签", "有效样本 (COUNT)", "总合计 (SUM)", "平均值 (AVG)", "最小值 (MIN)", "最大值 (MAX)"],
statRows
),
];
if (aggReport.groups && aggReport.groups.length > 0) {
lines.push("");
lines.push(`── 按 [${groupBy}] 分组统计 ──`);
const groupRows: Array<Array<string | number>> = [];
for (const g of aggReport.groups) {
for (const [query, s] of Object.entries(g.aggregates)) {
groupRows.push([g.groupValue, g.count, s.fieldLabel, s.sum, s.avg, s.min, s.max]);
}
}
lines.push(
printTable(
[`分组 (${groupBy})`, "组内条数", "字段", "组内合计", "组内均值", "最小值", "最大值"],
groupRows
)
);
}
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
}
// 4. 常规记录查询模式 (支持 --flat 扁平归一化)
if (isFlat) {
data = data.map((item) => normalizeDatalinkRecord(item, resolved.entity) as unknown as Record<string, unknown>);
}
if (fields.length) {
data = data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields));
}
const result = {
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: total || data.length,
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"));
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record<string, unknown>) : item;
const id = source.id ?? item.id;
const active = source.active ?? item.active;
const updateTime = source.updateTime ?? item.updateTime;
const nameVal = source.name ?? source["名称"] ?? (nameField ? source[nameField.name] : undefined) ?? source[`E_${resolved.entity!.id}_name`];
const codeVal = source.code ?? source["编码"] ?? (codeField ? source[codeField.name] : undefined) ?? source[`E_${resolved.entity!.id}_code`];
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} 记录 (总数: ${total || data.length}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
}
export 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] [--check-continuous=序号字段] [--expect=期望表达式]"
);
}
const checkFields = splitFields(stringOption(parsed.options, ["check-fields", "checkFields", "fields"]));
const activeOnly = booleanOption(parsed.options, ["active-only", "activeOnly"], false);
const checkContinuous = stringOption(parsed.options, ["check-continuous", "checkContinuous", "continuous", "seq", "sequence"]);
const expectClause = stringOption(parsed.options, ["expect", "expect-value", "expectValue", "baseline"]);
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,
});
let continuityReport: LedgerContinuityReport | undefined;
if (checkContinuous || expectClause) {
const expectedValues = expectClause ? parseExpectClause(expectClause) : undefined;
continuityReport = auditLedgerContinuityAndBaseline(page.data, resolved.entity, {
sequenceField: checkContinuous,
expectedValues,
});
}
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,
continuity: continuityReport,
};
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 + (continuityReport?.issues.length ?? 0),
"关键字段缺失 (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 (continuityReport) {
if (continuityReport.sequenceSummary) {
const seq = continuityReport.sequenceSummary;
outLines.push("");
outLines.push(`── 台账序号连续性体检 (字段: ${seq.fieldLabel}) ──`);
outLines.push(
printKeyValue({
"最小期数 (MIN)": seq.min,
"最大期数 (MAX)": seq.max,
"期望连续期数": seq.expectedCount,
"实际有效记录数": seq.actualCount,
"断层缺失期数 (MISSING)": seq.missing.length ? `❌ 缺少 [${seq.missing.join(", ")}]` : "✅ 无断层缺失",
"重复重号期数 (DUPLICATE)": seq.duplicates.length ? `❌ 重号 [${seq.duplicates.join(", ")}]` : "✅ 无重复重号",
})
);
}
if (expectClause) {
outLines.push("");
outLines.push(`── 基线离群异常核对 (共 ${continuityReport.outliers.length} 条偏离记录) ──`);
if (continuityReport.outliers.length > 0) {
const outlierRows = continuityReport.outliers.map((o, idx) => [
idx + 1,
o.recordId,
o.fieldLabel,
o.value,
o.expectedValue,
o.diff > 0 ? `+${o.diff}` : o.diff,
]);
outLines.push(printTable(["#", "记录 ID", "字段", "实际值", "基线期望", "偏离差额"], outlierRows));
} else {
outLines.push("✅ 所有记录数值均符合期望基线标准,无离群异常");
}
}
}
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,
};
}