feat(platform): add streaming ndjson, stats profiling, flat normalization, and public sdk surface
This commit is contained in:
1 parent
26a6b7318c
commit
03195bbbe5
12 files changed
+649
-9
No files matched your search
@@ -30,7 +30,7 @@ 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 <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>]
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--all] [--keyword <关键词>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats]
|
||||
hose-use platform record get [<应用> <业务对象>] <记录ID>
|
||||
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> [--set="字段=值" | --data='{"field": "val"}'] [--raw] [--dry-run|--yes]
|
||||
@@ -44,6 +44,9 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
|
||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||
|
||||
- `records --ndjson`(或 `--stream`):针对万级~十万级海量记录,采用 AsyncGenerator 分页流式生成,逐行向 `stdout` 发射 NDJSON。内存恒定为 $O(\text{pageSize})$,严防大报文撑爆内存或终端,无缝对接下游 `jq`、Python 处理流水线。
|
||||
- `records --stats`(或 `records stats <应用> <对象>` / `records profile`):宏观结构与特征聚类画像。输出总记录数、启用/停用分布及占比、唯一标题数与重名分布、编码生成规则聚类(自动提取 `${groupIndex}-${formCode}-month-${idx}` 等动态模板分布)、最早与最新维护时间,毫秒级洞察数据特征。
|
||||
- `records --flat`:自动剥离底层动态物理前缀(如 `E_<entityId>_`),提取关联引用对象的名称/编码,将复杂元数据规整为 `{ id, code, name, active, createTime, updateTime, fields }` 干净对象。
|
||||
- `records --sum="字段1,字段2" [--group-by="分组字段"]`:台账数学聚合核算,自动解析纯数值、金额对象(`{ standard: 100 }`)与货币符号字符串(`¥12,500.00`),输出样本数、总合计(SUM)、均值(AVG)、最小值(MIN)、最大值(MAX)以及指定字段的分组小计。
|
||||
- `records --where="条件"`:支持在客户端按字段中文标签或物理名做声明式组合过滤(支持 `==`, `!=`, `>`, `<`, `>=`, `<=`, `in (...)`, 以及 `&&` 联合条件)。
|
||||
- `audit --check-continuous="序号字段"`:台账连续性体检,精准识别期数序号序列中的断层缺失(MISSING)与重号重复(DUPLICATE)。
|
||||
@@ -54,3 +57,28 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
- `records --all` 自动按 `500` 条/页循环拉取全量台账记录。
|
||||
- `audit` 一键巡检必填/指定字段缺失、引用已停用档案以及跨台账同名字段同步差异,并输出 `suggestedPatches`。
|
||||
|
||||
## 公共 SDK (`hose-use/sdk`)
|
||||
|
||||
对于需要针对十万级业务记录编写个性化业务循环、分析或报表导出的脚本,直接通过 `hose-use/sdk` 引入标准公共 API,彻底告别依赖 CLI 内部文件路径:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
initCorpRuntime,
|
||||
resolvePlatform,
|
||||
resolveEntity,
|
||||
iterateAllEntityRecords,
|
||||
normalizeDatalinkRecord,
|
||||
calculateEntityRecordStats,
|
||||
} from "hose-use/sdk";
|
||||
|
||||
const runtime = await initCorpRuntime();
|
||||
const platform = await resolvePlatform(runtime.clients.ekbClient, "新转转集团");
|
||||
const entity = await resolveEntity(runtime.clients.ekbClient, platform.id, "合同");
|
||||
|
||||
// 1. 万级海量数据 $O(1)$ 内存流式遍历
|
||||
for await (const rawRecord of iterateAllEntityRecords(runtime.clients.ekbClient, runtime.corpId, entity.id, { pageSize: 200 })) {
|
||||
const record = normalizeDatalinkRecord(rawRecord, entity);
|
||||
// 执行业务逻辑...
|
||||
}
|
||||
```
|
||||
|
||||
@@ -16,8 +16,11 @@ import {
|
||||
auditLedgerContinuityAndBaseline,
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
calculateEntityRecordStats,
|
||||
fetchAllEntityRecords,
|
||||
filterRecordsByPredicate,
|
||||
iterateAllEntityRecords,
|
||||
normalizeDatalinkRecord,
|
||||
parseExpectClause,
|
||||
parseSetClause,
|
||||
selectRecordFields,
|
||||
@@ -531,5 +534,108 @@ describe("DataLink Domain - 应用、业务对象与记录查询", () => {
|
||||
active: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("normalizeDatalinkRecord 自动提取主键 ID、名称、编码并剥离动态前缀", () => {
|
||||
const entity = {
|
||||
id: "e816139ba5e1cd4ae3c0",
|
||||
name: "摊销明细",
|
||||
fields: [
|
||||
{ name: "E_e816139ba5e1cd4ae3c0_code", label: "编码", type: "text" },
|
||||
{ name: "E_e816139ba5e1cd4ae3c0_name", label: "名称", type: "text" },
|
||||
{ name: "E_e816139ba5e1cd4ae3c0_rent", label: "当期租金", type: "money" },
|
||||
{ name: "E_e816139ba5e1cd4ae3c0_vendor", label: "供应商", type: "ref" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const rawRecord = {
|
||||
dataLink: {
|
||||
id: "ID01UsDobfXRRZ",
|
||||
active: false,
|
||||
createTime: 1780000000000,
|
||||
updateTime: 1789000000000,
|
||||
E_e816139ba5e1cd4ae3c0_code: "0-DT-2026-month-1",
|
||||
E_e816139ba5e1cd4ae3c0_name: "使用权资产摊销-北京仓",
|
||||
E_e816139ba5e1cd4ae3c0_rent: { standard: "42680.54", standardUnit: "元" },
|
||||
E_e816139ba5e1cd4ae3c0_vendor: { name: "博展科技" },
|
||||
},
|
||||
};
|
||||
|
||||
const norm = normalizeDatalinkRecord(rawRecord as any, entity as any);
|
||||
expect(norm.id).toBe("ID01UsDobfXRRZ");
|
||||
expect(norm.active).toBe(false);
|
||||
expect(norm.code).toBe("0-DT-2026-month-1");
|
||||
expect(norm.name).toBe("使用权资产摊销-北京仓");
|
||||
expect(norm.fields["当期租金"]).toBe("42680.54");
|
||||
expect(norm.fields["供应商"]).toBe("博展科技");
|
||||
});
|
||||
|
||||
test("calculateEntityRecordStats 准确统计启用率、重名交叉与编码结构聚类", () => {
|
||||
const entity = {
|
||||
id: "e_test",
|
||||
name: "测试对象",
|
||||
fields: [
|
||||
{ name: "code", label: "编码", type: "text" },
|
||||
{ name: "name", label: "名称", type: "text" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const records = [
|
||||
{ id: "1", code: "0-DT-20260831-0001-month-1", name: "北京仓", active: true, createTime: 1000, updateTime: 2000 },
|
||||
{ id: "2", code: "0-DT-20260831-0001-month-2", name: "北京仓", active: true, createTime: 1000, updateTime: 3000 },
|
||||
{ id: "3", code: "0-DT-20260831-0001-period-1", name: "北京仓", active: false, createTime: 1000, updateTime: 2500 },
|
||||
{ id: "4", code: "0-DT-20260831-0002-month-1", name: "上海仓", active: false, createTime: 1200, updateTime: 2200 },
|
||||
];
|
||||
|
||||
const stats = calculateEntityRecordStats(records as any, entity as any, 4);
|
||||
expect(stats.total).toBe(4);
|
||||
expect(stats.activeCount).toBe(2);
|
||||
expect(stats.inactiveCount).toBe(2);
|
||||
expect(stats.activeRate).toBe("50.0%");
|
||||
expect(stats.uniqueNames).toBe(2);
|
||||
expect(stats.duplicateNamesCount).toBe(1); // "北京仓" 出现 3 次
|
||||
expect(stats.mixedStatusNamesCount).toBe(1); // "北京仓" 同时含启用与停用
|
||||
expect(stats.codePatterns).toHaveLength(2);
|
||||
expect(stats.codePatterns[0].count).toBe(3); // 3 条 month
|
||||
expect(stats.codePatterns[1].count).toBe(1); // 1 条 period
|
||||
});
|
||||
|
||||
test("iterateAllEntityRecords 支持跨页逐条流式下发", async () => {
|
||||
let callCount = 0;
|
||||
const mockClient = {
|
||||
post: () => ({
|
||||
json: async () => {
|
||||
callCount++;
|
||||
if (callCount === 1) {
|
||||
return {
|
||||
items: {
|
||||
total: 3,
|
||||
data: [{ id: "rec-1" }, { id: "rec-2" }],
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
items: {
|
||||
total: 3,
|
||||
data: [{ id: "rec-3" }],
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
const stream = iterateAllEntityRecords(mockClient as any, "corp-1", "entity-1", { pageSize: 2 });
|
||||
const collected: string[] = [];
|
||||
for await (const record of stream) {
|
||||
collected.push(record.id!);
|
||||
}
|
||||
|
||||
expect(collected).toEqual(["rec-1", "rec-2", "rec-3"]);
|
||||
expect(callCount).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ import type {
|
||||
LedgerAggregateReport,
|
||||
ContinuityIssue,
|
||||
LedgerContinuityReport,
|
||||
NormalizedDatalinkRecord,
|
||||
DatalinkRecordStats,
|
||||
} from "./types.js";
|
||||
|
||||
export type { SafeRecordEditOptions } from "./api.js";
|
||||
@@ -170,6 +172,224 @@ export async function fetchAllEntityRecords(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 流式异步迭代器:逐页拉取并逐条产出业务对象记录。
|
||||
* 内存开销恒定为 O(pageSize),可直接支持 10 万+ 级海量数据的流式下发与外部管道消费。
|
||||
*/
|
||||
export async function* iterateAllEntityRecords(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string,
|
||||
options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {}
|
||||
): AsyncGenerator<DatalinkRecord, void, unknown> {
|
||||
const pageSize = Math.max(1, Math.min(options.pageSize ?? 500, 1000));
|
||||
let start = 0;
|
||||
let total = 0;
|
||||
let yielded = 0;
|
||||
|
||||
while (true) {
|
||||
const page = await api.searchEntityRecords(client, corpId, entityId, {
|
||||
start,
|
||||
count: pageSize,
|
||||
filterBy: options.filterBy,
|
||||
orderBy: options.orderBy,
|
||||
});
|
||||
total = page.total;
|
||||
if (page.data.length === 0) break;
|
||||
for (const record of page.data) {
|
||||
yield record;
|
||||
yielded++;
|
||||
}
|
||||
start += page.data.length;
|
||||
if (yielded >= total || page.data.length < pageSize) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将数据互联原始报文规范化为标准、扁平、脱敏于动态前缀的结构。
|
||||
* 彻底消除 r.id vs r.dataLink.id 以及 E_<entityId>_ 动态前缀的困扰。
|
||||
*/
|
||||
export function normalizeDatalinkRecord(
|
||||
rawRecord: DatalinkRecord,
|
||||
entity?: DatalinkEntity,
|
||||
options: { includeRaw?: boolean } = {}
|
||||
): NormalizedDatalinkRecord {
|
||||
const dl =
|
||||
rawRecord.dataLink && typeof rawRecord.dataLink === "object" && !Array.isArray(rawRecord.dataLink)
|
||||
? (rawRecord.dataLink as Record<string, unknown>)
|
||||
: (rawRecord as Record<string, unknown>);
|
||||
|
||||
const entityId = String(entity?.id ?? dl.entityId ?? rawRecord.entityId ?? "");
|
||||
const bareEntityId = entityId.startsWith("$") ? entityId.slice(1) : entityId;
|
||||
|
||||
const id = String(dl.id ?? rawRecord.id ?? "");
|
||||
const active = (dl.active ?? rawRecord.active) !== false;
|
||||
const createTime = (dl.createTime ?? rawRecord.createTime ?? null) as number | null;
|
||||
const updateTime = (dl.updateTime ?? rawRecord.updateTime ?? null) as number | null;
|
||||
|
||||
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 name = String(
|
||||
dl.name ??
|
||||
dl["名称"] ??
|
||||
(nameField ? dl[nameField.name] : undefined) ??
|
||||
(bareEntityId ? dl[`E_${bareEntityId}_name`] : undefined) ??
|
||||
""
|
||||
);
|
||||
|
||||
const code = String(
|
||||
dl.code ??
|
||||
dl["编码"] ??
|
||||
(codeField ? dl[codeField.name] : undefined) ??
|
||||
(bareEntityId ? dl[`E_${bareEntityId}_code`] : undefined) ??
|
||||
""
|
||||
);
|
||||
|
||||
const fields: Record<string, unknown> = {};
|
||||
if (entity?.fields) {
|
||||
for (const field of entity.fields) {
|
||||
if (field.name === nameField?.name || field.name === codeField?.name) continue;
|
||||
const keyCandidates = [
|
||||
field.name,
|
||||
bareEntityId ? `E_${bareEntityId}_${field.name}` : undefined,
|
||||
field.label,
|
||||
].filter(Boolean) as string[];
|
||||
|
||||
let val: unknown = undefined;
|
||||
for (const key of keyCandidates) {
|
||||
if (key in dl) {
|
||||
val = dl[key];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (val !== undefined && val !== null) {
|
||||
if (typeof val === "object" && !Array.isArray(val)) {
|
||||
const obj = val as Record<string, unknown>;
|
||||
if ("standard" in obj) {
|
||||
val = obj.standard;
|
||||
} else if ("name" in obj && typeof obj.name === "string") {
|
||||
val = obj.name;
|
||||
} else if ("dataLink" in obj && typeof obj.dataLink === "object" && obj.dataLink) {
|
||||
const nested = obj.dataLink as Record<string, unknown>;
|
||||
const subEntityId = String(obj.entityId || "");
|
||||
const subBareId = subEntityId.startsWith("$") ? subEntityId.slice(1) : subEntityId;
|
||||
const subName = nested.name ?? nested["名称"] ?? nested[`E_${subBareId}_name`];
|
||||
const subCode = nested.code ?? nested["编码"] ?? nested[`E_${subBareId}_code`];
|
||||
val = subName || subCode || obj.id || val;
|
||||
}
|
||||
}
|
||||
fields[field.label || field.name] = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
code,
|
||||
name,
|
||||
active,
|
||||
createTime,
|
||||
updateTime,
|
||||
fields,
|
||||
...(options.includeRaw ? { raw: rawRecord } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算业务对象记录的轻量级宏观分布画像(统计总数、启用/停用数、重名率、编码前缀聚类等)。
|
||||
* 既可接收全量内存数组,也可配合流式生成器在 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;
|
||||
|
||||
@@ -178,3 +178,35 @@ export interface LedgerContinuityReport {
|
||||
}>;
|
||||
}
|
||||
|
||||
// ── 归一化记录与统计画像模型 ───────────────────────────────────────────────
|
||||
|
||||
export interface NormalizedDatalinkRecord {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
active: boolean;
|
||||
createTime?: number | null;
|
||||
updateTime?: number | null;
|
||||
fields: Record<string, unknown>;
|
||||
raw?: DatalinkRecord;
|
||||
}
|
||||
|
||||
export interface DatalinkRecordStats {
|
||||
total: number;
|
||||
activeCount: number;
|
||||
inactiveCount: number;
|
||||
activeRate: string;
|
||||
uniqueNames: number;
|
||||
duplicateNamesCount: number;
|
||||
mixedStatusNamesCount: number;
|
||||
codePatterns: Array<{
|
||||
pattern: string;
|
||||
sample: string;
|
||||
count: number;
|
||||
activeCount: number;
|
||||
inactiveCount: number;
|
||||
}>;
|
||||
earliestCreateTime?: string | null;
|
||||
latestUpdateTime?: string | null;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user