diff --git a/src/cli/commands/platform.test.ts b/src/cli/commands/platform.test.ts index eb53e25..82ef4ce 100644 --- a/src/cli/commands/platform.test.ts +++ b/src/cli/commands/platform.test.ts @@ -255,4 +255,154 @@ describe("CLI - platform 命令与 record 动作", () => { expect(res.stdout).toContain("Dry-Run 预览"); expect(editSpy).not.toHaveBeenCalled(); }); + + it("platform records 支持 --sum 数学核算与 --group-by 分组统计", 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, + fields: [ + { name: "fee", label: "租赁费用", type: "money" }, + { name: "status", label: "状态", type: "text" }, + ], + } as any)); + spies.push( + spyOn(services, "fetchAllEntityRecords").mockResolvedValue({ + data: [ + { id: "1", fee: 1000, status: "A" }, + { id: "2", fee: 2000, status: "A" }, + { id: "3", fee: 3000, status: "B" }, + ], + total: 3, + actions: [], + components: [], + path: null, + template: null, + }) + ); + + const res = await handlePlatformCommand( + { + area: "platform", + action: "records", + args: ["platform-1", "entity-1"], + options: { sum: "租赁费用", "group-by": "状态" }, + raw: ["platform", "records", "platform-1", "entity-1", "--sum=租赁费用", "--group-by=状态"], + }, + dummyRuntime + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("台账数学聚合核算"); + expect(res.stdout).toContain("总合计 (SUM)"); + expect(res.stdout).toContain("6000"); + expect(res.stdout).toContain("按 [状态] 分组统计"); + }); + + it("platform audit 支持 --check-continuous 与 --expect 基线离群诊断", 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, + fields: [ + { name: "seq", label: "摊销序号", type: "number" }, + { name: "fee", label: "租赁费用", type: "money" }, + ], + } as any)); + spies.push( + spyOn(services, "fetchAllEntityRecords").mockResolvedValue({ + data: [ + { id: "1", seq: 1, fee: 78787.55 }, + { id: "2", seq: 3, fee: 0 }, + ], + total: 2, + actions: [], + components: [], + path: null, + template: null, + }) + ); + + const res = await handlePlatformCommand( + { + area: "platform", + action: "audit", + args: ["platform-1", "entity-1"], + options: { "check-continuous": "摊销序号", expect: "租赁费用 ~= 78787.55" }, + raw: ["platform", "audit", "platform-1", "entity-1", "--check-continuous=摊销序号", "--expect=租赁费用 ~= 78787.55"], + }, + dummyRuntime + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("台账序号连续性体检"); + expect(res.stdout).toContain("断层缺失期数 (MISSING)"); + expect(res.stdout).toContain("缺少 [2]"); + expect(res.stdout).toContain("基线离群异常核对"); + expect(res.stdout).toContain("偏离差额"); + }); + + it("platform update 支持 --where 声明式筛选与 --set 原地修改(含 --dry-run 与 --yes)", 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, + fields: [ + { name: "fee", label: "租赁费用", type: "money" }, + { name: "status", label: "状态", type: "text" }, + ], + } as any)); + spies.push( + spyOn(services, "fetchAllEntityRecords").mockResolvedValue({ + data: [ + { id: "r-1", fee: 0, status: "PENDING" }, + { id: "r-2", fee: 78787.55, status: "DONE" }, + ], + total: 2, + actions: [], + components: [], + path: null, + template: null, + }) + ); + + spies.push( + spyOn(api, "getRecordDetail").mockResolvedValue({ + dataLink: { id: "r-1", active: true, fee: 0, status: "PENDING" }, + }) + ); + const editSpy = spyOn(api, "editRecord").mockResolvedValue({ id: "r-1" } as any); + spies.push(editSpy); + + // 1. Dry-run 模式测试 + const dryRes = await handlePlatformCommand( + { + area: "platform", + action: "update", + args: ["platform-1", "entity-1"], + options: { where: "租赁费用 == 0", set: "租赁费用 = 78787.55", "dry-run": true }, + raw: ["platform", "update", "platform-1", "entity-1", "--where=租赁费用 == 0", "--set=租赁费用 = 78787.55", "--dry-run"], + }, + dummyRuntime + ); + expect(dryRes.exitCode).toBe(0); + expect(dryRes.stdout).toContain("Dry-Run 预览"); + expect(dryRes.stdout).toContain("r-1"); + expect(editSpy).not.toHaveBeenCalled(); + + // 2. 真实确认执行测试 (--yes) + const execRes = await handlePlatformCommand( + { + area: "platform", + action: "update", + args: ["platform-1", "entity-1"], + options: { where: "租赁费用 == 0", set: "租赁费用 = 78787.55", yes: true }, + raw: ["platform", "update", "platform-1", "entity-1", "--where=租赁费用 == 0", "--set=租赁费用 = 78787.55", "--yes"], + }, + dummyRuntime + ); + expect(execRes.exitCode).toBe(0); + expect(execRes.stdout).toContain("已执行"); + expect(editSpy).toHaveBeenCalled(); + }); }); diff --git a/src/cli/commands/platform/index.ts b/src/cli/commands/platform/index.ts index 3c7dee5..f46fe14 100644 --- a/src/cli/commands/platform/index.ts +++ b/src/cli/commands/platform/index.ts @@ -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": diff --git a/src/cli/commands/platform/record-actions.ts b/src/cli/commands/platform/record-actions.ts index 93dac1e..c8d2377 100644 --- a/src/cli/commands/platform/record-actions.ts +++ b/src/cli/commands/platform/record-actions.ts @@ -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= | --filter=) (--data='' | --file=) [--concurrency=8] [--dry-run] [--yes]" + "用法: hose-use platform record batch-edit <应用> <业务对象> (--where='' | --ids= | --filter=) (--set='' | --data='' | --file=) [--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='' 或 --file= 提供要批量更新的字段内容"); + if (!dataStr && !filePath && !setClause) { + throw new Error("请通过 --set='字段=值'、--data='' 或 --file= 提供要批量更新的字段内容"); } requireMutationConfirmation( @@ -170,7 +174,9 @@ async function handleBatchEdit( } let uniformPatch: Record | undefined; - if (dataStr) { + if (setClause) { + uniformPatch = parseSetClause(setClause, resolved.entity); + } else if (dataStr) { try { uniformPatch = JSON.parse(dataStr) as Record; } 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= 或 --filter=<表达式> 指定要批量更新的目标记录"); + if (whereClause) { + return { + stdout: `未找到符合条件 [--where="${whereClause}"] 的记录,无需更新。\n`, + stderr: "", + exitCode: 0, + }; + } + throw new Error("请通过 --where=<条件>、--ids= 或 --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); diff --git a/src/cli/commands/platform/records.ts b/src/cli/commands/platform/records.ts index 2485fc4..44262d0 100644 --- a/src/cli/commands/platform/records.ts +++ b/src/cli/commands/platform/records.ts @@ -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> = 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> = []; + 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 => { @@ -51,10 +117,14 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): export async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): Promise { 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, }; } + diff --git a/src/domains/datalink/README.datalink.md b/src/domains/datalink/README.datalink.md index 3c5d1ed..ecc33ab 100644 --- a/src/domains/datalink/README.datalink.md +++ b/src/domains/datalink/README.datalink.md @@ -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__*` 字段、将嵌套引用对象归一化为字符串 ID、保留 `active` 与 `visibility` 结构,支持字段短名/中文标签映射);仅当显式传入 `--raw` 时才直接透传原始补丁。 - `records --all` 自动按 `500` 条/页循环拉取全量台账记录。 - `audit` 一键巡检必填/指定字段缺失、引用已停用档案以及跨台账同名字段同步差异,并输出 `suggestedPatches`。 + diff --git a/src/domains/datalink/datalink.test.ts b/src/domains/datalink/datalink.test.ts index f04b474..8c0d4b5 100644 --- a/src/domains/datalink/datalink.test.ts +++ b/src/domains/datalink/datalink.test.ts @@ -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, + }); + }); }); diff --git a/src/domains/datalink/services.ts b/src/domains/datalink/services.ts index e56b0ba..4f0518e 100644 --- a/src/domains/datalink/services.ts +++ b/src/domains/datalink/services.ts @@ -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) + : 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)[fieldName]; + if (val === undefined && fieldLabel) { + val = (record.form as Record)[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 => { + const stats: Record = {}; + 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(); + 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(); + 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 { + const result: Record = {}; + 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; +} diff --git a/src/domains/datalink/types.ts b/src/domains/datalink/types.ts index 0ad1ce4..cbfa5e7 100644 --- a/src/domains/datalink/types.ts +++ b/src/domains/datalink/types.ts @@ -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; +} + +export interface LedgerAggregateReport { + totalRecords: number; + overall: Record; + 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; + }>; +} +