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
@@ -30,20 +30,27 @@ 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 <表达式>] [--fields <字段列表>]
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--all] [--keyword <关键词>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>]
|
||||
hose-use platform record get [<应用> <业务对象>] <记录ID>
|
||||
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> --data='{"field": "val"}' [--raw] [--dry-run|--yes]
|
||||
hose-use platform record batch-edit <应用> <业务对象> [--ids=id1,id2|--filter=...] --data='{"field": "val"}' [--concurrency=8] [--dry-run|--yes]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> [--set="字段=值" | --data='{"field": "val"}'] [--raw] [--dry-run|--yes]
|
||||
hose-use platform record update <应用> <业务对象> [--where="条件"] --set="字段=值" [--dry-run|--yes]
|
||||
hose-use platform record batch-edit <应用> <业务对象> [--where="条件"|--ids=id1,id2|--filter=...] [--set="字段=值"|--data='{"field": "val"}'] [--concurrency=8] [--dry-run|--yes]
|
||||
hose-use platform record recompute <应用> <业务对象> <记录ID> [--dry-run|--yes]
|
||||
hose-use platform audit <应用 ID|名称> <对象 ID|名称> [--check-fields=字段1,字段2] [--active-only]
|
||||
hose-use platform audit <应用 ID|名称> <对象 ID|名称> [--check-fields=字段1,字段2] [--active-only] [--check-continuous=序号字段] [--expect="字段 ~= 期望值 [+- 容差]"]
|
||||
hose-use platform permissions <应用 ID|名称> [对象 ID|名称]
|
||||
hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
```
|
||||
|
||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||
|
||||
- `records --sum="字段1,字段2" [--group-by="分组字段"]`:台账数学聚合核算,自动解析纯数值、金额对象(`{ standard: 100 }`)与货币符号字符串(`¥12,500.00`),输出样本数、总合计(SUM)、均值(AVG)、最小值(MIN)、最大值(MAX)以及指定字段的分组小计。
|
||||
- `records --where="条件"`:支持在客户端按字段中文标签或物理名做声明式组合过滤(支持 `==`, `!=`, `>`, `<`, `>=`, `<=`, `in (...)`, 以及 `&&` 联合条件)。
|
||||
- `audit --check-continuous="序号字段"`:台账连续性体检,精准识别期数序号序列中的断层缺失(MISSING)与重号重复(DUPLICATE)。
|
||||
- `audit --expect="字段 ~= 期望值 [+- 容差]"`:基线数值离群诊断,自动识别并列出偏离基准值的异常记录明细与差额。
|
||||
- `record update <应用> <业务对象> [--where="条件"] --set="字段=值" [--dry-run] [--yes]`:声明式原地批量修改,支持中文字段标签解析与智能类型转换,通过 `--dry-run` 预览拟更新记录与合并后字段,追加 `--yes` 真正执行。
|
||||
- `record get` 支持直传 `<记录ID>` 免传应用与业务对象。
|
||||
- `record edit` 与 `record batch-edit` 默认启用 **Read-Modify-Write 安全全量合并**(保留全部 `E_<entityId>_*` 字段、将嵌套引用对象归一化为字符串 ID、保留 `active` 与 `visibility` 结构,支持字段短名/中文标签映射);仅当显式传入 `--raw` 时才直接透传原始补丁。
|
||||
- `records --all` 自动按 `500` 条/页循环拉取全量台账记录。
|
||||
- `audit` 一键巡检必填/指定字段缺失、引用已停用档案以及跨台账同名字段同步差异,并输出 `suggestedPatches`。
|
||||
|
||||
@@ -11,10 +11,15 @@ import {
|
||||
toggleRecordState,
|
||||
} from "./api.js";
|
||||
import {
|
||||
aggregateRecordFields,
|
||||
auditEntityRecords,
|
||||
auditLedgerContinuityAndBaseline,
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
fetchAllEntityRecords,
|
||||
filterRecordsByPredicate,
|
||||
parseExpectClause,
|
||||
parseSetClause,
|
||||
selectRecordFields,
|
||||
} from "./services.js";
|
||||
|
||||
@@ -386,5 +391,145 @@ describe("DataLink Domain - 应用、业务对象与记录查询", () => {
|
||||
expect(results[0]?.status).toBe("preview");
|
||||
expect(results[0]?.payload?.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
});
|
||||
|
||||
test("aggregateRecordFields 准确统计数值、金额对象、货币字符串并支持分组", () => {
|
||||
const entity = {
|
||||
id: "e_lease",
|
||||
name: "租金台账",
|
||||
fields: [
|
||||
{ name: "E_e_lease_period", label: "期数", type: "number" },
|
||||
{ name: "E_e_lease_rent", label: "租赁费用", type: "money" },
|
||||
{ name: "E_e_lease_status", label: "状态", type: "text" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const records = [
|
||||
{ id: "1", E_e_lease_period: 1, E_e_lease_rent: { standard: 10000 }, E_e_lease_status: "已摊销" },
|
||||
{ id: "2", E_e_lease_period: 2, E_e_lease_rent: 15000, E_e_lease_status: "已摊销" },
|
||||
{ id: "3", E_e_lease_period: 3, E_e_lease_rent: "¥20,000.00", E_e_lease_status: "待摊销" },
|
||||
];
|
||||
|
||||
const report = aggregateRecordFields(records as any, entity as any, {
|
||||
fields: ["租赁费用"],
|
||||
groupBy: "状态",
|
||||
});
|
||||
|
||||
expect(report.totalRecords).toBe(3);
|
||||
const rentStats = report.overall["租赁费用"];
|
||||
expect(rentStats).toBeDefined();
|
||||
expect(rentStats?.count).toBe(3);
|
||||
expect(rentStats?.sum).toBe(45000);
|
||||
expect(rentStats?.avg).toBe(15000);
|
||||
expect(rentStats?.min).toBe(10000);
|
||||
expect(rentStats?.max).toBe(20000);
|
||||
|
||||
expect(report.groups).toHaveLength(2);
|
||||
const amortizedGroup = report.groups?.find((g) => g.groupValue === "已摊销");
|
||||
expect(amortizedGroup?.count).toBe(2);
|
||||
expect(amortizedGroup?.aggregates["租赁费用"]?.sum).toBe(25000);
|
||||
});
|
||||
|
||||
test("auditLedgerContinuityAndBaseline 精准诊断台账序号断层、重号以及离群异常", () => {
|
||||
const entity = {
|
||||
id: "e_lease",
|
||||
name: "租金台账",
|
||||
fields: [
|
||||
{ name: "E_e_lease_seq", label: "摊销序号", type: "number" },
|
||||
{ name: "E_e_lease_fee", label: "租金金额", type: "money" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const records = [
|
||||
{ id: "r-1", E_e_lease_seq: 1, E_e_lease_fee: 78787.55 },
|
||||
{ id: "r-2a", E_e_lease_seq: 2, E_e_lease_fee: 78787.55 },
|
||||
{ id: "r-2b", E_e_lease_seq: 2, E_e_lease_fee: 0 }, // 离群 + 重号
|
||||
// 缺少序号 3
|
||||
{ id: "r-4", E_e_lease_seq: 4, E_e_lease_fee: 78787.55 },
|
||||
];
|
||||
|
||||
const report = auditLedgerContinuityAndBaseline(records as any, entity as any, {
|
||||
sequenceField: "摊销序号",
|
||||
expectedValues: [{ field: "租金金额", targetValue: 78787.55, tolerance: 0.1 }],
|
||||
});
|
||||
|
||||
expect(report.sequenceSummary).toBeDefined();
|
||||
expect(report.sequenceSummary?.min).toBe(1);
|
||||
expect(report.sequenceSummary?.max).toBe(4);
|
||||
expect(report.sequenceSummary?.missing).toEqual([3]);
|
||||
expect(report.sequenceSummary?.duplicates).toEqual([2]);
|
||||
|
||||
expect(report.outliers).toHaveLength(1);
|
||||
expect(report.outliers[0]?.recordId).toBe("r-2b");
|
||||
expect(report.outliers[0]?.value).toBe(0);
|
||||
expect(report.outliers[0]?.expectedValue).toBe(78787.55);
|
||||
|
||||
const missingIssue = report.issues.find((i) => i.type === "MISSING_SEQUENCE");
|
||||
expect(missingIssue?.message).toContain("缺少第 [3] 期记录");
|
||||
const dupIssue = report.issues.find((i) => i.type === "DUPLICATE_SEQUENCE");
|
||||
expect(dupIssue?.message).toContain("第 [2] 期存在 2 条重复记录");
|
||||
});
|
||||
|
||||
test("parseExpectClause 解析各种容差与期望表达式", () => {
|
||||
const res1 = parseExpectClause("租赁费用 ~= 78787.55");
|
||||
expect(res1).toEqual([{ field: "租赁费用", targetValue: 78787.55, tolerance: undefined }]);
|
||||
|
||||
const res2 = parseExpectClause("租赁费用 = 78787.55 +- 0.05, 日折旧费 ~= 2626.25");
|
||||
expect(res2).toEqual([
|
||||
{ field: "租赁费用", targetValue: 78787.55, tolerance: 0.05 },
|
||||
{ field: "日折旧费", targetValue: 2626.25, tolerance: undefined },
|
||||
]);
|
||||
});
|
||||
|
||||
test("filterRecordsByPredicate 支持比较操作符与 in 语法", () => {
|
||||
const entity = {
|
||||
id: "e_item",
|
||||
name: "资产",
|
||||
fields: [
|
||||
{ name: "E_e_item_amount", label: "金额", type: "number" },
|
||||
{ name: "E_e_item_status", label: "状态", type: "text" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const records = [
|
||||
{ id: "1", E_e_item_amount: 100, E_e_item_status: "ACTIVE" },
|
||||
{ id: "2", E_e_item_amount: 0, E_e_item_status: "INACTIVE" },
|
||||
{ id: "3", E_e_item_amount: 250, E_e_item_status: "ACTIVE" },
|
||||
];
|
||||
|
||||
const matchZero = filterRecordsByPredicate(records as any, "金额 == 0", entity as any);
|
||||
expect(matchZero.map((r) => r.id)).toEqual(["2"]);
|
||||
|
||||
const matchActiveGt100 = filterRecordsByPredicate(records as any, "状态 == 'ACTIVE' && 金额 > 100", entity as any);
|
||||
expect(matchActiveGt100.map((r) => r.id)).toEqual(["3"]);
|
||||
|
||||
const matchIn = filterRecordsByPredicate(records as any, "状态 in (ACTIVE, PENDING)", entity as any);
|
||||
expect(matchIn.map((r) => r.id)).toEqual(["1", "3"]);
|
||||
});
|
||||
|
||||
test("parseSetClause 解析声明式更新赋值并映射到实体字段名", () => {
|
||||
const entity = {
|
||||
id: "e_item",
|
||||
name: "资产",
|
||||
fields: [
|
||||
{ name: "E_e_item_amount", label: "租赁费用", type: "number" },
|
||||
{ name: "E_e_item_status", label: "状态", type: "text" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const patch = parseSetClause("租赁费用 = 78787.55, 状态 = '待摊销', active = true", entity as any);
|
||||
expect(patch).toEqual({
|
||||
E_e_item_amount: 78787.55,
|
||||
E_e_item_status: "待摊销",
|
||||
active: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,11 @@ import type {
|
||||
DatalinkRecord,
|
||||
DatalinkRecordEditPayload,
|
||||
DatalinkRecordPage,
|
||||
AggregateFieldStats,
|
||||
GroupAggregateResult,
|
||||
LedgerAggregateReport,
|
||||
ContinuityIssue,
|
||||
LedgerContinuityReport,
|
||||
} from "./types.js";
|
||||
|
||||
export type { SafeRecordEditOptions } from "./api.js";
|
||||
@@ -612,3 +617,433 @@ export async function batchSafeEditRecords(
|
||||
return results;
|
||||
}
|
||||
|
||||
// ── 台账数学核对与声明式更新引擎 (Ledger Math & In-line Ops) ───────────────────
|
||||
|
||||
/**
|
||||
* 根据字段名或标签模糊解析实体字段元数据
|
||||
*/
|
||||
export function resolveEntityField(
|
||||
entity: DatalinkEntity,
|
||||
query: string
|
||||
): DatalinkField | undefined {
|
||||
const q = query.trim().toLowerCase();
|
||||
const bareQ = q.replace(/^e_[^_]+_/, "").replace(/^e_/, "");
|
||||
|
||||
return (
|
||||
entity.fields.find(
|
||||
(f) =>
|
||||
f.name.toLowerCase() === q ||
|
||||
f.label?.toLowerCase() === q ||
|
||||
f.name.toLowerCase() === `e_${entity.id.toLowerCase()}_${bareQ}` ||
|
||||
f.name.replace(/^e_[^_]+_/, "").toLowerCase() === bareQ
|
||||
) ||
|
||||
entity.fields.find((f) => f.label?.toLowerCase().includes(q))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用提取记录中某一字段的原始值
|
||||
*/
|
||||
export function extractRecordFieldValue(
|
||||
record: DatalinkRecord,
|
||||
field: DatalinkField | string
|
||||
): unknown {
|
||||
const source =
|
||||
record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink)
|
||||
? (record.dataLink as Record<string, unknown>)
|
||||
: record;
|
||||
const fieldName = typeof field === "string" ? field : field.name;
|
||||
const fieldLabel = typeof field === "string" ? undefined : field.label;
|
||||
|
||||
let val = source[fieldName] ?? record[fieldName];
|
||||
if (val === undefined && fieldLabel) {
|
||||
val = source[fieldLabel] ?? record[fieldLabel];
|
||||
}
|
||||
if (val === undefined && record.form && typeof record.form === "object") {
|
||||
val = (record.form as Record<string, unknown>)[fieldName];
|
||||
if (val === undefined && fieldLabel) {
|
||||
val = (record.form as Record<string, unknown>)[fieldLabel];
|
||||
}
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取记录中某一字段的数值(兼容数值、货币对象与格式化字符串)
|
||||
*/
|
||||
export function extractNumericFieldValue(
|
||||
record: DatalinkRecord,
|
||||
field: DatalinkField | string
|
||||
): number | null {
|
||||
const val = extractRecordFieldValue(record, field);
|
||||
if (val === null || val === undefined || val === "") return null;
|
||||
if (typeof val === "number" && !Number.isNaN(val)) return val;
|
||||
if (typeof val === "object" && !Array.isArray(val)) {
|
||||
const std = (val as any).standard ?? (val as any).amount;
|
||||
if (typeof std === "number" && !Number.isNaN(std)) return std;
|
||||
if (typeof std === "string") {
|
||||
const parsed = parseFloat(std);
|
||||
if (!Number.isNaN(parsed)) return parsed;
|
||||
}
|
||||
}
|
||||
if (typeof val === "string") {
|
||||
const clean = val.replace(/^[¥$¥\s,]+/, "").replace(/,/g, "");
|
||||
const parsed = parseFloat(clean);
|
||||
if (!Number.isNaN(parsed)) return parsed;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对记录进行聚合统计(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,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户端声明式筛选器(支持 ==, !=, >, >=, <, <=, in (...) 以及 && 组合)
|
||||
*/
|
||||
export function filterRecordsByPredicate(
|
||||
records: DatalinkRecord[],
|
||||
whereClause: string,
|
||||
entity: DatalinkEntity
|
||||
): DatalinkRecord[] {
|
||||
if (!whereClause || !whereClause.trim()) return records;
|
||||
|
||||
const conditions = whereClause
|
||||
.split(/\s+&&\s+/)
|
||||
.map((c) => c.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
return records.filter((r) => {
|
||||
return conditions.every((cond) => {
|
||||
// 1. in 操作符: field in (v1, v2, v3)
|
||||
const inMatch = cond.match(/^(.+?)\s+in\s*\((.+?)\)$/i);
|
||||
if (inMatch) {
|
||||
const fieldKey = inMatch[1].trim();
|
||||
const rawValues = inMatch[2]
|
||||
.split(",")
|
||||
.map((v) => v.trim().replace(/^['"]|['"]$/g, ""));
|
||||
const actualVal = String(extractRecordFieldValue(r, resolveEntityField(entity, fieldKey) ?? fieldKey) ?? "");
|
||||
return rawValues.some((v) => v === actualVal);
|
||||
}
|
||||
|
||||
// 2. 比较操作符: ==, !=, >=, <=, >, <, =
|
||||
const compMatch = cond.match(/^(.+?)\s*(==|!=|>=|<=|>|<|=)\s*(.+)$/);
|
||||
if (compMatch) {
|
||||
const fieldKey = compMatch[1].trim();
|
||||
const op = compMatch[2];
|
||||
const rawTarget = compMatch[3].trim().replace(/^['"]|['"]$/g, "");
|
||||
const actualRaw = extractRecordFieldValue(r, resolveEntityField(entity, fieldKey) ?? fieldKey);
|
||||
|
||||
// 数值比较
|
||||
const actualNum = extractNumericFieldValue(r, resolveEntityField(entity, fieldKey) ?? fieldKey);
|
||||
const targetNum = Number(rawTarget);
|
||||
if (actualNum !== null && !Number.isNaN(targetNum)) {
|
||||
switch (op) {
|
||||
case "==":
|
||||
case "=":
|
||||
return actualNum === targetNum;
|
||||
case "!=":
|
||||
return actualNum !== targetNum;
|
||||
case ">":
|
||||
return actualNum > targetNum;
|
||||
case ">=":
|
||||
return actualNum >= targetNum;
|
||||
case "<":
|
||||
return actualNum < targetNum;
|
||||
case "<=":
|
||||
return actualNum <= targetNum;
|
||||
}
|
||||
}
|
||||
|
||||
// 字符串/布尔比较
|
||||
const actualStr = String(actualRaw ?? "");
|
||||
switch (op) {
|
||||
case "==":
|
||||
case "=":
|
||||
return actualStr === rawTarget;
|
||||
case "!=":
|
||||
return actualStr !== rawTarget;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 --set 表达式为字段更新补丁: "租赁费用 = 78787.55, 状态 = 待摊销"
|
||||
*/
|
||||
export function parseSetClause(
|
||||
setClause: string,
|
||||
entity: DatalinkEntity
|
||||
): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = {};
|
||||
const assignments = setClause.split(",").map((s) => s.trim()).filter(Boolean);
|
||||
|
||||
for (const assign of assignments) {
|
||||
const eqIdx = assign.indexOf("=");
|
||||
if (eqIdx === -1) continue;
|
||||
const rawKey = assign.slice(0, eqIdx).trim();
|
||||
let rawVal = assign.slice(eqIdx + 1).trim();
|
||||
|
||||
// 去除外层引号
|
||||
if ((rawVal.startsWith('"') && rawVal.endsWith('"')) || (rawVal.startsWith("'") && rawVal.endsWith("'"))) {
|
||||
rawVal = rawVal.slice(1, -1);
|
||||
}
|
||||
|
||||
const field = resolveEntityField(entity, rawKey);
|
||||
const targetKey = field ? field.name : rawKey;
|
||||
|
||||
// 类型智能转换
|
||||
if (rawVal === "true") {
|
||||
result[targetKey] = true;
|
||||
} else if (rawVal === "false") {
|
||||
result[targetKey] = false;
|
||||
} else if (rawVal === "null") {
|
||||
result[targetKey] = null;
|
||||
} else if (!Number.isNaN(Number(rawVal)) && rawVal !== "") {
|
||||
result[targetKey] = Number(rawVal);
|
||||
} else {
|
||||
result[targetKey] = rawVal;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 --expect 表达式为数值基线期望列表: "租赁费用 ~= 78787.55, 日折旧费 = 2626.25 +- 0.05"
|
||||
*/
|
||||
export function parseExpectClause(
|
||||
expectClause: string
|
||||
): Array<{ field: string; targetValue: number; tolerance?: number }> {
|
||||
if (!expectClause || !expectClause.trim()) return [];
|
||||
const parts = expectClause.split(/[,;]/).map((s) => s.trim()).filter(Boolean);
|
||||
const results: Array<{ field: string; targetValue: number; tolerance?: number }> = [];
|
||||
|
||||
for (const part of parts) {
|
||||
const match = part.match(
|
||||
/^(.+?)\s*(?:~=|==|=|\:)\s*([0-9.-]+)(?:\s*(?:\+\-|\+\/\-|±|\~)\s*([0-9.]+))?$/
|
||||
);
|
||||
if (match) {
|
||||
const field = match[1].trim();
|
||||
const targetValue = parseFloat(match[2]);
|
||||
const tolerance = match[3] ? parseFloat(match[3]) : undefined;
|
||||
if (!Number.isNaN(targetValue)) {
|
||||
results.push({ field, targetValue, tolerance });
|
||||
}
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
@@ -119,3 +119,62 @@ export interface DatalinkRecordEditPayload {
|
||||
};
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
// ── 台账聚合统计与数学核对模型 ─────────────────────────────────────────────
|
||||
|
||||
export interface AggregateFieldStats {
|
||||
field: string;
|
||||
fieldLabel: string;
|
||||
count: number;
|
||||
sum: number;
|
||||
avg: number;
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
|
||||
export interface GroupAggregateResult {
|
||||
groupValue: string;
|
||||
count: number;
|
||||
aggregates: Record<string, AggregateFieldStats>;
|
||||
}
|
||||
|
||||
export interface LedgerAggregateReport {
|
||||
totalRecords: number;
|
||||
overall: Record<string, AggregateFieldStats>;
|
||||
groups?: GroupAggregateResult[];
|
||||
}
|
||||
|
||||
// ── 台账连续性与基线断层核对模型 ──────────────────────────────────────────
|
||||
|
||||
export interface ContinuityIssue {
|
||||
type: "MISSING_SEQUENCE" | "DUPLICATE_SEQUENCE" | "VALUE_OUTLIER";
|
||||
recordId?: string;
|
||||
field: string;
|
||||
message: string;
|
||||
expected?: unknown;
|
||||
actual?: unknown;
|
||||
}
|
||||
|
||||
export interface LedgerContinuityReport {
|
||||
totalRecords: number;
|
||||
sequenceSummary?: {
|
||||
field: string;
|
||||
fieldLabel: string;
|
||||
min: number;
|
||||
max: number;
|
||||
expectedCount: number;
|
||||
actualCount: number;
|
||||
missing: number[];
|
||||
duplicates: number[];
|
||||
};
|
||||
issues: ContinuityIssue[];
|
||||
outliers: Array<{
|
||||
recordId: string;
|
||||
field: string;
|
||||
fieldLabel: string;
|
||||
value: number;
|
||||
expectedValue: number;
|
||||
diff: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user