refactor: 将应用数据与工作流统一归入应用平台子模块
建立 applications 的应用模型和查询出口,保留基础及详情投影差异。 下沉 DataLink,将工作流模型、API、编排及执行上下文归回 workflow。 同步 CLI、SDK、生成脚本、测试和活跃文档引用,公开命令与 SDK 名称保持兼容。 验证:943 项测试、类型和版本检查通过;三份生成规范字节一致,README 审计通过。
This commit is contained in:
1 parent
edf300b808
commit
4e03c9bcd7
107 files changed
+423
-496
No files matched your search
@@ -0,0 +1,460 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { resolveDatalinkField } from "./fields.js";
|
||||
import {
|
||||
DatalinkEntitySchema,
|
||||
enrichDatalinkField,
|
||||
type DatalinkEntity,
|
||||
type DatalinkField,
|
||||
type DatalinkImportJob,
|
||||
type DatalinkRecord,
|
||||
type DatalinkRecordDetail,
|
||||
type DatalinkRecordEditPayload,
|
||||
type DatalinkRecordPage,
|
||||
type DatalinkRecordQuery,
|
||||
} from "./types.js";
|
||||
|
||||
function asRecord(value: unknown): Record<string, any> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, any>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function numberOr(value: unknown, fallback: number): number {
|
||||
const parsed = typeof value === "number" ? value : Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : fallback;
|
||||
}
|
||||
|
||||
function parseEntity(value: unknown): DatalinkEntity {
|
||||
const entity = DatalinkEntitySchema.parse(asRecord(value));
|
||||
return {
|
||||
...entity,
|
||||
fields: entity.fields.map(enrichDatalinkField),
|
||||
};
|
||||
}
|
||||
|
||||
/** 获取应用下的业务对象目录及完整字段定义。 */
|
||||
export async function listPlatformEntities(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
platformId: string
|
||||
): Promise<DatalinkEntity[]> {
|
||||
const normalizedId = platformId.startsWith("$") ? platformId : `$${platformId}`;
|
||||
const response = await client.post(`api/v2/datalink/entity/platformId/${normalizedId}`, {
|
||||
searchParams: { corpId },
|
||||
// 该 POST 即使没有筛选条件也要求发送空 JSON body;前端会发送 {}。
|
||||
json: {},
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
const rawItems = Array.isArray(json.items)
|
||||
? json.items
|
||||
: Array.isArray(asRecord(json.value).items)
|
||||
? asRecord(json.value).items
|
||||
: [];
|
||||
return rawItems.map(parseEntity);
|
||||
}
|
||||
|
||||
/** 分页检索指定业务对象的记录。filterBy 使用 DataLink 原生表达式。 */
|
||||
export async function searchEntityRecords(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string,
|
||||
query: DatalinkRecordQuery = {}
|
||||
): Promise<DatalinkRecordPage> {
|
||||
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
|
||||
const limit = {
|
||||
start: query.start ?? 0,
|
||||
count: query.count ?? 20,
|
||||
};
|
||||
const nativeQuery: Record<string, unknown> = {
|
||||
filterBy: query.filterBy?.trim() || "(active.in(true,false))",
|
||||
limit,
|
||||
};
|
||||
if (query.orderBy !== undefined) nativeQuery.orderBy = query.orderBy;
|
||||
|
||||
const response = await client.post(
|
||||
`api/v2/datalink/searchPlatformDataLinkWithChild/${normalizedId}`,
|
||||
{
|
||||
searchParams: { corpId },
|
||||
json: { query: nativeQuery, entityId },
|
||||
}
|
||||
);
|
||||
const json = asRecord(await response.json());
|
||||
const payload = asRecord(json.items && !Array.isArray(json.items) ? json.items : json.value ?? json);
|
||||
const rawData = Array.isArray(payload.data)
|
||||
? payload.data
|
||||
: Array.isArray(payload.items)
|
||||
? payload.items
|
||||
: Array.isArray(json.items)
|
||||
? json.items
|
||||
: [];
|
||||
|
||||
return {
|
||||
total: numberOr(payload.total ?? json.total, rawData.length),
|
||||
data: rawData.filter((item): item is DatalinkRecord => item !== null && typeof item === "object"),
|
||||
actions: Array.isArray(payload.actions) ? payload.actions : [],
|
||||
components: Array.isArray(payload.components) ? payload.components : [],
|
||||
path: payload.path,
|
||||
template: payload.template,
|
||||
};
|
||||
}
|
||||
|
||||
/** 查询对象导入任务状态。 */
|
||||
export async function listImportJobs(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string
|
||||
): Promise<DatalinkImportJob[]> {
|
||||
const response = await client.get("api/engine/easo/batchJobs", {
|
||||
searchParams: { entityId, corpId },
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
const items = json.items ?? asRecord(json.value).items ?? json.value ?? [];
|
||||
return Array.isArray(items) ? items.filter((item): item is DatalinkImportJob => item !== null && typeof item === "object") : [];
|
||||
}
|
||||
|
||||
/** 查询对象最近一次 Excel 导入结果。 */
|
||||
export async function getImportResult(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string
|
||||
): Promise<Record<string, unknown>> {
|
||||
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
|
||||
const response = await client.get(`api/v1/datalink/excel/import/result/${normalizedId}`, {
|
||||
searchParams: { entityId, corpId },
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
|
||||
/** 切换业务对象记录的停启用状态 (active: true <-> false)。若未指定 state 则自动反转当前状态。 */
|
||||
export async function toggleRecordState(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
recordId: string,
|
||||
state?: boolean
|
||||
): Promise<{ recordId: string; active: boolean }> {
|
||||
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
|
||||
const bareId = recordId.startsWith("$") ? recordId.slice(1) : recordId;
|
||||
let targetState = state;
|
||||
if (targetState === undefined) {
|
||||
const detail = await getRecordDetail(client, corpId, recordId);
|
||||
const record = ((detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>);
|
||||
targetState = !(record.active ?? true);
|
||||
}
|
||||
|
||||
await client.put(`api/supplier/v3/contract/${normalizedId}/state`, {
|
||||
searchParams: { corpId },
|
||||
json: { id: bareId, state: targetState },
|
||||
});
|
||||
|
||||
return { recordId: bareId, active: targetState };
|
||||
}
|
||||
|
||||
/** 获取单条业务对象记录的完整详情(包含展示模板、字段值、可见性及审批历史等)。 */
|
||||
export async function getRecordDetail(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
recordId: string
|
||||
): Promise<DatalinkRecordDetail> {
|
||||
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
|
||||
const bareId = recordId.startsWith("$") ? recordId.slice(1) : recordId;
|
||||
const response = await client.get(`api/v2/datalink/detail/${normalizedId}/$DETAIL`, {
|
||||
searchParams: {
|
||||
dataLinkId: bareId,
|
||||
type: "DETAIL",
|
||||
corpId,
|
||||
},
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
return (json.value ?? json.data ?? json) as DatalinkRecordDetail;
|
||||
}
|
||||
|
||||
/** 获取业务对象编辑表单的字段结构定义。 */
|
||||
export async function getRecordFormSchema(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string
|
||||
): Promise<Record<string, unknown>> {
|
||||
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
|
||||
const bareId = entityId.startsWith("$") ? entityId.slice(1) : entityId;
|
||||
const response = await client.get(`api/v2/datalink/entityEdit/entityForm/${normalizedId}/$true`, {
|
||||
searchParams: {
|
||||
entityId: bareId,
|
||||
isInsert: "true",
|
||||
needFormula: "true",
|
||||
corpId,
|
||||
},
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
|
||||
/** 编辑更新业务对象记录字段。 */
|
||||
export async function editRecord(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
payload: DatalinkRecordEditPayload
|
||||
): Promise<Record<string, unknown>> {
|
||||
const bareEntityId = payload.dataLinkEntityId.startsWith("$")
|
||||
? payload.dataLinkEntityId.slice(1)
|
||||
: payload.dataLinkEntityId;
|
||||
const bareRecordId = payload.dataLinkId.startsWith("$")
|
||||
? payload.dataLinkId.slice(1)
|
||||
: payload.dataLinkId;
|
||||
|
||||
const response = await client.post("api/v2/datalink/entityEdit/edit", {
|
||||
searchParams: { corpId },
|
||||
json: {
|
||||
...payload,
|
||||
dataLinkEntityId: bareEntityId,
|
||||
dataLinkId: bareRecordId,
|
||||
},
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
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 field = resolveDatalinkField(fields, bareEntityId, inputKey);
|
||||
if (field) return { key: field.name, fieldDef: field };
|
||||
const prefixedKey = `E_${bareEntityId}_${inputKey}`;
|
||||
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,
|
||||
corpId: string,
|
||||
recordId: string
|
||||
): Promise<Record<string, unknown>> {
|
||||
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
|
||||
const response = await client.post(`api/v2/ledger/recompute/${normalizedId}`, {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user