Files
hose-use/src/domains/platform/datalink/audit.ts
T
gitea a2cdefb322 refactor: 拆分应用平台服务职责并固化无环边界
将工作流查询、配置、执行、差异、调试、目录和 DataLink 记录、表达式、审计分别归位。
门面保留显式导出,消除 tracker 及分支类型经聚合出口形成的循环,补充文件级循环检查。
同步总纲、层级文档与接口源码索引,交付完整整改报告。

验证:943 项测试通过,类型、版本和 README 审计通过;二进制和插件构建、验证与打包通过。
81 个迁移函数体保持一致,公共 SDK 导出名和三份生成规范与原始基线一致。
2026-10-30 17:05:20 +08:00

642 lines
20 KiB
TypeScript

import type { DatalinkEntity, DatalinkField, DatalinkRecord, AggregateFieldStats, GroupAggregateResult, LedgerAggregateReport, ContinuityIssue, LedgerContinuityReport, DatalinkRecordStats } from "./types.js";
import { normalizeDatalinkRecord, extractRefIdAndName, resolveEntityField, extractRecordFieldValue, extractNumericFieldValue } from "./records.js";
/**
* 计算业务对象记录的轻量级宏观分布画像(统计总数、启用/停用数、重名率、编码前缀聚类等)。
* 既可接收全量内存数组,也可配合流式生成器在 O(1) 内存下在线累加计算。
*/
export function calculateEntityRecordStats(
records: Iterable<DatalinkRecord>,
entity?: DatalinkEntity,
explicitTotal?: number
): DatalinkRecordStats {
let total = 0;
let activeCount = 0;
let inactiveCount = 0;
const namesMap = new Map<string, { total: number; active: number; inactive: number }>();
const patternsMap = new Map<string, { pattern: string; sample: string; count: number; activeCount: number; inactiveCount: number }>();
let earliestCreate: number | null = null;
let latestUpdate: number | null = null;
for (const raw of records) {
total++;
const norm = normalizeDatalinkRecord(raw, entity);
if (norm.active) activeCount++;
else inactiveCount++;
if (norm.createTime && typeof norm.createTime === "number") {
if (earliestCreate === null || norm.createTime < earliestCreate) earliestCreate = norm.createTime;
}
if (norm.updateTime && typeof norm.updateTime === "number") {
if (latestUpdate === null || norm.updateTime > latestUpdate) latestUpdate = norm.updateTime;
}
// 统计名称重名与状态交叉
if (norm.name) {
if (!namesMap.has(norm.name)) {
namesMap.set(norm.name, { total: 0, active: 0, inactive: 0 });
}
const nStats = namesMap.get(norm.name)!;
nStats.total++;
if (norm.active) nStats.active++;
else nStats.inactive++;
}
// 统计编码结构聚类
const code = norm.code || "EMPTY";
const pattern = code
.replace(/\d{8}/g, "YYYYMMDD")
.replace(/\d{6}/g, "SEQ6")
.replace(/\d+/g, "N");
if (!patternsMap.has(pattern)) {
patternsMap.set(pattern, { pattern, sample: code, count: 0, activeCount: 0, inactiveCount: 0 });
}
const pStats = patternsMap.get(pattern)!;
pStats.count++;
if (norm.active) pStats.activeCount++;
else pStats.inactiveCount++;
}
const finalTotal = explicitTotal !== undefined ? Math.max(explicitTotal, total) : total;
const activeRate = finalTotal > 0 ? `${((activeCount / finalTotal) * 100).toFixed(1)}%` : "0.0%";
let duplicateNamesCount = 0;
let mixedStatusNamesCount = 0;
for (const n of namesMap.values()) {
if (n.total > 1) duplicateNamesCount++;
if (n.active > 0 && n.inactive > 0) mixedStatusNamesCount++;
}
const codePatterns = Array.from(patternsMap.values()).sort((a, b) => b.count - a.count);
const formatDate = (ts: number | null) => (ts ? new Date(ts).toLocaleString("zh-CN", { hour12: false }) : null);
return {
total: finalTotal,
activeCount,
inactiveCount,
activeRate,
uniqueNames: namesMap.size,
duplicateNamesCount,
mixedStatusNamesCount,
codePatterns,
earliestCreateTime: formatDate(earliestCreate),
latestUpdateTime: formatDate(latestUpdate),
};
}
export interface DatalinkAuditIssue {
recordId: string;
recordCode: string;
recordName: string;
active: boolean;
type:
| "MISSING_FIELD"
| "DISABLED_REFERENCE"
| "CROSS_LEDGER_MISSING_SYNC"
| "CROSS_LEDGER_MISMATCH";
field: string;
fieldLabel: string;
message: string;
linkedField?: string;
linkedFieldLabel?: string;
linkedRecordId?: string;
actualId?: string;
actualName?: string;
expectedId?: string;
expectedName?: string;
}
export interface DatalinkAuditReport {
entityId: string;
entityName: string;
totalRecords: number;
auditedRecords: number;
healthyRecords: number;
affectedRecordCount: number;
issueCount: number;
summary: {
missingFieldCount: number;
disabledReferenceCount: number;
crossLedgerMissingSyncCount: number;
crossLedgerMismatchCount: number;
};
issues: DatalinkAuditIssue[];
suggestedPatches: Array<{
id: string;
code: string;
name: string;
form: Record<string, string>;
reason: string;
}>;
}
function isEmptyFieldValue(value: unknown): boolean {
if (value === undefined || value === null || value === "") return true;
if (Array.isArray(value)) return value.length === 0;
if (typeof value === "object") {
const obj = value as Record<string, unknown>;
if ("id" in obj) {
return obj.id === undefined || obj.id === null || obj.id === "";
}
if ("standard" in obj) {
return obj.standard === undefined || obj.standard === null || obj.standard === "";
}
return Object.keys(obj).length === 0;
}
return false;
}
/**
* 对业务对象记录集合执行数据健康度体检:
* 1. 必填/关键字段缺失检查 (MISSING_FIELD)
* 2. 关联对象/档案停用检查 (DISABLED_REFERENCE)
* 3. 跨表关联同名维度一致性检查 (CROSS_LEDGER_MISSING_SYNC / CROSS_LEDGER_MISMATCH)
*/
export function auditEntityRecords(
records: DatalinkRecord[],
entity: DatalinkEntity,
options: { checkFields?: string[]; activeOnly?: boolean; total?: number } = {}
): DatalinkAuditReport {
const bareEntityId = entity.id.startsWith("$") ? entity.id.slice(1) : entity.id;
const nameField = entity.fields.find(
(f) => f.label === "名称" || f.label === "标题" || f.name === `E_${bareEntityId}_name` || f.name.endsWith("_name")
);
const codeField = entity.fields.find(
(f) => f.label === "编码" || f.name === `E_${bareEntityId}_code` || f.name.endsWith("_code")
);
// 解析需要检查缺失的字段集合
const explicitSelectors = (options.checkFields ?? []).map((s) => s.trim()).filter(Boolean);
const fieldsToCheck: DatalinkField[] =
explicitSelectors.length > 0
? explicitSelectors.map((selector) => {
const found = entity.fields.find(
(f) =>
f.name === selector ||
f.label === selector ||
f.name === `E_${bareEntityId}_${selector}`
);
return (
found ?? {
name: selector.startsWith("E_") ? selector : `E_${bareEntityId}_${selector}`,
label: selector,
type: "text",
}
);
})
: entity.fields.filter(
(f) =>
f.optional === false ||
f.type === "dimension" ||
f.type === "dataLink"
);
const dataLinkFields = entity.fields.filter((f) => f.type === "dataLink");
const dimensionFields = entity.fields.filter((f) => f.type === "dimension");
const issues: DatalinkAuditIssue[] = [];
const suggestedPatchesMap = new Map<
string,
{ id: string; code: string; name: string; form: Record<string, string>; reasons: string[] }
>();
const affectedRecordIds = new Set<string>();
let auditedRecords = 0;
let missingFieldCount = 0;
let disabledReferenceCount = 0;
let crossLedgerMissingSyncCount = 0;
let crossLedgerMismatchCount = 0;
for (const rawRecord of records) {
const dl =
rawRecord.dataLink &&
typeof rawRecord.dataLink === "object" &&
!Array.isArray(rawRecord.dataLink)
? (rawRecord.dataLink as Record<string, unknown>)
: (rawRecord as Record<string, unknown>);
const recordId = String(dl.id ?? rawRecord.id ?? "");
const active = (dl.active ?? rawRecord.active) !== false;
if (options.activeOnly && !active) continue;
auditedRecords++;
const recordName = String(
dl.name ??
dl["名称"] ??
(nameField ? dl[nameField.name] : undefined) ??
dl[`E_${bareEntityId}_name`] ??
""
);
const recordCode = String(
dl.code ??
dl["编码"] ??
(codeField ? dl[codeField.name] : undefined) ??
dl[`E_${bareEntityId}_code`] ??
""
);
const getFieldVal = (field: DatalinkField): unknown =>
dl[field.name] ??
dl[`E_${bareEntityId}_${field.name}`] ??
(dl.form && typeof dl.form === "object"
? (dl.form as Record<string, unknown>)[field.name]
: undefined) ??
dl[field.label];
// 1. 必填/关键字段缺失检查
for (const field of fieldsToCheck) {
const val = getFieldVal(field);
if (isEmptyFieldValue(val)) {
missingFieldCount++;
affectedRecordIds.add(recordId);
issues.push({
recordId,
recordCode,
recordName,
active,
type: "MISSING_FIELD",
field: field.name,
fieldLabel: field.label || field.name,
message: `字段 [${field.label || field.name}] (${field.name}) 为空`,
});
}
}
// 2. 关联对象/档案停用检查
for (const field of entity.fields) {
if (field.type !== "dimension" && field.type !== "dataLink") continue;
const val = getFieldVal(field);
const items = Array.isArray(val) ? val : val ? [val] : [];
for (const item of items) {
const refInfo = extractRefIdAndName(item);
if (refInfo.active === false) {
disabledReferenceCount++;
affectedRecordIds.add(recordId);
issues.push({
recordId,
recordCode,
recordName,
active,
type: "DISABLED_REFERENCE",
field: field.name,
fieldLabel: field.label || field.name,
actualId: refInfo.id,
actualName: refInfo.name,
message: `字段 [${field.label || field.name}] 引用的${
field.type === "dataLink" ? "业务对象记录" : "维度档案"
} [${refInfo.name || refInfo.id || "-"}] (${refInfo.id || "-"}) 已停用 (active=false)`,
});
}
}
}
// 3. 跨表关联同名维度一致性检查
for (const linkField of dataLinkFields) {
const linkVal = getFieldVal(linkField);
if (!linkVal || typeof linkVal !== "object" || Array.isArray(linkVal)) continue;
const linkObj = linkVal as Record<string, unknown>;
const parentDl =
linkObj.data &&
typeof linkObj.data === "object" &&
(linkObj.data as Record<string, unknown>).dataLink &&
typeof (linkObj.data as Record<string, unknown>).dataLink === "object"
? ((linkObj.data as Record<string, unknown>).dataLink as Record<string, unknown>)
: linkObj.dataLink && typeof linkObj.dataLink === "object"
? (linkObj.dataLink as Record<string, unknown>)
: linkObj;
const linkedRecordId = String(parentDl.id ?? linkObj.id ?? "");
for (const dimField of dimensionFields) {
const entityPrefix = `E_${bareEntityId}_`;
const suffix = dimField.name.startsWith(entityPrefix)
? dimField.name.slice(entityPrefix.length)
: dimField.name.replace(/^E_[^_]+_/, "");
const parentKey = Object.keys(parentDl).find(
(k) =>
k === dimField.label ||
k === suffix ||
k.endsWith(`_${suffix}`) ||
(Boolean(dimField.label) && k.endsWith(`_${dimField.label}`))
);
if (!parentKey) continue;
const parentRef = extractRefIdAndName(parentDl[parentKey]);
if (!parentRef.id) continue;
const childRef = extractRefIdAndName(getFieldVal(dimField));
if (!childRef.id) {
crossLedgerMissingSyncCount++;
affectedRecordIds.add(recordId);
const reason = `子表字段 [${dimField.label || dimField.name}] 为空,但关联 [${
linkField.label || linkField.name
}] (${linkedRecordId}) 中同名字段有值 [${parentRef.name || parentRef.id}] (${
parentRef.id
}),建议回填修复`;
issues.push({
recordId,
recordCode,
recordName,
active,
type: "CROSS_LEDGER_MISSING_SYNC",
field: dimField.name,
fieldLabel: dimField.label || dimField.name,
linkedField: linkField.name,
linkedFieldLabel: linkField.label || linkField.name,
linkedRecordId,
expectedId: parentRef.id,
expectedName: parentRef.name,
message: reason,
});
const existingPatch = suggestedPatchesMap.get(recordId) ?? {
id: recordId,
code: recordCode,
name: recordName,
form: {},
reasons: [],
};
existingPatch.form[dimField.name] = parentRef.id;
existingPatch.reasons.push(
`${dimField.label || dimField.name} <- ${parentRef.name || parentRef.id} (${parentRef.id})`
);
suggestedPatchesMap.set(recordId, existingPatch);
} else if (childRef.id !== parentRef.id) {
crossLedgerMismatchCount++;
affectedRecordIds.add(recordId);
issues.push({
recordId,
recordCode,
recordName,
active,
type: "CROSS_LEDGER_MISMATCH",
field: dimField.name,
fieldLabel: dimField.label || dimField.name,
linkedField: linkField.name,
linkedFieldLabel: linkField.label || linkField.name,
linkedRecordId,
actualId: childRef.id,
actualName: childRef.name,
expectedId: parentRef.id,
expectedName: parentRef.name,
message: `子表字段 [${dimField.label || dimField.name}] 当前值 [${
childRef.name || childRef.id
}] (${childRef.id}) 与关联 [${
linkField.label || linkField.name
}] (${linkedRecordId}) 中的值 [${parentRef.name || parentRef.id}] (${
parentRef.id
}) 不一致`,
});
}
}
}
}
const suggestedPatches = [...suggestedPatchesMap.values()].map((item) => ({
id: item.id,
code: item.code,
name: item.name,
form: item.form,
reason: item.reasons.join("; "),
}));
return {
entityId: entity.id,
entityName: entity.name,
totalRecords: options.total ?? records.length,
auditedRecords,
healthyRecords: Math.max(0, auditedRecords - affectedRecordIds.size),
affectedRecordCount: affectedRecordIds.size,
issueCount: issues.length,
summary: {
missingFieldCount,
disabledReferenceCount,
crossLedgerMissingSyncCount,
crossLedgerMismatchCount,
},
issues,
suggestedPatches,
};
}
/**
* 对记录进行聚合统计(COUNT, SUM, AVG, MIN, MAX,可选分组)
*/
export function aggregateRecordFields(
records: DatalinkRecord[],
entity: DatalinkEntity,
options: {
fields: string[];
groupBy?: string;
}
): LedgerAggregateReport {
const resolvedFields = options.fields.map((f) => {
const resolved = resolveEntityField(entity, f);
return {
query: f,
field: resolved ?? { name: f, label: f, type: "number" },
};
});
const calcStats = (list: DatalinkRecord[]): Record<string, AggregateFieldStats> => {
const stats: Record<string, AggregateFieldStats> = {};
for (const { query, field } of resolvedFields) {
let count = 0;
let sum = 0;
let min = Infinity;
let max = -Infinity;
for (const r of list) {
const num = extractNumericFieldValue(r, field);
if (num !== null) {
count++;
sum += num;
if (num < min) min = num;
if (num > max) max = num;
}
}
stats[query] = {
field: field.name,
fieldLabel: field.label || field.name,
count,
sum: Math.round(sum * 100) / 100,
avg: count > 0 ? Math.round((sum / count) * 100) / 100 : 0,
min: count > 0 ? min : 0,
max: count > 0 ? max : 0,
};
}
return stats;
};
const overall = calcStats(records);
let groups: GroupAggregateResult[] | undefined;
if (options.groupBy) {
const groupField = resolveEntityField(entity, options.groupBy) ?? {
name: options.groupBy,
label: options.groupBy,
type: "text",
};
const groupMap = new Map<string, DatalinkRecord[]>();
for (const r of records) {
const gVal = String(extractRecordFieldValue(r, groupField) ?? "(未填写)");
const existing = groupMap.get(gVal);
if (existing) existing.push(r);
else groupMap.set(gVal, [r]);
}
groups = Array.from(groupMap.entries()).map(([groupValue, groupRecords]) => ({
groupValue,
count: groupRecords.length,
aggregates: calcStats(groupRecords),
}));
}
return {
totalRecords: records.length,
overall,
groups,
};
}
/**
* 台账序号连续性检查与期望基线数学核对
*/
export function auditLedgerContinuityAndBaseline(
records: DatalinkRecord[],
entity: DatalinkEntity,
options: {
sequenceField?: string;
expectedValues?: Array<{
field: string;
targetValue: number;
tolerance?: number;
}>;
}
): LedgerContinuityReport {
const issues: ContinuityIssue[] = [];
const outliers: LedgerContinuityReport["outliers"] = [];
let sequenceSummary: LedgerContinuityReport["sequenceSummary"] | undefined;
// 1. 序号连续性核查
if (options.sequenceField) {
const resolvedSeqField = resolveEntityField(entity, options.sequenceField) ?? {
name: options.sequenceField,
label: options.sequenceField,
type: "number",
};
const seqMap = new Map<number, string[]>();
const numbers: number[] = [];
for (const r of records) {
const num = extractNumericFieldValue(r, resolvedSeqField);
if (num !== null) {
const intVal = Math.round(num);
numbers.push(intVal);
const existing = seqMap.get(intVal);
const rId = r.id || String(r.recordId || "");
if (existing) existing.push(rId);
else seqMap.set(intVal, [rId]);
}
}
if (numbers.length > 0) {
const min = Math.min(...numbers);
const max = Math.max(...numbers);
const missing: number[] = [];
const duplicates: number[] = [];
for (let i = min; i <= max; i++) {
const count = seqMap.get(i)?.length ?? 0;
if (count === 0) {
missing.push(i);
issues.push({
type: "MISSING_SEQUENCE",
field: resolvedSeqField.name,
message: `台账序号断层:缺少第 [${i}] 期记录`,
expected: i,
actual: null,
});
} else if (count > 1) {
duplicates.push(i);
issues.push({
type: "DUPLICATE_SEQUENCE",
field: resolvedSeqField.name,
message: `台账序号重号:第 [${i}] 期存在 ${count} 条重复记录 (${seqMap.get(i)?.join(", ")})`,
expected: 1,
actual: count,
});
}
}
sequenceSummary = {
field: resolvedSeqField.name,
fieldLabel: resolvedSeqField.label || resolvedSeqField.name,
min,
max,
expectedCount: max - min + 1,
actualCount: numbers.length,
missing,
duplicates,
};
}
}
// 2. 基线离群异常核对
if (options.expectedValues && options.expectedValues.length > 0) {
for (const exp of options.expectedValues) {
const field = resolveEntityField(entity, exp.field) ?? {
name: exp.field,
label: exp.field,
type: "number",
};
const tolerance = exp.tolerance ?? 0.05;
for (const r of records) {
const val = extractNumericFieldValue(r, field);
if (val !== null) {
const diff = Math.abs(val - exp.targetValue);
if (diff > tolerance) {
const rId = r.id || String(r.recordId || "");
outliers.push({
recordId: rId,
field: field.name,
fieldLabel: field.label || field.name,
value: val,
expectedValue: exp.targetValue,
diff: Math.round(diff * 100) / 100,
});
issues.push({
type: "VALUE_OUTLIER",
recordId: rId,
field: field.name,
message: `记录 [${rId}] 字段 [${field.label || field.name}] 数值 [${val}] 偏离基线期望 [${exp.targetValue}] (差额: ${diff > 0 ? "+" : ""}${Math.round(diff * 100) / 100})`,
expected: exp.targetValue,
actual: val,
});
}
}
}
}
}
return {
totalRecords: records.length,
sequenceSummary,
issues,
outliers,
};
}