feat(platform,datalink,bill): add workflow job drilldown, safe record batch-edit, audit, and spec linkage diagnostics (v0.8.11)
This commit is contained in:
1 parent
2ec08033e0
commit
a0ec7f95a7
37 files changed
+3958
-674
No files matched your search
@@ -30,15 +30,20 @@ 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|名称> [--keyword <关键词>] [--filter <表达式>] [--fields <字段列表>]
|
||||
hose-use platform record get <应用> <业务对象> <记录ID>
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--all] [--keyword <关键词>] [--filter <表达式>] [--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"}' [--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 recompute <应用> <业务对象> <记录ID> [--dry-run|--yes]
|
||||
hose-use platform audit <应用 ID|名称> <对象 ID|名称> [--check-fields=字段1,字段2] [--active-only]
|
||||
hose-use platform permissions <应用 ID|名称> [对象 ID|名称]
|
||||
hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
```
|
||||
|
||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||
|
||||
单条业务对象记录支持通过 `record get`(详情)、`record toggle`(启停用)、`record edit`(字段编辑更新)以及 `record recompute`(台账重算)进行维护。Excel 批量上传与流程引擎触发暂不在本域开放。
|
||||
- `record get` 支持直传 `<记录ID>` 免传应用与业务对象。
|
||||
- `record edit` 与 `record batch-edit` 默认启用 **Read-Modify-Write 安全全量合并**(保留全部 `E_<entityId>_*` 字段、将嵌套引用对象归一化为字符串 ID、保留 `active` 与 `visibility` 结构,支持字段短名/中文标签映射);仅当显式传入 `--raw` 时才直接透传原始补丁。
|
||||
- `records --all` 自动按 `500` 条/页循环拉取全量台账记录。
|
||||
- `audit` 一键巡检必填/指定字段缺失、引用已停用档案以及跨台账同名字段同步差异,并输出 `suggestedPatches`。
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
DatalinkEntitySchema,
|
||||
DatalinkPlatformDetailSchema,
|
||||
type DatalinkEntity,
|
||||
type DatalinkField,
|
||||
type DatalinkImportJob,
|
||||
type DatalinkPlatformDetail,
|
||||
type DatalinkRecord,
|
||||
@@ -266,6 +267,248 @@ export async function editRecord(
|
||||
return (json.value ?? json.data ?? json) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
const REFERENCE_FIELD_TYPES = new Set([
|
||||
"dimension",
|
||||
"dataLink",
|
||||
"staff",
|
||||
"department",
|
||||
"role",
|
||||
"reference",
|
||||
]);
|
||||
|
||||
const SYSTEM_RECORD_KEYS = new Set([
|
||||
"id",
|
||||
"entityId",
|
||||
"active",
|
||||
"visibility",
|
||||
"createTime",
|
||||
"updateTime",
|
||||
"corporationId",
|
||||
"platformId",
|
||||
"ownerId",
|
||||
"creatorId",
|
||||
"form",
|
||||
"fieldAuth",
|
||||
"actions",
|
||||
"source",
|
||||
"sourceId",
|
||||
]);
|
||||
|
||||
function extractReferenceId(value: unknown): string | undefined {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
||||
const obj = value as Record<string, unknown>;
|
||||
if ("standard" in obj) return undefined;
|
||||
if (typeof obj.id === "string" && obj.id) return obj.id;
|
||||
if (obj.dataLink && typeof obj.dataLink === "object" && !Array.isArray(obj.dataLink)) {
|
||||
const dl = obj.dataLink as Record<string, unknown>;
|
||||
if (typeof dl.id === "string" && dl.id) return dl.id;
|
||||
}
|
||||
if (obj.data && typeof obj.data === "object" && !Array.isArray(obj.data)) {
|
||||
const dataObj = obj.data as Record<string, unknown>;
|
||||
if (typeof dataObj.id === "string" && dataObj.id) return dataObj.id;
|
||||
if (dataObj.dataLink && typeof dataObj.dataLink === "object" && !Array.isArray(dataObj.dataLink)) {
|
||||
const dl = dataObj.dataLink as Record<string, unknown>;
|
||||
if (typeof dl.id === "string" && dl.id) return dl.id;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function normalizeRecordFieldValue(
|
||||
value: unknown,
|
||||
fieldDef?: DatalinkField
|
||||
): unknown {
|
||||
if (value === undefined) return undefined;
|
||||
if (value === null) return "";
|
||||
const isRefType = fieldDef ? REFERENCE_FIELD_TYPES.has(fieldDef.type) : false;
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => {
|
||||
const refId = extractReferenceId(item);
|
||||
if (refId && (isRefType || refId)) {
|
||||
return refId;
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof value === "object" && "standard" in (value as Record<string, unknown>)) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
const refId = extractReferenceId(value);
|
||||
if (refId && (isRefType || refId)) {
|
||||
return refId;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export function resolveEntityFieldKey(
|
||||
inputKey: string,
|
||||
entityId: string,
|
||||
fields: DatalinkField[] = [],
|
||||
existingForm: Record<string, unknown> = {}
|
||||
): { key: string; fieldDef?: DatalinkField } {
|
||||
const bareEntityId = entityId.startsWith("$") ? entityId.slice(1) : entityId;
|
||||
const exactByName = fields.find((f) => f.name === inputKey);
|
||||
if (exactByName) {
|
||||
return { key: exactByName.name, fieldDef: exactByName };
|
||||
}
|
||||
const prefixedKey = `E_${bareEntityId}_${inputKey}`;
|
||||
const byPrefixedName = fields.find((f) => f.name === prefixedKey);
|
||||
if (byPrefixedName) {
|
||||
return { key: byPrefixedName.name, fieldDef: byPrefixedName };
|
||||
}
|
||||
const byLabel = fields.find((f) => f.label === inputKey);
|
||||
if (byLabel && byLabel.name) {
|
||||
return { key: byLabel.name, fieldDef: byLabel };
|
||||
}
|
||||
if (inputKey.startsWith(`E_${bareEntityId}_`)) {
|
||||
return { key: inputKey };
|
||||
}
|
||||
if (prefixedKey in existingForm) {
|
||||
return { key: prefixedKey };
|
||||
}
|
||||
if (fields.some((f) => f.name.startsWith(`E_${bareEntityId}_`)) && !(inputKey in existingForm)) {
|
||||
return { key: prefixedKey };
|
||||
}
|
||||
return { key: inputKey };
|
||||
}
|
||||
|
||||
export interface SafeRecordEditOptions {
|
||||
entityId: string;
|
||||
recordId: string;
|
||||
detail?: DatalinkRecordDetail | Record<string, unknown>;
|
||||
fields?: DatalinkField[];
|
||||
patchForm: Record<string, unknown>;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建安全的业务对象记录 Read-Modify-Write 编辑 Payload:
|
||||
* 1. 自动提取并保留原记录全部 E_<entityId>_* 及已有业务字段;
|
||||
* 2. 自动将 dimension / dataLink / staff / department 等引用对象 { id: "ID01..." } 归一化为字符串 ID;
|
||||
* 3. 自动保留 active 与 visibility(将 staff/role/department 映射为 staffs/roles/departments);
|
||||
* 4. 支持按完整字段名(E_<entityId>_xxx)或简写字段显示名/后缀(我方签约主体、name、code)合并变更。
|
||||
*/
|
||||
export function buildSafeRecordEditPayload(
|
||||
options: SafeRecordEditOptions
|
||||
): DatalinkRecordEditPayload {
|
||||
const bareEntityId = options.entityId.startsWith("$")
|
||||
? options.entityId.slice(1)
|
||||
: options.entityId;
|
||||
const bareRecordId = options.recordId.startsWith("$")
|
||||
? options.recordId.slice(1)
|
||||
: options.recordId;
|
||||
const fields = options.fields ?? [];
|
||||
const detailObj = asRecord(options.detail);
|
||||
const nestedData = asRecord(detailObj.data);
|
||||
const record = asRecord(
|
||||
detailObj.dataLink ?? nestedData.dataLink ?? detailObj
|
||||
);
|
||||
|
||||
const mergedForm: Record<string, unknown> = {};
|
||||
const fieldByName = new Map<string, DatalinkField>();
|
||||
for (const f of fields) {
|
||||
if (f.name) fieldByName.set(f.name, f);
|
||||
}
|
||||
|
||||
// 1. 提取 record.form 中的字段(兼容测试与部分特殊实体结构)
|
||||
if (record.form && typeof record.form === "object" && !Array.isArray(record.form)) {
|
||||
for (const [k, v] of Object.entries(record.form as Record<string, unknown>)) {
|
||||
const fDef = fieldByName.get(k);
|
||||
mergedForm[k] = normalizeRecordFieldValue(v, fDef);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 提取原记录中的 E_<entityId>_* 字段与 schema 中定义的业务字段
|
||||
const entityPrefix = `E_${bareEntityId}_`;
|
||||
for (const [k, v] of Object.entries(record)) {
|
||||
if (SYSTEM_RECORD_KEYS.has(k)) continue;
|
||||
const fDef = fieldByName.get(k);
|
||||
if (k.startsWith(entityPrefix) || k.startsWith("E_") || fDef) {
|
||||
mergedForm[k] = normalizeRecordFieldValue(v, fDef);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 合并用户传入的 patchForm(支持字段名、中文显示名或后缀简写)
|
||||
for (const [rawKey, rawVal] of Object.entries(options.patchForm)) {
|
||||
const { key, fieldDef } = resolveEntityFieldKey(
|
||||
rawKey,
|
||||
bareEntityId,
|
||||
fields,
|
||||
mergedForm
|
||||
);
|
||||
mergedForm[key] = normalizeRecordFieldValue(rawVal, fieldDef);
|
||||
}
|
||||
|
||||
// 4. 保留 active 与 visibility
|
||||
const resolvedActive =
|
||||
options.active !== undefined
|
||||
? options.active
|
||||
: typeof record.active === "boolean"
|
||||
? record.active
|
||||
: true;
|
||||
|
||||
const rawVis = asRecord(record.visibility);
|
||||
const normalizeRefIdList = (list: unknown): string[] => {
|
||||
if (!Array.isArray(list)) return [];
|
||||
return list
|
||||
.map((item) =>
|
||||
typeof item === "string"
|
||||
? item
|
||||
: item && typeof item === "object" && typeof (item as Record<string, unknown>).id === "string"
|
||||
? String((item as Record<string, unknown>).id)
|
||||
: undefined
|
||||
)
|
||||
.filter((item): item is string => Boolean(item));
|
||||
};
|
||||
|
||||
const visibility = {
|
||||
fullVisible:
|
||||
typeof rawVis.fullVisible === "boolean" ? rawVis.fullVisible : true,
|
||||
staffs: normalizeRefIdList(rawVis.staffs ?? rawVis.staff),
|
||||
roles: normalizeRefIdList(rawVis.roles ?? rawVis.role),
|
||||
departments: normalizeRefIdList(rawVis.departments ?? rawVis.department),
|
||||
departmentsIncludeChildren:
|
||||
typeof rawVis.departmentsIncludeChildren === "boolean"
|
||||
? rawVis.departmentsIncludeChildren
|
||||
: false,
|
||||
};
|
||||
|
||||
return {
|
||||
dataLinkEntityId: bareEntityId,
|
||||
dataLinkId: bareRecordId,
|
||||
active: resolvedActive,
|
||||
form: mergedForm,
|
||||
visibility,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全编辑单条业务对象记录(Read-Modify-Write 模式)。
|
||||
*/
|
||||
export async function safeEditRecord(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: Omit<SafeRecordEditOptions, "detail"> & {
|
||||
detail?: DatalinkRecordDetail | Record<string, unknown>;
|
||||
}
|
||||
): Promise<{
|
||||
payload: DatalinkRecordEditPayload;
|
||||
result: Record<string, unknown>;
|
||||
}> {
|
||||
const detail =
|
||||
options.detail ?? (await getRecordDetail(client, corpId, options.recordId));
|
||||
const payload = buildSafeRecordEditPayload({
|
||||
...options,
|
||||
detail,
|
||||
});
|
||||
const result = await editRecord(client, corpId, payload);
|
||||
return { payload, result };
|
||||
}
|
||||
|
||||
/** 重算业务对象记录下的台账信息。 */
|
||||
export async function recomputeRecordLedger(
|
||||
client: KyInstance,
|
||||
@@ -278,3 +521,4 @@ export async function recomputeRecordLedger(
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
buildSafeRecordEditPayload,
|
||||
editRecord,
|
||||
getPlatform,
|
||||
getRecordDetail,
|
||||
@@ -9,7 +10,13 @@ import {
|
||||
searchEntityRecords,
|
||||
toggleRecordState,
|
||||
} from "./api.js";
|
||||
import { buildKeywordFilter, selectRecordFields } from "./services.js";
|
||||
import {
|
||||
auditEntityRecords,
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
fetchAllEntityRecords,
|
||||
selectRecordFields,
|
||||
} from "./services.js";
|
||||
|
||||
const platform = {
|
||||
id: "platform-1",
|
||||
@@ -167,5 +174,217 @@ describe("DataLink Domain - 应用、业务对象与记录查询", () => {
|
||||
const result = await recomputeRecordLedger(client, "corp-1", "record-1");
|
||||
expect(result.id).toBe("ok");
|
||||
});
|
||||
|
||||
test("buildSafeRecordEditPayload 执行 Read-Modify-Write 安全合并并归一化嵌套引用 ID 与 visibility", async () => {
|
||||
const fields = [
|
||||
{ name: "E_e1_name", label: "合同名称", type: "text" },
|
||||
{ name: "E_e1_company", label: "我方签约主体", type: "dimension" },
|
||||
{ name: "E_e1_supplier", label: "供应商", type: "supplier" },
|
||||
{ name: "E_e1_amount", label: "合同金额", type: "money" },
|
||||
];
|
||||
const detail = {
|
||||
dataLink: {
|
||||
id: "ID01VSau4VJWSH",
|
||||
active: true,
|
||||
E_e1_name: "年度采购合同",
|
||||
E_e1_company: null,
|
||||
E_e1_supplier: { id: "ID01SUP123", name: "测试供应商" },
|
||||
E_e1_amount: { standard: "1000.00", standardUnit: "元", standardScale: 2 },
|
||||
visibility: {
|
||||
fullVisible: false,
|
||||
staff: [{ id: "staff-1" }],
|
||||
role: ["role-1"],
|
||||
department: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const payload = buildSafeRecordEditPayload({
|
||||
entityId: "e1",
|
||||
recordId: "ID01VSau4VJWSH",
|
||||
detail,
|
||||
fields: fields as any,
|
||||
patchForm: {
|
||||
我方签约主体: "ID01RnG3b79daL",
|
||||
},
|
||||
});
|
||||
|
||||
expect(payload.dataLinkEntityId).toBe("e1");
|
||||
expect(payload.dataLinkId).toBe("ID01VSau4VJWSH");
|
||||
expect(payload.active).toBe(true);
|
||||
expect(payload.form.E_e1_name).toBe("年度采购合同");
|
||||
expect(payload.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
expect(payload.form.E_e1_supplier).toBe("ID01SUP123");
|
||||
expect(payload.form.E_e1_amount).toBe(
|
||||
JSON.stringify({
|
||||
standard: "1000.00",
|
||||
standardUnit: "元",
|
||||
standardScale: 2,
|
||||
})
|
||||
);
|
||||
expect(payload.visibility).toEqual({
|
||||
fullVisible: false,
|
||||
staffs: ["staff-1"],
|
||||
roles: ["role-1"],
|
||||
departments: [],
|
||||
departmentsIncludeChildren: false,
|
||||
});
|
||||
|
||||
let postUrl = "";
|
||||
let postBody: any = null;
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
postUrl = url;
|
||||
postBody = options.json;
|
||||
return { json: async () => ({ value: { id: "ID01VSau4VJWSH" } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
await editRecord(client, "corp-1", payload);
|
||||
expect(postUrl).toBe("api/v2/datalink/entityEdit/edit");
|
||||
expect(postBody.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
expect(postBody.visibility.staffs).toEqual(["staff-1"]);
|
||||
});
|
||||
|
||||
test("fetchAllEntityRecords 自动分页拉取全量记录", async () => {
|
||||
const calls: Array<{ start: number; count: number }> = [];
|
||||
const client = {
|
||||
post: async (_url: string, options: any) => {
|
||||
const limit = options.json.query.limit;
|
||||
calls.push(limit);
|
||||
if (limit.start === 0) {
|
||||
return {
|
||||
json: async () => ({
|
||||
items: {
|
||||
total: 3,
|
||||
data: [
|
||||
{ id: "r-1", dataLink: { id: "r-1" } },
|
||||
{ id: "r-2", dataLink: { id: "r-2" } },
|
||||
],
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
json: async () => ({
|
||||
items: {
|
||||
total: 3,
|
||||
data: [{ id: "r-3", dataLink: { id: "r-3" } }],
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await fetchAllEntityRecords(client, "corp-1", "entity-1", { pageSize: 2 });
|
||||
expect(calls).toEqual([
|
||||
{ start: 0, count: 2 },
|
||||
{ start: 2, count: 2 },
|
||||
]);
|
||||
expect(result.data).toHaveLength(3);
|
||||
});
|
||||
|
||||
test("auditEntityRecords 巡检必填缺失、停用引用与跨台账同名字段同步差异", () => {
|
||||
const childEntity = {
|
||||
id: "e_plan",
|
||||
name: "支付计划表",
|
||||
fields: [
|
||||
{ name: "E_e_plan_code", label: "编码", type: "text", optional: true },
|
||||
{ name: "E_e_plan_company", label: "我方签约主体", type: "dimension", optional: false },
|
||||
{
|
||||
name: "E_e_plan_contract",
|
||||
label: "关联合同流程",
|
||||
type: "dataLink",
|
||||
optional: true,
|
||||
entityId: "e_contract",
|
||||
},
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const records = [
|
||||
{
|
||||
id: "plan-1",
|
||||
dataLink: {
|
||||
id: "plan-1",
|
||||
code: "PL-001",
|
||||
name: "第一期付款",
|
||||
active: true,
|
||||
E_e_plan_company: null,
|
||||
E_e_plan_contract: {
|
||||
id: "contract-1",
|
||||
name: "测试合同",
|
||||
active: false,
|
||||
data: {
|
||||
dataLink: {
|
||||
id: "contract-1",
|
||||
code: "HT-001",
|
||||
active: false,
|
||||
E_e_contract_company: {
|
||||
id: "ID01RnG3b79daL",
|
||||
name: "北京转转精神科技有限责任公司",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const report = auditEntityRecords(records as any, childEntity as any, {
|
||||
checkFields: ["我方签约主体"],
|
||||
});
|
||||
|
||||
expect(report.totalRecords).toBe(1);
|
||||
expect(report.summary.missingFieldCount).toBe(1);
|
||||
expect(report.summary.disabledReferenceCount).toBe(1);
|
||||
expect(report.summary.crossLedgerMissingSyncCount).toBe(1);
|
||||
expect(report.suggestedPatches).toEqual([
|
||||
{
|
||||
id: "plan-1",
|
||||
code: "PL-001",
|
||||
name: "第一期付款",
|
||||
form: {
|
||||
E_e_plan_company: "ID01RnG3b79daL",
|
||||
},
|
||||
reason: "我方签约主体 <- 北京转转精神科技有限责任公司 (ID01RnG3b79daL)",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("batchSafeEditRecords 支持 dryRun 预览与并发安全合并", async () => {
|
||||
const entity = {
|
||||
id: "e1",
|
||||
name: "合同流程",
|
||||
fields: [{ name: "E_e1_company", label: "我方签约主体", type: "dimension" }],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
const client = {
|
||||
get: async () => ({
|
||||
json: async () => ({
|
||||
value: {
|
||||
dataLink: {
|
||||
id: "r-1",
|
||||
active: true,
|
||||
E_e1_company: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
} as any;
|
||||
|
||||
const results = await batchSafeEditRecords(
|
||||
client,
|
||||
"corp-1",
|
||||
entity as any,
|
||||
[{ recordId: "r-1", patchForm: { 我方签约主体: "ID01RnG3b79daL" } }],
|
||||
{ dryRun: true }
|
||||
);
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0]?.status).toBe("preview");
|
||||
expect(results[0]?.payload?.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "./api.js";
|
||||
import type { DatalinkEntity, DatalinkField, DatalinkPlatformDetail } from "./types.js";
|
||||
import type {
|
||||
DatalinkEntity,
|
||||
DatalinkField,
|
||||
DatalinkPlatformDetail,
|
||||
DatalinkRecord,
|
||||
DatalinkRecordEditPayload,
|
||||
DatalinkRecordPage,
|
||||
} from "./types.js";
|
||||
|
||||
function matches(value: unknown, target: string): boolean {
|
||||
return typeof value === "string" && value.toLowerCase() === target.toLowerCase();
|
||||
@@ -35,14 +42,21 @@ export function buildKeywordFilter(keyword: string): string {
|
||||
return `(name.containsIgnoreCase("${escaped}")||code.containsIgnoreCase("${escaped}"))&&(active.in(true,false))`;
|
||||
}
|
||||
|
||||
export function selectRecordFields(record: Record<string, unknown>, fields: string[], definitions: DatalinkField[] = []): Record<string, unknown> {
|
||||
export function selectRecordFields(
|
||||
record: Record<string, unknown>,
|
||||
fields: string[],
|
||||
definitions: DatalinkField[] = []
|
||||
): Record<string, unknown> {
|
||||
if (fields.length === 0) return record;
|
||||
const dataLink = record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink)
|
||||
? (record.dataLink as Record<string, unknown>)
|
||||
: record;
|
||||
const dataLink =
|
||||
record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink)
|
||||
? (record.dataLink as Record<string, unknown>)
|
||||
: record;
|
||||
const selected: Record<string, unknown> = {};
|
||||
for (const selector of fields) {
|
||||
const definition = definitions.find((field) => field.name === selector || field.label === selector);
|
||||
const definition = definitions.find(
|
||||
(field) => field.name === selector || field.label === selector
|
||||
);
|
||||
const sourceName = definition?.name ?? selector;
|
||||
if (sourceName in dataLink) selected[definition?.label || selector] = dataLink[sourceName];
|
||||
}
|
||||
@@ -50,3 +64,493 @@ export function selectRecordFields(record: Record<string, unknown>, fields: stri
|
||||
? { ...record, dataLink: selected }
|
||||
: selected;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动分页全量拉取指定业务对象的全部记录(默认每页 500 条循环直到底)。
|
||||
*/
|
||||
export async function fetchAllEntityRecords(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string,
|
||||
options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {}
|
||||
): Promise<DatalinkRecordPage> {
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
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<string, string>;
|
||||
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<string, unknown>;
|
||||
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<string, unknown>;
|
||||
const nestedData =
|
||||
obj.data && typeof obj.data === "object"
|
||||
? (obj.data as Record<string, unknown>)
|
||||
: undefined;
|
||||
const nestedDl =
|
||||
nestedData?.dataLink && typeof nestedData.dataLink === "object"
|
||||
? (nestedData.dataLink as Record<string, unknown>)
|
||||
: obj.dataLink && typeof obj.dataLink === "object"
|
||||
? (obj.dataLink as Record<string, unknown>)
|
||||
: 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<string, string>; reasons: string[] }
|
||||
>();
|
||||
const affectedRecordIds = new Set<string>();
|
||||
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<string, unknown>)
|
||||
: (rawRecord as Record<string, unknown>);
|
||||
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<string, unknown>)[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<string, unknown>;
|
||||
const parentDl =
|
||||
linkObj.data &&
|
||||
typeof linkObj.data === "object" &&
|
||||
(linkObj.data as Record<string, unknown>).dataLink &&
|
||||
typeof (linkObj.data as Record<string, unknown>).dataLink === "object"
|
||||
? ((linkObj.data as Record<string, unknown>).dataLink as Record<string, unknown>)
|
||||
: linkObj.dataLink && typeof linkObj.dataLink === "object"
|
||||
? (linkObj.dataLink as Record<string, unknown>)
|
||||
: 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<string, unknown>;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
export interface BatchEditItemResult {
|
||||
recordId: string;
|
||||
status: "preview" | "updated" | "failed";
|
||||
payload?: DatalinkRecordEditPayload;
|
||||
result?: Record<string, unknown>;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export async function batchSafeEditRecords(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entity: DatalinkEntity,
|
||||
targets: BatchEditTargetItem[],
|
||||
options: { concurrency?: number; dryRun?: boolean } = {}
|
||||
): Promise<BatchEditItemResult[]> {
|
||||
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;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user