Files
hose-use/src/domains/datalink/datalink.test.ts
T

674 lines
24 KiB
TypeScript

import { describe, expect, test } from "bun:test";
import {
buildSafeRecordEditPayload,
editRecord,
getPlatform,
getRecordDetail,
listPlatformEntities,
listPlatforms,
recomputeRecordLedger,
searchEntityRecords,
toggleRecordState,
} from "./api.js";
import {
aggregateRecordFields,
auditEntityRecords,
auditLedgerContinuityAndBaseline,
batchSafeEditRecords,
buildKeywordFilter,
calculateEntityRecordStats,
compileRecordPredicate,
fetchAllEntityRecords,
filterRecordsByPredicate,
iterateAllEntityRecords,
normalizeDatalinkRecord,
parseExpectClause,
parseSetClause,
selectRecordFields,
} from "./services.js";
describe("record predicate and normalized projection regressions", () => {
const entity = { id: "ent", name: "台账", fields: [
{ name: "E_ent_seq", label: "序号", type: "number" },
{ name: "E_ent_rent", label: "租金", type: "number" },
{ name: "E_ent_note", label: "备注", type: "text" },
{ name: "E_ent_name", label: "名称", type: "text" },
] } as any;
const records = [
{ dataLink: { id: "r1", E_ent_seq: 1, E_ent_rent: 100, E_ent_note: "A,B && C", E_ent_name: "Name" } },
{ dataLink: { id: "r2", E_ent_seq: 2, E_ent_rent: 200, E_ent_note: null } },
];
for (const clause of ["序号 in [1]", "序号 == 1 &&", "不存在 != 1", "序号 === 1", "序号 in ()", "序号 > 1 || 序号 < 3", "备注 == 'broken", "序号 == 1&&garbage"]) {
test(`rejects invalid predicate even with no records: ${clause}`, () => {
expect(() => filterRecordsByPredicate([], clause, entity)).toThrow();
});
}
test("validates unknown and ambiguous fields before evaluating records", () => {
expect(() => compileRecordPredicate("租 == 1", { ...entity, fields: [...entity.fields, { name: "other", label: "租期", type: "number" }] })).toThrow("歧义");
});
test("honors quotes, commas and conjunctions inside values", () => {
expect(filterRecordsByPredicate(records, "备注 in ('A,B && C','other')&&序号>=1", entity)).toEqual([records[0]]);
expect(filterRecordsByPredicate(records, "备注 == null", entity)).toEqual([records[1]]);
expect(filterRecordsByPredicate(records, "序号 in (1,2) && 租金 < 150", entity)).toEqual([records[0]]);
});
test("selects normalized business fields and system name by label or original field name", () => {
const normalized = normalizeDatalinkRecord(records[0], entity);
expect(selectRecordFields(normalized as any, ["租金", "E_ent_seq", "名称", "id"], entity.fields)).toEqual({ 租金: 100, 序号: 1, 名称: "Name", id: "r1" });
});
});
const platform = {
id: "platform-1",
name: "业务应用",
corporationId: "corp-1",
active: true,
adminIds: ["staff-1"],
};
describe("DataLink Domain - 应用、业务对象与记录查询", () => {
test("列出应用并为权限数组提供稳定默认值", async () => {
const client = {
get: async (url: string, options: any) => {
expect(url).toBe("api/v2/datalink/platform/search");
expect(options.searchParams).toEqual({ scope: "enable", corpId: "corp-1" });
return { json: async () => ({ items: [platform] }) };
},
} as any;
const result = await listPlatforms(client, "corp-1");
expect(result[0]?.name).toBe("业务应用");
expect(result[0]?.staffIds).toEqual([]);
expect(result[0]?.departmentIds).toEqual([]);
});
test("获取应用详情时请求管理员关联", async () => {
const client = {
get: async (url: string, options: any) => {
expect(url).toBe("api/v2/datalink/platform/$platform-1");
expect(options.searchParams).toBeInstanceOf(URLSearchParams);
expect(options.searchParams.get("id")).toBe("platform-1");
expect(options.searchParams.getAll("join")).toEqual([
"icon.fileId,fileId,/v1/attachment/attachments",
"adminIds,admin,/v1/organization/staffs",
]);
expect(options.searchParams.get("corpId")).toBe("corp-1");
return { json: async () => ({ value: { ...platform, staffIds: ["staff-1"], roleIds: ["role-1"], departmentIds: [], admin: [{ id: "staff-1", name: "管理员", code: "A-1", cellphone: "13800000000" }] } }) };
},
} as any;
const result = await getPlatform(client, "corp-1", "platform-1");
expect(result.adminIds).toEqual(["staff-1"]);
expect(result.roleIds).toEqual(["role-1"]);
expect(result.admin).toEqual([{ id: "staff-1", name: "管理员", code: "A-1", active: undefined }]);
expect(JSON.stringify(result)).not.toContain("13800000000");
});
test("获取对象字段元数据并保留扩展属性", async () => {
const client = {
post: async (url: string, options: any) => {
expect(url).toBe("api/v2/datalink/entity/platformId/$platform-1");
expect(options.searchParams.corpId).toBe("corp-1");
expect(options.json).toEqual({});
return { json: async () => ({ items: [{ id: "entity-1", name: "供应商", fields: [{ name: "code", label: "编码", type: "text", optional: false, customFlag: true }] }] }) };
},
} as any;
const result = await listPlatformEntities(client, "corp-1", "platform-1");
expect(result[0]?.fields[0]?.label).toBe("编码");
expect(result[0]?.fields[0]?.customFlag).toBe(true);
});
test("分页查询记录并生成标准化分页结果", async () => {
const client = {
post: async (url: string, options: any) => {
expect(url).toBe("api/v2/datalink/searchPlatformDataLinkWithChild/$entity-1");
expect(options.searchParams.corpId).toBe("corp-1");
expect(options.json).toEqual({
entityId: "entity-1",
query: { filterBy: 'code == "A-1"', limit: { start: 10, count: 5 } },
});
return { json: async () => ({ items: { total: 1, data: [{ id: "record-1", dataLink: { code: "A-1" } }] } }) };
},
} as any;
const result = await searchEntityRecords(client, "corp-1", "entity-1", { start: 10, count: 5, filterBy: 'code == "A-1"' });
expect(result.total).toBe(1);
expect(result.data[0]?.dataLink?.code).toBe("A-1");
});
test("关键词过滤和字段投影可用于通用 CLI 查询", () => {
expect(buildKeywordFilter('A"1')).toContain('A\\"1');
expect(selectRecordFields({ id: "r-1", dataLink: { code: "A-1" } }, ["编码"], [{ name: "code", label: "编码", type: "text" }])).toEqual({ id: "r-1", dataLink: { 编码: "A-1" } });
});
test("切换记录停启用状态调用 PUT contract state 接口", async () => {
let calledUrl = "";
let calledParams: any = null;
let calledJson: any = null;
const client = {
get: async () => ({
json: async () => ({ value: { id: "record-1", active: true } }),
}),
put: async (url: string, options: any) => {
calledUrl = url;
calledParams = options.searchParams;
calledJson = options.json;
return { status: 204 };
},
} as any;
const res = await toggleRecordState(client, "corp-1", "record-1");
expect(calledUrl).toBe("api/supplier/v3/contract/$record-1/state");
expect(calledParams).toEqual({ corpId: "corp-1" });
expect(calledJson).toEqual({ id: "record-1", state: false });
expect(res).toEqual({ recordId: "record-1", active: false });
});
test("获取记录详情调用 GET datalink detail 接口", async () => {
const client = {
get: async (url: string, options: any) => {
expect(url).toBe("api/v2/datalink/detail/$record-1/$DETAIL");
expect(options.searchParams).toEqual({
dataLinkId: "record-1",
type: "DETAIL",
corpId: "corp-1",
});
return { json: async () => ({ value: { id: "record-1", name: "记录1" } }) };
},
} as any;
const result = await getRecordDetail(client, "corp-1", "record-1");
expect((result as any).name).toBe("记录1");
});
test("编辑业务对象记录调用 POST entityEdit edit 接口", async () => {
const client = {
post: async (url: string, options: any) => {
expect(url).toBe("api/v2/datalink/entityEdit/edit");
expect(options.searchParams).toEqual({ corpId: "corp-1" });
expect(options.json.dataLinkEntityId).toBe("entity-1");
expect(options.json.dataLinkId).toBe("record-1");
expect(options.json.form).toEqual({ name: "新名称" });
return { json: async () => ({ value: { id: "record-1", name: "新名称" } }) };
},
} as any;
const result = await editRecord(client, "corp-1", {
dataLinkEntityId: "$entity-1",
dataLinkId: "$record-1",
form: { name: "新名称" },
});
expect((result as any).name).toBe("新名称");
});
test("重算台账调用 POST ledger recompute 接口", async () => {
const client = {
post: async (url: string, options: any) => {
expect(url).toBe("api/v2/ledger/recompute/$record-1");
expect(options.searchParams).toEqual({ corpId: "corp-1" });
return { json: async () => ({ id: "ok" }) };
},
} as any;
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");
});
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,
});
});
test("normalizeDatalinkRecord 自动提取主键 ID、名称、编码并剥离动态前缀", () => {
const entity = {
id: "e816139ba5e1cd4ae3c0",
name: "摊销明细",
fields: [
{ name: "E_e816139ba5e1cd4ae3c0_code", label: "编码", type: "text" },
{ name: "E_e816139ba5e1cd4ae3c0_name", label: "名称", type: "text" },
{ name: "E_e816139ba5e1cd4ae3c0_rent", label: "当期租金", type: "money" },
{ name: "E_e816139ba5e1cd4ae3c0_vendor", label: "供应商", type: "ref" },
],
actions: [],
importMethod: [],
};
const rawRecord = {
dataLink: {
id: "ID01UsDobfXRRZ",
active: false,
createTime: 1780000000000,
updateTime: 1789000000000,
E_e816139ba5e1cd4ae3c0_code: "0-DT-2026-month-1",
E_e816139ba5e1cd4ae3c0_name: "使用权资产摊销-北京仓",
E_e816139ba5e1cd4ae3c0_rent: { standard: "42680.54", standardUnit: "元" },
E_e816139ba5e1cd4ae3c0_vendor: { name: "博展科技" },
},
};
const norm = normalizeDatalinkRecord(rawRecord as any, entity as any);
expect(norm.id).toBe("ID01UsDobfXRRZ");
expect(norm.active).toBe(false);
expect(norm.code).toBe("0-DT-2026-month-1");
expect(norm.name).toBe("使用权资产摊销-北京仓");
expect(norm.fields["当期租金"]).toBe("42680.54");
expect(norm.fields["供应商"]).toBe("博展科技");
});
test("calculateEntityRecordStats 准确统计启用率、重名交叉与编码结构聚类", () => {
const entity = {
id: "e_test",
name: "测试对象",
fields: [
{ name: "code", label: "编码", type: "text" },
{ name: "name", label: "名称", type: "text" },
],
actions: [],
importMethod: [],
};
const records = [
{ id: "1", code: "0-DT-20260831-0001-month-1", name: "北京仓", active: true, createTime: 1000, updateTime: 2000 },
{ id: "2", code: "0-DT-20260831-0001-month-2", name: "北京仓", active: true, createTime: 1000, updateTime: 3000 },
{ id: "3", code: "0-DT-20260831-0001-period-1", name: "北京仓", active: false, createTime: 1000, updateTime: 2500 },
{ id: "4", code: "0-DT-20260831-0002-month-1", name: "上海仓", active: false, createTime: 1200, updateTime: 2200 },
];
const stats = calculateEntityRecordStats(records as any, entity as any, 4);
expect(stats.total).toBe(4);
expect(stats.activeCount).toBe(2);
expect(stats.inactiveCount).toBe(2);
expect(stats.activeRate).toBe("50.0%");
expect(stats.uniqueNames).toBe(2);
expect(stats.duplicateNamesCount).toBe(1); // "北京仓" 出现 3 次
expect(stats.mixedStatusNamesCount).toBe(1); // "北京仓" 同时含启用与停用
expect(stats.codePatterns).toHaveLength(2);
expect(stats.codePatterns[0].count).toBe(3); // 3 条 month
expect(stats.codePatterns[1].count).toBe(1); // 1 条 period
});
test("iterateAllEntityRecords 支持跨页逐条流式下发", async () => {
let callCount = 0;
const mockClient = {
post: () => ({
json: async () => {
callCount++;
if (callCount === 1) {
return {
items: {
total: 3,
data: [{ id: "rec-1" }, { id: "rec-2" }],
},
};
}
return {
items: {
total: 3,
data: [{ id: "rec-3" }],
},
};
},
}),
};
const stream = iterateAllEntityRecords(mockClient as any, "corp-1", "entity-1", { pageSize: 2 });
const collected: string[] = [];
for await (const record of stream) {
collected.push(record.id!);
}
expect(collected).toEqual(["rec-1", "rec-2", "rec-3"]);
expect(callCount).toBe(2);
});
});