feat(platform): add streaming ndjson, stats profiling, flat normalization, and public sdk surface

This commit is contained in:
gitea committed 2026-10-15 11:00:18 +08:00
1 parent 26a6b7318c
commit 03195bbbe5
12 files changed
+649 -9

No files matched your search

+109
View File
@@ -405,4 +405,113 @@ describe("CLI - platform 命令与 record 动作", () => {
expect(execRes.stdout).toContain("已执行");
expect(editSpy).toHaveBeenCalled();
});
it("platform records 支持 --stats 画像统计(计算状态、重名与编码聚类)", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
spies.push(
spyOn(api, "searchEntityRecords").mockResolvedValue({
total: 3,
data: [
{ id: "r-1", dataLink: { id: "r-1", name: "场地A", code: "0-DT-2026-month-1", active: true } },
{ id: "r-2", dataLink: { id: "r-2", name: "场地A", code: "0-DT-2026-period-1", active: false } },
{ id: "r-3", dataLink: { id: "r-3", name: "场地B", code: "0-DT-2026-month-2", active: true } },
],
actions: [],
components: [],
path: null,
template: null,
})
);
// 1. 命令行表格输出测试
const textRes = await handlePlatformCommand(
{
area: "platform",
action: "records",
args: ["platform-1", "entity-1"],
options: { stats: true },
raw: ["platform", "records", "platform-1", "entity-1", "--stats"],
},
dummyRuntime
);
expect(textRes.exitCode).toBe(0);
expect(textRes.stdout).toContain("宏观状态与数据画像");
expect(textRes.stdout).toContain("启用 2 条");
expect(textRes.stdout).toContain("停用 1 条");
expect(textRes.stdout).toContain("N-DT-N-month-N");
// 2. JSON 结构化输出测试
const jsonRes = await handlePlatformCommand(
{
area: "platform",
action: "records",
args: ["platform-1", "entity-1"],
options: { stats: true },
raw: ["platform", "records", "platform-1", "entity-1", "--stats"],
},
{ ...dummyRuntime, jsonMode: true }
);
expect(jsonRes.exitCode).toBe(0);
const parsed = JSON.parse(jsonRes.stdout);
expect(parsed.total).toBe(3);
expect(parsed.activeCount).toBe(2);
expect(parsed.inactiveCount).toBe(1);
expect(parsed.duplicateNamesCount).toBe(1);
});
it("platform records 支持 --ndjson 流式逐行下发与 --flat 归一化", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
spies.push(
spyOn(api, "searchEntityRecords").mockResolvedValue({
total: 2,
data: [
{
id: "r-1",
dataLink: { id: "r-1", name: "项目1", code: "P1", active: true, customField: "测试值" },
},
{
id: "r-2",
dataLink: { id: "r-2", name: "项目2", code: "P2", active: false, customField: "停用值" },
},
],
actions: [],
components: [],
path: null,
template: null,
})
);
const streamedLines: string[] = [];
const writeSpy = spyOn(process.stdout, "write").mockImplementation((str: any) => {
streamedLines.push(String(str));
return true;
});
spies.push(writeSpy);
const streamRes = await handlePlatformCommand(
{
area: "platform",
action: "records",
args: ["platform-1", "entity-1"],
options: { ndjson: true },
raw: ["platform", "records", "platform-1", "entity-1", "--ndjson"],
},
dummyRuntime
);
expect(streamRes.exitCode).toBe(0);
expect(streamedLines.length).toBe(2);
const row1 = JSON.parse(streamedLines[0].trim());
expect(row1.id).toBe("r-1");
expect(row1.name).toBe("项目1");
expect(row1.code).toBe("P1");
expect(row1.active).toBe(true);
expect(row1.fields["自定义字段"]).toBe("测试值");
});
});
+3 -1
View File
@@ -28,7 +28,9 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
case "fields": return handleSchema(parsed, runtime);
case "records":
case "data":
case "search": return handleRecords(parsed, runtime);
case "search":
case "stats":
case "profile": return handleRecords(parsed, runtime);
case "audit":
case "check":
case "health": return handleAudit(parsed, runtime);
+95 -6
View File
@@ -3,8 +3,11 @@ import {
auditEntityRecords,
auditLedgerContinuityAndBaseline,
buildKeywordFilter,
calculateEntityRecordStats,
fetchAllEntityRecords,
filterRecordsByPredicate,
iterateAllEntityRecords,
normalizeDatalinkRecord,
parseExpectClause,
searchEntityRecords,
selectRecordFields,
@@ -16,19 +19,100 @@ 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 resolved = await resolveAppAndEntity(parsed, runtime);
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 filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
const whereClause = stringOption(parsed.options, ["where"]);
const sumOption = stringOption(parsed.options, ["sum", "stats", "aggregate"]);
const sumOption = stringOption(parsed.options, ["sum", "aggregate"]);
const isProfileStats = isStatsSubcommand || booleanOption(parsed.options, ["stats", "profile"], false);
const isStream = booleanOption(parsed.options, ["ndjson", "stream"], 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 = booleanOption(parsed.options, ["all", "a"], false) || Boolean(whereClause || sumOption);
const fetchAll = isAll || Boolean(whereClause || sumOption || isProfileStats);
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"]));
// 1. 高性能流式下发模式 (--ndjson / --stream,内存开销 O(pageSize),专为海量数据外部脚本管道设计)
if (isStream) {
let streamCount = 0;
const maxLimit = isAll ? Infinity : count;
for await (const rawRecord of iterateAllEntityRecords(
resolved.clients.ekbClient,
resolved.corpId,
resolved.entity.id,
{ filterBy, pageSize }
)) {
if (whereClause) {
const matched = filterRecordsByPredicate([rawRecord], whereClause, resolved.entity);
if (matched.length === 0) 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);
}
process.stdout.write(JSON.stringify(outputRecord) + "\n");
streamCount++;
if (maxLimit !== undefined && streamCount >= maxLimit) break;
}
return { stdout: "", 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 (whereClause) {
records = filterRecordsByPredicate(records, whereClause, resolved.entity);
}
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 };
}
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 });
@@ -38,7 +122,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
data = filterRecordsByPredicate(data, whereClause, resolved.entity);
}
// 1. 数学聚合核算模式 (--sum="租赁费用,日折旧费")
// 3. 数学聚合核算模式 (--sum="租赁费用,日折旧费")
if (sumOption) {
const sumFields = splitFields(sumOption);
const aggReport = aggregateRecordFields(data, resolved.entity, { fields: sumFields, groupBy });
@@ -84,7 +168,11 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
}
// 2. 常规记录查询模式
// 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));
}
@@ -92,7 +180,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
const result = {
platform: resolved.platform,
entity: resolved.entity,
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, where: whereClause, fields },
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, where: whereClause, fields, flat: isFlat },
total: page.total,
returned: data.length,
data,
@@ -114,6 +202,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${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) {
+1 -1
View File
@@ -41,7 +41,7 @@ export const HELP_REGISTRY: Record<string, HelpTopic> = {
config: { summary: "全局运行模式与路径配置", usage: "hose-use config <子命令>", commands: { paths: "诊断配置目录链", get: "查看全局配置", mode: "切换 stateful/stateless", set: "更新指定配置项" } },
workflow: { summary: "工作流查询、草稿、运行排障与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流(含禁用/SKIP/联动覆盖检查)", job: "查看单次运行实例树、报错节点与MVEL日志", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作", "--file=<workflow.json> 指定工作流快照", "--failed 只看失败节点", "--parent=<executionId> 展开循环/分支子节点", "--logs=<executionId> 查看节点执行日志"] },
bill: { summary: "单据检索、表单规格诊断与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", spec: "查看单据模板字段配置与联动覆盖规则", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
platform: { summary: "自建应用、业务对象、全量记录安全更新与台账体检", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录(支持 --all 全量拉取)", record: "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)", audit: "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)", permissions: "查看权限", imports: "查看导入任务" }, options: ["--all 自动翻页拉取全量记录", "--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作", "--raw 跳过安全合并直接发送原始补丁"] },
platform: { summary: "自建应用、业务对象、全量记录安全更新与台账体检", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录(支持 --all / --ndjson 流式 / --stats 画像)", record: "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)", audit: "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)", permissions: "查看权限", imports: "查看导入任务" }, options: ["--all 自动翻页拉取全量记录", "--ndjson 流式逐行下发 JSON Lines ($O(1)内存)", "--flat 剥离底层实体动态字段前缀并提取引用", "--stats 输出总数/启停/重名/编码规则聚类画像", "--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作", "--raw 跳过安全合并直接发送原始补丁"] },
feetype: { summary: "费用类型全生命周期管理与模板规格查询", usage: "hose-use feetype <子命令> [参数]", commands: { list: "查看费用类型树", get: "查看详情与字段", spec: "查看单据/申请模板字段与联动规则", create: "新建费用类型", update: "修改属性", disable: "停用", enable: "启用", move: "移动层级", fields: "查看字段配置" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
rule: { summary: "本地审批规约管理", usage: "hose-use rule <子命令> [参数]", commands: { scopes: "列出适用场景", scope: "查看场景明细", list: "列出规则", get: "查看规则详情", add: "新增规则", delete: "删除规则" }, options: ["--dry-run 只预览增删", "--yes/--confirm 确认增删"] },
approval: { summary: "确定性审批网关与要点仲裁", usage: "hose-use approval audit <子命令> [单号]", commands: { points: "查看审核要点", checklist: "查看核验清单", review: "核验事实", decide: "生成或执行仲裁决定" }, options: ["--apply --yes 执行真实审批流转"] },
+29 -1
View File
@@ -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);
// 执行业务逻辑...
}
```
+106
View File
@@ -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);
});
});
+220
View File
@@ -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;
+32
View File
@@ -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;
}
+45
View File
@@ -0,0 +1,45 @@
/**
* hose-use SDK: 针对脚本编写、自动化批处理与外部 Agent 集成的标准公共 API 界面。
* 彻底消除外部脚本对内部私有路径和动态字段报文结构的直接依赖。
*/
export { initCorpRuntime, createClientsForCorp, requireSelectedCorp } from "./cli/helpers.js";
export { resolveCorpConfig } from "./core/config/manager.js";
// DataLink / 自建应用与业务对象能力
export {
listPlatforms,
listAllPlatforms,
getPlatform,
resolvePlatform,
listPlatformEntities,
resolveEntity,
searchEntityRecords,
fetchAllEntityRecords,
iterateAllEntityRecords,
normalizeDatalinkRecord,
calculateEntityRecordStats,
auditEntityRecords,
aggregateRecordFields,
filterRecordsByPredicate,
batchSafeEditRecords,
editRecord,
safeEditRecord,
getRecordDetail,
toggleRecordState,
} from "./domains/datalink/services.js";
export type {
DatalinkPlatformDetail,
DatalinkEntity,
DatalinkField,
DatalinkRecord,
NormalizedDatalinkRecord,
DatalinkRecordStats,
LedgerAggregateReport,
} from "./domains/datalink/types.js";
export type {
DatalinkAuditReport,
BatchEditTargetItem,
} from "./domains/datalink/services.js";