feat(datalink,platform): add ledger math audit, continuity check, and in-line declarative batch update
This commit is contained in:
1 parent
d3f7d3efbc
commit
cd0aa2bf41
8 files changed
+984
-26
No files matched your search
@@ -38,6 +38,9 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
|
||||
case "record-edit":
|
||||
case "record-batch-edit":
|
||||
case "batch-edit":
|
||||
case "record-update":
|
||||
case "update":
|
||||
case "batch-update":
|
||||
case "record-recompute": return handleRecordAction(parsed, runtime);
|
||||
case "permissions":
|
||||
case "permission":
|
||||
|
||||
@@ -4,7 +4,9 @@ import {
|
||||
buildSafeRecordEditPayload,
|
||||
editRecord,
|
||||
fetchAllEntityRecords,
|
||||
filterRecordsByPredicate,
|
||||
getRecordDetail,
|
||||
parseSetClause,
|
||||
recomputeRecordLedger,
|
||||
toggleRecordState,
|
||||
type BatchEditTargetItem,
|
||||
@@ -137,20 +139,22 @@ async function handleBatchEdit(
|
||||
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]"
|
||||
"用法: hose-use platform record batch-edit <应用> <业务对象> (--where='<expr>' | --ids=<id1,id2> | --filter=<expr>) (--set='<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 whereClause = stringOption(parsed.options, ["where"]);
|
||||
const setClause = stringOption(parsed.options, ["set"]);
|
||||
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> 提供要批量更新的字段内容");
|
||||
if (!dataStr && !filePath && !setClause) {
|
||||
throw new Error("请通过 --set='字段=值'、--data='<json>' 或 --file=<patch.json> 提供要批量更新的字段内容");
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
@@ -170,7 +174,9 @@ async function handleBatchEdit(
|
||||
}
|
||||
|
||||
let uniformPatch: Record<string, unknown> | undefined;
|
||||
if (dataStr) {
|
||||
if (setClause) {
|
||||
uniformPatch = parseSetClause(setClause, resolved.entity);
|
||||
} else if (dataStr) {
|
||||
try {
|
||||
uniformPatch = JSON.parse(dataStr) as Record<string, unknown>;
|
||||
} catch {
|
||||
@@ -223,14 +229,18 @@ async function handleBatchEdit(
|
||||
throw new Error("未解析到有效的批量更新内容");
|
||||
}
|
||||
let recordIds = splitFields(idsOpt);
|
||||
if (recordIds.length === 0 && filterBy) {
|
||||
if (recordIds.length === 0 && (whereClause || filterBy)) {
|
||||
const page = await fetchAllEntityRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity.id,
|
||||
{ filterBy }
|
||||
);
|
||||
recordIds = page.data
|
||||
let records = page.data;
|
||||
if (whereClause) {
|
||||
records = filterRecordsByPredicate(records, whereClause, resolved.entity);
|
||||
}
|
||||
recordIds = records
|
||||
.map((r) => {
|
||||
const dl =
|
||||
r.dataLink && typeof r.dataLink === "object"
|
||||
@@ -241,7 +251,14 @@ async function handleBatchEdit(
|
||||
.filter(Boolean);
|
||||
}
|
||||
if (recordIds.length === 0) {
|
||||
throw new Error("请通过 --ids=<id1,id2,...> 或 --filter=<表达式> 指定要批量更新的目标记录");
|
||||
if (whereClause) {
|
||||
return {
|
||||
stdout: `未找到符合条件 [--where="${whereClause}"] 的记录,无需更新。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
throw new Error("请通过 --where=<条件>、--ids=<id1,id2,...> 或 --filter=<表达式> 指定要批量更新的目标记录");
|
||||
}
|
||||
for (const id of recordIds) {
|
||||
targets.push({
|
||||
@@ -289,14 +306,23 @@ async function handleBatchEdit(
|
||||
item.error || "-",
|
||||
]);
|
||||
|
||||
const outputLines = [
|
||||
`====== 批量安全编辑业务对象记录 (${dryRun ? "Dry-Run 预览" : "已执行"}) ======`,
|
||||
`应用: ${resolved.platform.name} (${resolved.platform.id}) | 业务对象: ${resolved.entity.name} (${resolved.entity.id})`,
|
||||
`总计: ${results.length} | 成功/预览: ${succeeded} | 失败: ${failed}`,
|
||||
];
|
||||
if (uniformPatch) {
|
||||
outputLines.push(`应用变更 Patch: ${JSON.stringify(uniformPatch)}`);
|
||||
}
|
||||
outputLines.push(printTable(["#", "记录 ID", "状态", "合并后字段数", "错误信息"], rows));
|
||||
if (dryRun) {
|
||||
outputLines.push("");
|
||||
outputLines.push("💡 这是 Dry-Run 预演模式,数据未发生任何改变。如需真正执行修改,请追加 --yes(或 --confirm)参数。");
|
||||
}
|
||||
outputLines.push("");
|
||||
|
||||
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"),
|
||||
stdout: outputLines.join("\n"),
|
||||
stderr: "",
|
||||
exitCode: failed > 0 ? 1 : 0,
|
||||
};
|
||||
@@ -309,7 +335,11 @@ export async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRunt
|
||||
let entityIndex: number;
|
||||
let recordIdIndex: number;
|
||||
|
||||
if (action === "batch-edit" || action === "record-batch-edit") {
|
||||
if (
|
||||
action === "batch-edit" ||
|
||||
action === "record-batch-edit" ||
|
||||
action === "batch-update"
|
||||
) {
|
||||
return handleBatchEdit(parsed, runtime, 0, 1);
|
||||
}
|
||||
|
||||
@@ -318,6 +348,11 @@ export async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRunt
|
||||
appIndex = 0;
|
||||
entityIndex = 1;
|
||||
recordIdIndex = 2;
|
||||
} else if (action === "update") {
|
||||
subAction = "update";
|
||||
appIndex = 0;
|
||||
entityIndex = 1;
|
||||
recordIdIndex = 2;
|
||||
} else {
|
||||
const firstArg = parsed.args[0]?.toLowerCase();
|
||||
if (
|
||||
@@ -330,6 +365,7 @@ export async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRunt
|
||||
"edit",
|
||||
"update",
|
||||
"batch-edit",
|
||||
"batch-update",
|
||||
"recompute",
|
||||
"recalc",
|
||||
].includes(firstArg)
|
||||
@@ -346,7 +382,12 @@ export async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRunt
|
||||
}
|
||||
}
|
||||
|
||||
if (subAction === "batch-edit") {
|
||||
if (subAction === "batch-edit" || subAction === "batch-update") {
|
||||
return handleBatchEdit(parsed, runtime, appIndex, entityIndex);
|
||||
}
|
||||
|
||||
const whereClause = stringOption(parsed.options, ["where"]);
|
||||
if ((subAction === "update" || subAction === "edit") && (whereClause || parsed.args.length <= recordIdIndex)) {
|
||||
return handleBatchEdit(parsed, runtime, appIndex, entityIndex);
|
||||
}
|
||||
|
||||
@@ -442,7 +483,8 @@ export async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRunt
|
||||
}
|
||||
case "edit":
|
||||
case "update": {
|
||||
const form = parseJsonDataOption(parsed);
|
||||
const setClause = stringOption(parsed.options, ["set"]);
|
||||
const form = setClause ? parseSetClause(setClause, resolved.entity) : parseJsonDataOption(parsed);
|
||||
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
||||
const isRaw = booleanOption(parsed.options, ["raw"], false);
|
||||
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import {
|
||||
aggregateRecordFields,
|
||||
auditEntityRecords,
|
||||
auditLedgerContinuityAndBaseline,
|
||||
buildKeywordFilter,
|
||||
fetchAllEntityRecords,
|
||||
filterRecordsByPredicate,
|
||||
parseExpectClause,
|
||||
searchEntityRecords,
|
||||
selectRecordFields,
|
||||
} from "../../../domains/datalink/services.js";
|
||||
import type { LedgerContinuityReport } from "../../../domains/datalink/types.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
@@ -15,24 +20,85 @@ 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 fetchAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const whereClause = stringOption(parsed.options, ["where"]);
|
||||
const sumOption = stringOption(parsed.options, ["sum", "stats", "aggregate"]);
|
||||
const groupBy = stringOption(parsed.options, ["group-by", "groupBy"]);
|
||||
const fetchAll = booleanOption(parsed.options, ["all", "a"], false) || Boolean(whereClause || sumOption);
|
||||
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 = 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 });
|
||||
const data = fields.length ? page.data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields)) : page.data;
|
||||
|
||||
let data = page.data;
|
||||
if (whereClause) {
|
||||
data = filterRecordsByPredicate(data, whereClause, resolved.entity);
|
||||
}
|
||||
|
||||
// 1. 数学聚合核算模式 (--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 };
|
||||
}
|
||||
|
||||
// 2. 常规记录查询模式
|
||||
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, fields },
|
||||
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, where: whereClause, 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"));
|
||||
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
|
||||
@@ -51,10 +117,14 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
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]");
|
||||
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);
|
||||
|
||||
@@ -68,10 +138,20 @@ export async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
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 };
|
||||
@@ -104,7 +184,7 @@ export async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
"本次体检记录数": report.auditedRecords,
|
||||
"健康记录数": report.healthyRecords,
|
||||
"异常记录数": report.affectedRecordCount,
|
||||
"总问题项数": report.issueCount,
|
||||
"总问题项数": report.issueCount + (continuityReport?.issues.length ?? 0),
|
||||
"关键字段缺失 (MISSING_FIELD)": report.summary.missingFieldCount,
|
||||
"引用对象已停用 (DISABLED_REFERENCE)": report.summary.disabledReferenceCount,
|
||||
"跨表同名维度待回填 (CROSS_LEDGER_MISSING_SYNC)": report.summary.crossLedgerMissingSyncCount,
|
||||
@@ -117,6 +197,42 @@ export async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
: "✅ 未发现任何字段缺失、停用引用或跨表维度不一致问题",
|
||||
];
|
||||
|
||||
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 执行) ──`);
|
||||
@@ -129,3 +245,4 @@ export async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user