import type { KyInstance } from "ky"; import * as api from "./api.js"; import { ValidationError } from "../../../core/errors.js"; import { resolveDatalinkField } from "./fields.js"; import type { DatalinkEntity, DatalinkField, DatalinkRecord, DatalinkRecordEditPayload, DatalinkRecordPage, AggregateFieldStats, GroupAggregateResult, LedgerAggregateReport, ContinuityIssue, LedgerContinuityReport, NormalizedDatalinkRecord, DatalinkRecordStats } from "./types.js"; import type { DatalinkPlatformDetail } from "../applications/types.js"; export type { SafeRecordEditOptions } from "./api.js"; export function listPlatformEntities(...args: Parameters) { return api.listPlatformEntities(...args); } export function searchEntityRecords(...args: Parameters) { return api.searchEntityRecords(...args); } export function listImportJobs(...args: Parameters) { return api.listImportJobs(...args); } export function getImportResult(...args: Parameters) { return api.getImportResult(...args); } export function toggleRecordState(...args: Parameters) { return api.toggleRecordState(...args); } export function getRecordDetail(...args: Parameters) { return api.getRecordDetail(...args); } export function getRecordFormSchema(...args: Parameters) { return api.getRecordFormSchema(...args); } export function editRecord(...args: Parameters) { return api.editRecord(...args); } export function buildSafeRecordEditPayload(...args: Parameters) { return api.buildSafeRecordEditPayload(...args); } export function safeEditRecord(...args: Parameters) { return api.safeEditRecord(...args); } export function recomputeRecordLedger(...args: Parameters) { return api.recomputeRecordLedger(...args); } function matches(value: unknown, target: string): boolean { return typeof value === "string" && value.toLowerCase() === target.toLowerCase(); } export async function resolveEntity( client: KyInstance, corpId: string, platform: DatalinkPlatformDetail, target: string ): Promise { const entities = await api.listPlatformEntities(client, corpId, platform.id); return entities.find((entity) => [entity.id, entity.name, entity.code].some((value) => matches(value, target)) ); } export interface BuildKeywordFilterOptions { entity?: DatalinkEntity; searchFields?: string[]; } /** * 格式化服务端 filterBy 字段表达式。 * 针对 DataLink 特性: * - 动态业务字段(E_ 前缀)自动附加 form. 命名空间 * - money 货币复合对象自动下钻到 .standard 标准字符串 * - number 数值字段支持比较运算符 */ export function formatServerFieldExpr( fieldKey: string, op: string, rawVal: string, entity?: DatalinkEntity ): string { const resolved = entity ? resolveEntityField(entity, fieldKey) : undefined; const targetKey = resolved?.name || fieldKey; const isCustom = targetKey.startsWith("E_"); const serverPath = isCustom ? `form.${targetKey}` : targetKey; const escaped = rawVal.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); const isNumericString = !Number.isNaN(Number(rawVal)) && rawVal.trim() !== ""; // Money 字段 (服务端为 { standard: "100.00", standardUnit: "元", ... }) if (resolved?.type === "money") { const moneyPath = `${serverPath}.standard`; const num = Number(rawVal); const withDec = !Number.isNaN(num) && !rawVal.includes("../../datalink") ? `${rawVal}.00` : rawVal; if (op === "=" || op === "==") { if (withDec !== rawVal) { return `(${moneyPath}=="${escaped}"||${moneyPath}=="${withDec}")`; } return `${moneyPath}=="${escaped}"`; } if (op === "!=") { return `${moneyPath}!="${escaped}"`; } return `${moneyPath}.containsIgnoreCase("${escaped}")`; } // Number 字段 if (resolved?.type === "number" || (isNumericString && op !== "~" && op !== "=~" && op !== ":")) { if (op === "~" || op === "=~" || op === ":") { return `${serverPath}.containsIgnoreCase("${escaped}")`; } const cmp = op === "=" ? "==" : op; return `${serverPath}${cmp}${rawVal}`; } // Text / Ref / Other 字段 if (op === "~" || op === "=~" || op === ":") { return `${serverPath}.containsIgnoreCase("${escaped}")`; } if (op === "!=") { return `${serverPath}!="${escaped}"`; } return `${serverPath}=="${escaped}"`; } export function buildKeywordFilter( keyword: string, options?: BuildKeywordFilterOptions ): string { const escaped = keyword.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); const conds: string[] = [ `name.containsIgnoreCase("${escaped}")`, `code.containsIgnoreCase("${escaped}")`, ]; if (options?.entity && options.searchFields && options.searchFields.length > 0) { for (const searchField of options.searchFields) { const resolved = resolveEntityField(options.entity, searchField); const targetName = resolved?.name || searchField; if (targetName && targetName !== "name" && targetName !== "code") { const expr = formatServerFieldExpr(targetName, "~", keyword, options.entity); conds.push(expr); } } } return `(${conds.join("||")})&&(active.in(true,false))`; } /** * 将字段过滤表达式解析并转换为 DataLink 服务端原生 filterBy 语法。 * 支持透传原生 DSL,或智能解析 "字段~值"、"字段=值"、"字段!=值" 并结合元数据映射为物理 Key。 */ export function buildServerFieldFilter( filterInput: string, entity?: DatalinkEntity ): string { const trimmed = filterInput.trim(); if ( trimmed.startsWith("(") || trimmed.includes(".containsIgnoreCase(") || trimmed.includes(".in(") || trimmed.includes("==") ) { return trimmed; } // 解析 key-value: 如 "客户名称~猫子"、"不含税金额=191700"、"状态!=停用" const match = trimmed.match(/^([^=~:!]+)\s*(=~|==|!=|~|:|=)\s*(.+)$/); if (!match) return trimmed; const rawKey = match[1].trim(); const op = match[2]; const rawVal = match[3].trim().replace(/^["']|["']$/g, ""); const expr = formatServerFieldExpr(rawKey, op, rawVal, entity); return expr ? `(${expr})&&(active.in(true,false))` : trimmed; } export function selectRecordFields( record: Record, fields: string[], definitions: DatalinkField[] = [] ): Record { if (fields.length === 0) return record; const dataLink = record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink) ? (record.dataLink as Record) : record; const selected: Record = {}; const normalizedFields = record.fields && typeof record.fields === "object" && !Array.isArray(record.fields) ? record.fields as Record : undefined; for (const selector of fields) { const definition = definitions.find( (field) => field.name === selector || field.label === selector ); const sourceName = definition?.name ?? selector; const label = definition?.label || selector; if (sourceName in dataLink) selected[label] = dataLink[sourceName]; else if (normalizedFields && label in normalizedFields) selected[label] = normalizedFields[label]; else if (normalizedFields && sourceName in normalizedFields) selected[label] = normalizedFields[sourceName]; else if (normalizedFields) { const systemName = sourceName.replace(/^E_.+_/, ""); if (["name", "code"].includes(systemName) && systemName in record) selected[label] = record[systemName]; } } return record.dataLink && typeof record.dataLink === "object" ? { ...record, dataLink: selected } : selected; } /** * 自动分页全量拉取指定业务对象的全部记录(默认每页 500 条循环直到底)。 */ export async function fetchAllEntityRecords( client: KyInstance, corpId: string, entityId: string, options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {} ): Promise { const pageSize = Math.max(1, Math.min(options.pageSize ?? 500, 1000)); let start = 0; let total = 0; const allData: DatalinkRecord[] = []; let firstPage: DatalinkRecordPage | undefined; while (true) { const page = await api.searchEntityRecords(client, corpId, entityId, { start, count: pageSize, filterBy: options.filterBy, orderBy: options.orderBy, }); firstPage ??= page; total = page.total; if (page.data.length === 0) break; allData.push(...page.data); start += page.data.length; if (allData.length >= total || page.data.length < pageSize) { break; } } return { total: Math.max(total, allData.length), data: allData, actions: firstPage?.actions ?? [], components: firstPage?.components ?? [], path: firstPage?.path, template: firstPage?.template, }; } /** * 流式异步迭代器:逐页拉取并逐条产出业务对象记录。 * 内存开销恒定为 O(pageSize),可直接支持 10 万+ 级海量数据的流式下发与外部管道消费。 */ export async function* iterateAllEntityRecords( client: KyInstance, corpId: string, entityId: string, options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {} ): AsyncGenerator { 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__ 动态前缀的困扰。 */ 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) : (rawRecord as Record); 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 = {}; 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; if ("standard" in obj) { val = obj.standard; } else if ("name" in obj && typeof obj.name === "string" && obj.name) { val = obj.name; } else { let targetDataLink: Record | undefined = undefined; if ("dataLink" in obj && typeof obj.dataLink === "object" && obj.dataLink) { targetDataLink = obj.dataLink as Record; } else if ("data" in obj && typeof obj.data === "object" && obj.data && "dataLink" in (obj.data as Record)) { targetDataLink = (obj.data as Record).dataLink as Record; } if (targetDataLink) { const form = (targetDataLink.form && typeof targetDataLink.form === "object" ? targetDataLink.form : {}) as Record; const combined = { ...targetDataLink, ...form }; let subDisplay: string | undefined = undefined; for (const [k, v] of Object.entries(combined)) { if (typeof v === "string" && v.trim() && (k === "name" || k === "title" || k === "名称" || k === "标题" || k.endsWith("_name") || k.endsWith("_title"))) { subDisplay = v; break; } } if (!subDisplay) { for (const [k, v] of Object.entries(combined)) { if (typeof v === "string" && v.trim() && (k === "code" || k === "编码" || k.endsWith("_code") || k.includes("编号"))) { subDisplay = v; break; } } } val = subDisplay || (targetDataLink.id ? String(targetDataLink.id) : undefined) || (obj.id ? String(obj.id) : undefined); } else if (obj.id && typeof obj.id === "string") { val = obj.id; } } } 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, entity?: DatalinkEntity, explicitTotal?: number ): DatalinkRecordStats { let total = 0; let activeCount = 0; let inactiveCount = 0; const namesMap = new Map(); const patternsMap = new Map(); let earliestCreate: number | null = null; let latestUpdate: number | null = null; for (const raw of records) { total++; const norm = normalizeDatalinkRecord(raw, entity); if (norm.active) activeCount++; else inactiveCount++; if (norm.createTime && typeof norm.createTime === "number") { if (earliestCreate === null || norm.createTime < earliestCreate) earliestCreate = norm.createTime; } if (norm.updateTime && typeof norm.updateTime === "number") { if (latestUpdate === null || norm.updateTime > latestUpdate) latestUpdate = norm.updateTime; } // 统计名称重名与状态交叉 if (norm.name) { if (!namesMap.has(norm.name)) { namesMap.set(norm.name, { total: 0, active: 0, inactive: 0 }); } const nStats = namesMap.get(norm.name)!; nStats.total++; if (norm.active) nStats.active++; else nStats.inactive++; } // 统计编码结构聚类 const code = norm.code || "EMPTY"; const pattern = code .replace(/\d{8}/g, "YYYYMMDD") .replace(/\d{6}/g, "SEQ6") .replace(/\d+/g, "N"); if (!patternsMap.has(pattern)) { patternsMap.set(pattern, { pattern, sample: code, count: 0, activeCount: 0, inactiveCount: 0 }); } const pStats = patternsMap.get(pattern)!; pStats.count++; if (norm.active) pStats.activeCount++; else pStats.inactiveCount++; } const finalTotal = explicitTotal !== undefined ? Math.max(explicitTotal, total) : total; const activeRate = finalTotal > 0 ? `${((activeCount / finalTotal) * 100).toFixed(1)}%` : "0.0%"; let duplicateNamesCount = 0; let mixedStatusNamesCount = 0; for (const n of namesMap.values()) { if (n.total > 1) duplicateNamesCount++; if (n.active > 0 && n.inactive > 0) mixedStatusNamesCount++; } const codePatterns = Array.from(patternsMap.values()).sort((a, b) => b.count - a.count); const formatDate = (ts: number | null) => (ts ? new Date(ts).toLocaleString("zh-CN", { hour12: false }) : null); return { total: finalTotal, activeCount, inactiveCount, activeRate, uniqueNames: namesMap.size, duplicateNamesCount, mixedStatusNamesCount, codePatterns, earliestCreateTime: formatDate(earliestCreate), latestUpdateTime: formatDate(latestUpdate), }; } export interface DatalinkAuditIssue { recordId: string; recordCode: string; recordName: string; active: boolean; type: | "MISSING_FIELD" | "DISABLED_REFERENCE" | "CROSS_LEDGER_MISSING_SYNC" | "CROSS_LEDGER_MISMATCH"; field: string; fieldLabel: string; message: string; linkedField?: string; linkedFieldLabel?: string; linkedRecordId?: string; actualId?: string; actualName?: string; expectedId?: string; expectedName?: string; } export interface DatalinkAuditReport { entityId: string; entityName: string; totalRecords: number; auditedRecords: number; healthyRecords: number; affectedRecordCount: number; issueCount: number; summary: { missingFieldCount: number; disabledReferenceCount: number; crossLedgerMissingSyncCount: number; crossLedgerMismatchCount: number; }; issues: DatalinkAuditIssue[]; suggestedPatches: Array<{ id: string; code: string; name: string; form: Record; reason: string; }>; } function isEmptyFieldValue(value: unknown): boolean { if (value === undefined || value === null || value === "") return true; if (Array.isArray(value)) return value.length === 0; if (typeof value === "object") { const obj = value as Record; if ("id" in obj) { return obj.id === undefined || obj.id === null || obj.id === ""; } if ("standard" in obj) { return obj.standard === undefined || obj.standard === null || obj.standard === ""; } return Object.keys(obj).length === 0; } return false; } function extractRefIdAndName(value: unknown): { id?: string; name?: string; active?: boolean; } { if (typeof value === "string" && value.trim()) { return { id: value.trim() }; } if (!value || typeof value !== "object" || Array.isArray(value)) { return {}; } const obj = value as Record; const nestedData = obj.data && typeof obj.data === "object" ? (obj.data as Record) : undefined; const nestedDl = nestedData?.dataLink && typeof nestedData.dataLink === "object" ? (nestedData.dataLink as Record) : obj.dataLink && typeof obj.dataLink === "object" ? (obj.dataLink as Record) : undefined; const id = typeof obj.id === "string" && obj.id.trim() ? obj.id.trim() : typeof nestedDl?.id === "string" && nestedDl.id.trim() ? nestedDl.id.trim() : undefined; const name = typeof obj.name === "string" && obj.name.trim() ? obj.name.trim() : typeof nestedDl?.name === "string" && nestedDl.name.trim() ? nestedDl.name.trim() : undefined; const active = typeof obj.active === "boolean" ? obj.active : typeof nestedDl?.active === "boolean" ? nestedDl.active : undefined; return { id, name, active }; } /** * 对业务对象记录集合执行数据健康度体检: * 1. 必填/关键字段缺失检查 (MISSING_FIELD) * 2. 关联对象/档案停用检查 (DISABLED_REFERENCE) * 3. 跨表关联同名维度一致性检查 (CROSS_LEDGER_MISSING_SYNC / CROSS_LEDGER_MISMATCH) */ export function auditEntityRecords( records: DatalinkRecord[], entity: DatalinkEntity, options: { checkFields?: string[]; activeOnly?: boolean; total?: number } = {} ): DatalinkAuditReport { const bareEntityId = entity.id.startsWith("$") ? entity.id.slice(1) : entity.id; const nameField = entity.fields.find( (f) => f.label === "名称" || f.label === "标题" || f.name === `E_${bareEntityId}_name` || f.name.endsWith("_name") ); const codeField = entity.fields.find( (f) => f.label === "编码" || f.name === `E_${bareEntityId}_code` || f.name.endsWith("_code") ); // 解析需要检查缺失的字段集合 const explicitSelectors = (options.checkFields ?? []).map((s) => s.trim()).filter(Boolean); const fieldsToCheck: DatalinkField[] = explicitSelectors.length > 0 ? explicitSelectors.map((selector) => { const found = entity.fields.find( (f) => f.name === selector || f.label === selector || f.name === `E_${bareEntityId}_${selector}` ); return ( found ?? { name: selector.startsWith("E_") ? selector : `E_${bareEntityId}_${selector}`, label: selector, type: "text", } ); }) : entity.fields.filter( (f) => f.optional === false || f.type === "dimension" || f.type === "dataLink" ); const dataLinkFields = entity.fields.filter((f) => f.type === "dataLink"); const dimensionFields = entity.fields.filter((f) => f.type === "dimension"); const issues: DatalinkAuditIssue[] = []; const suggestedPatchesMap = new Map< string, { id: string; code: string; name: string; form: Record; reasons: string[] } >(); const affectedRecordIds = new Set(); let auditedRecords = 0; let missingFieldCount = 0; let disabledReferenceCount = 0; let crossLedgerMissingSyncCount = 0; let crossLedgerMismatchCount = 0; for (const rawRecord of records) { const dl = rawRecord.dataLink && typeof rawRecord.dataLink === "object" && !Array.isArray(rawRecord.dataLink) ? (rawRecord.dataLink as Record) : (rawRecord as Record); const recordId = String(dl.id ?? rawRecord.id ?? ""); const active = (dl.active ?? rawRecord.active) !== false; if (options.activeOnly && !active) continue; auditedRecords++; const recordName = String( dl.name ?? dl["名称"] ?? (nameField ? dl[nameField.name] : undefined) ?? dl[`E_${bareEntityId}_name`] ?? "" ); const recordCode = String( dl.code ?? dl["编码"] ?? (codeField ? dl[codeField.name] : undefined) ?? dl[`E_${bareEntityId}_code`] ?? "" ); const getFieldVal = (field: DatalinkField): unknown => dl[field.name] ?? dl[`E_${bareEntityId}_${field.name}`] ?? (dl.form && typeof dl.form === "object" ? (dl.form as Record)[field.name] : undefined) ?? dl[field.label]; // 1. 必填/关键字段缺失检查 for (const field of fieldsToCheck) { const val = getFieldVal(field); if (isEmptyFieldValue(val)) { missingFieldCount++; affectedRecordIds.add(recordId); issues.push({ recordId, recordCode, recordName, active, type: "MISSING_FIELD", field: field.name, fieldLabel: field.label || field.name, message: `字段 [${field.label || field.name}] (${field.name}) 为空`, }); } } // 2. 关联对象/档案停用检查 for (const field of entity.fields) { if (field.type !== "dimension" && field.type !== "dataLink") continue; const val = getFieldVal(field); const items = Array.isArray(val) ? val : val ? [val] : []; for (const item of items) { const refInfo = extractRefIdAndName(item); if (refInfo.active === false) { disabledReferenceCount++; affectedRecordIds.add(recordId); issues.push({ recordId, recordCode, recordName, active, type: "DISABLED_REFERENCE", field: field.name, fieldLabel: field.label || field.name, actualId: refInfo.id, actualName: refInfo.name, message: `字段 [${field.label || field.name}] 引用的${ field.type === "dataLink" ? "业务对象记录" : "维度档案" } [${refInfo.name || refInfo.id || "-"}] (${refInfo.id || "-"}) 已停用 (active=false)`, }); } } } // 3. 跨表关联同名维度一致性检查 for (const linkField of dataLinkFields) { const linkVal = getFieldVal(linkField); if (!linkVal || typeof linkVal !== "object" || Array.isArray(linkVal)) continue; const linkObj = linkVal as Record; const parentDl = linkObj.data && typeof linkObj.data === "object" && (linkObj.data as Record).dataLink && typeof (linkObj.data as Record).dataLink === "object" ? ((linkObj.data as Record).dataLink as Record) : linkObj.dataLink && typeof linkObj.dataLink === "object" ? (linkObj.dataLink as Record) : linkObj; const linkedRecordId = String(parentDl.id ?? linkObj.id ?? ""); for (const dimField of dimensionFields) { const entityPrefix = `E_${bareEntityId}_`; const suffix = dimField.name.startsWith(entityPrefix) ? dimField.name.slice(entityPrefix.length) : dimField.name.replace(/^E_[^_]+_/, ""); const parentKey = Object.keys(parentDl).find( (k) => k === dimField.label || k === suffix || k.endsWith(`_${suffix}`) || (Boolean(dimField.label) && k.endsWith(`_${dimField.label}`)) ); if (!parentKey) continue; const parentRef = extractRefIdAndName(parentDl[parentKey]); if (!parentRef.id) continue; const childRef = extractRefIdAndName(getFieldVal(dimField)); if (!childRef.id) { crossLedgerMissingSyncCount++; affectedRecordIds.add(recordId); const reason = `子表字段 [${dimField.label || dimField.name}] 为空,但关联 [${ linkField.label || linkField.name }] (${linkedRecordId}) 中同名字段有值 [${parentRef.name || parentRef.id}] (${ parentRef.id }),建议回填修复`; issues.push({ recordId, recordCode, recordName, active, type: "CROSS_LEDGER_MISSING_SYNC", field: dimField.name, fieldLabel: dimField.label || dimField.name, linkedField: linkField.name, linkedFieldLabel: linkField.label || linkField.name, linkedRecordId, expectedId: parentRef.id, expectedName: parentRef.name, message: reason, }); const existingPatch = suggestedPatchesMap.get(recordId) ?? { id: recordId, code: recordCode, name: recordName, form: {}, reasons: [], }; existingPatch.form[dimField.name] = parentRef.id; existingPatch.reasons.push( `${dimField.label || dimField.name} <- ${parentRef.name || parentRef.id} (${parentRef.id})` ); suggestedPatchesMap.set(recordId, existingPatch); } else if (childRef.id !== parentRef.id) { crossLedgerMismatchCount++; affectedRecordIds.add(recordId); issues.push({ recordId, recordCode, recordName, active, type: "CROSS_LEDGER_MISMATCH", field: dimField.name, fieldLabel: dimField.label || dimField.name, linkedField: linkField.name, linkedFieldLabel: linkField.label || linkField.name, linkedRecordId, actualId: childRef.id, actualName: childRef.name, expectedId: parentRef.id, expectedName: parentRef.name, message: `子表字段 [${dimField.label || dimField.name}] 当前值 [${ childRef.name || childRef.id }] (${childRef.id}) 与关联 [${ linkField.label || linkField.name }] (${linkedRecordId}) 中的值 [${parentRef.name || parentRef.id}] (${ parentRef.id }) 不一致`, }); } } } } const suggestedPatches = [...suggestedPatchesMap.values()].map((item) => ({ id: item.id, code: item.code, name: item.name, form: item.form, reason: item.reasons.join("; "), })); return { entityId: entity.id, entityName: entity.name, totalRecords: options.total ?? records.length, auditedRecords, healthyRecords: Math.max(0, auditedRecords - affectedRecordIds.size), affectedRecordCount: affectedRecordIds.size, issueCount: issues.length, summary: { missingFieldCount, disabledReferenceCount, crossLedgerMissingSyncCount, crossLedgerMismatchCount, }, issues, suggestedPatches, }; } export interface BatchEditTargetItem { recordId: string; patchForm: Record; active?: boolean; } export interface BatchEditItemResult { recordId: string; status: "preview" | "updated" | "failed"; payload?: DatalinkRecordEditPayload; result?: Record; error?: string; } export async function batchSafeEditRecords( client: KyInstance, corpId: string, entity: DatalinkEntity, targets: BatchEditTargetItem[], options: { concurrency?: number; dryRun?: boolean } = {} ): Promise { const concurrency = Math.max(1, Math.min(options.concurrency ?? 8, 32)); const results: BatchEditItemResult[] = new Array(targets.length); let cursor = 0; const worker = async () => { while (true) { const idx = cursor++; if (idx >= targets.length) break; const target = targets[idx]; try { const detail = await api.getRecordDetail(client, corpId, target.recordId); const payload = api.buildSafeRecordEditPayload({ entityId: entity.id, recordId: target.recordId, detail, fields: entity.fields, patchForm: target.patchForm, active: target.active, }); if (options.dryRun) { results[idx] = { recordId: target.recordId, status: "preview", payload, }; } else { const res = await api.editRecord(client, corpId, payload); results[idx] = { recordId: target.recordId, status: "updated", payload, result: res, }; } } catch (error) { results[idx] = { recordId: target.recordId, status: "failed", error: error instanceof Error ? error.message : String(error), }; } } }; await Promise.all( Array.from({ length: Math.min(concurrency, targets.length) }, () => worker()) ); return results; } // ── 台账数学核对与声明式更新引擎 (Ledger Math & In-line Ops) ─────────────────── /** * 根据字段名或标签模糊解析实体字段元数据 */ export function resolveEntityField( entity: DatalinkEntity, query: string ): DatalinkField | undefined { return resolveDatalinkField(entity.fields, entity.id, query); } /** * 通用提取记录中某一字段的原始值 */ 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 (...) 以及 && 组合) */ function splitPredicateParts(source: string, separator: string): string[] { const parts: string[] = []; let quote = "", depth = 0, start = 0; for (let i = 0; i < source.length; i++) { const char = source[i]; if (quote) { if (char === "\\") i++; else if (char === quote) quote = ""; continue; } if (char === "'" || char === '"') quote = char; else if (char === "(") depth++; else if (char === ")") { if (--depth < 0) throw new ValidationError("筛选条件括号不匹配"); } else if (depth === 0 && source.startsWith(separator, i)) { parts.push(source.slice(start, i).trim()); start = i + separator.length; i += separator.length - 1; } } if (quote || depth !== 0) throw new ValidationError("筛选条件引号或括号不匹配"); parts.push(source.slice(start).trim()); if (parts.some(part => !part)) throw new ValidationError("筛选条件或列表值不能为空"); return parts; } function predicateLiteral(raw: string): string | number | boolean | null { if (/^(["']).*\1$/s.test(raw)) { const value = raw.slice(1, -1); if (raw[0] === '"') { try { return JSON.parse(raw); } catch { throw new ValidationError(`筛选值不是有效字符串: ${raw}`); } } if (/(? boolean { const conditions = splitPredicateParts(whereClause, "&&").map(cond => { // 1. in 操作符: field in (v1, v2, v3) const inMatch = cond.match(/^(.+?)\s+in\s*\((.*)\)$/i); // 2. 比较操作符: ==, !=, >=, <=, >, <, = const compMatch = inMatch ? null : cond.match(/^(.+?)\s*(==|!=|>=|<=|>|<|=)\s*(.+)$/s); if (!inMatch && !compMatch) throw new ValidationError(`不支持的筛选条件: ${cond}`); const field = predicateField(entity, (inMatch ?? compMatch)![1].trim()); const op = inMatch ? "in" : compMatch![2]; const targets = inMatch ? splitPredicateParts(inMatch[2], ",").map(predicateLiteral) : [predicateLiteral(compMatch![3].trim())]; return (record: DatalinkRecord) => { const actual = extractRecordFieldValue(record, field); const equal = (target: string | number | boolean | null): boolean => { if (target === null) return actual === null || actual === undefined; if (typeof target === "number") return extractNumericFieldValue(record, field) === target; return actual !== null && actual !== undefined && String(actual) === String(target); }; if (op === "in") return targets.some(equal); // 字符串/布尔比较 if (op === "=" || op === "==") return equal(targets[0]); if (op === "!=") return !equal(targets[0]); // 数值比较 const value = extractNumericFieldValue(record, field); const target = targets[0]; if (value === null || typeof target !== "number") return false; return op === ">" ? value > target : op === ">=" ? value >= target : op === "<" ? value < target : value <= target; }; }); return record => conditions.every(condition => condition(record)); } export function filterRecordsByPredicate( records: DatalinkRecord[], whereClause: string, entity: DatalinkEntity ): DatalinkRecord[] { if (!whereClause || !whereClause.trim()) return records; return records.filter(compileRecordPredicate(whereClause, entity)); } /** * 解析 --set 表达式为字段更新补丁: "租赁费用 = 78787.55, 状态 = 待摊销" */ export function parseSetClause( setClause: string, entity: DatalinkEntity ): Record { const result: Record = {}; let assignments: string[]; try { assignments = splitPredicateParts(setClause, ","); } catch { throw new ValidationError("赋值表达式引号或括号不匹配,且赋值项不能为空"); } for (const assign of assignments) { const eqIdx = assign.indexOf("="); if (eqIdx === -1) throw new ValidationError(`赋值项缺少等号: ${assign}`); const rawKey = assign.slice(0, eqIdx).trim(); if (!rawKey) throw new ValidationError("赋值字段不能为空"); let rawVal = assign.slice(eqIdx + 1).trim(); // 去除外层引号,同时保留显式字符串的类型与转义语义。 const quoted = (rawVal.startsWith('"') && rawVal.endsWith('"')) || (rawVal.startsWith("'") && rawVal.endsWith("'")); const literal = quoted ? predicateLiteral(rawVal) : undefined; const field = resolveEntityField(entity, rawKey); const targetKey = field ? field.name : rawKey; // 类型智能转换 if (quoted) { result[targetKey] = literal; } else 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; }