feat(datalink): add record get, toggle, edit, and recompute actions and fix active display
This commit is contained in:
1 parent
09c4e7df4a
commit
97b67c71da
9 files changed
+655
-7
No files matched your search
@@ -0,0 +1,189 @@
|
||||
import { describe, expect, it, spyOn } from "bun:test";
|
||||
import { handlePlatformCommand } from "./platform.js";
|
||||
import * as api from "../../domains/datalink/api.js";
|
||||
import * as services from "../../domains/datalink/services.js";
|
||||
import * as helpers from "../helpers.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
describe("CLI - platform 命令与 record 动作", () => {
|
||||
const mockCorp: CorpConfig = {
|
||||
id: "corp-1",
|
||||
name: "测试企业",
|
||||
source: "account",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
credentials: {
|
||||
accessToken: "mock-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "staff-1",
|
||||
},
|
||||
};
|
||||
|
||||
const dummyRuntime: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [mockCorp],
|
||||
getCurrent: () => mockCorp,
|
||||
switchCorp: () => true,
|
||||
resolve: () => mockCorp,
|
||||
} as any,
|
||||
selectedCorp: mockCorp,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
const mockPlatform = {
|
||||
id: "platform-1",
|
||||
name: "项目台账",
|
||||
code: "PJ",
|
||||
active: true,
|
||||
adminIds: ["staff-1"],
|
||||
staffIds: [],
|
||||
roleIds: [],
|
||||
departmentIds: [],
|
||||
departmentsIncludeChildren: false,
|
||||
};
|
||||
|
||||
const mockEntity = {
|
||||
id: "entity-1",
|
||||
name: "项目",
|
||||
code: "PROJECT",
|
||||
type: "DIMENSION",
|
||||
active: true,
|
||||
fields: [
|
||||
{ name: "code", label: "编码", type: "text" },
|
||||
{ name: "name", label: "名称", type: "text" },
|
||||
{ name: "customField", label: "自定义字段", type: "text" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
it("未选中企业时报错并返回 exitCode 1", async () => {
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "list", args: [], options: {}, raw: [] },
|
||||
{ ...dummyRuntime, selectedCorp: null }
|
||||
);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未选中企业");
|
||||
});
|
||||
|
||||
it("records 正确解析嵌套 dataLink 的停启用状态和更新时间", async () => {
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any);
|
||||
spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any);
|
||||
spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any);
|
||||
spyOn(api, "searchEntityRecords").mockResolvedValue({
|
||||
total: 2,
|
||||
data: [
|
||||
{
|
||||
id: "r-1",
|
||||
dataLink: { id: "r-1", name: "项目1", code: "P1", active: false, updateTime: "2026-09-09" },
|
||||
},
|
||||
{
|
||||
id: "r-2",
|
||||
dataLink: { id: "r-2", name: "项目2", code: "P2", active: true, updateTime: "2026-09-09" },
|
||||
},
|
||||
],
|
||||
actions: [],
|
||||
components: [],
|
||||
path: null,
|
||||
template: null,
|
||||
});
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["platform-1", "entity-1"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("停用");
|
||||
expect(res.stdout).toContain("启用");
|
||||
});
|
||||
|
||||
it("record get 获取记录详情", async () => {
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any);
|
||||
spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any);
|
||||
spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any);
|
||||
spyOn(api, "getRecordDetail").mockResolvedValue({
|
||||
dataLink: {
|
||||
id: "r-1",
|
||||
name: "测试项目",
|
||||
code: "P-100",
|
||||
active: true,
|
||||
createTime: 12345678,
|
||||
updateTime: 12345679,
|
||||
form: { customField: "测试值" },
|
||||
},
|
||||
});
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "record", args: ["get", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("测试项目");
|
||||
expect(res.stdout).toContain("P-100");
|
||||
expect(res.stdout).toContain("测试值");
|
||||
});
|
||||
|
||||
it("record toggle 切换停启用状态", async () => {
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any);
|
||||
spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any);
|
||||
spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any);
|
||||
const toggleSpy = spyOn(api, "toggleRecordState").mockResolvedValue({ recordId: "r-1", active: true });
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "record", args: ["toggle", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("状态已成功切换为");
|
||||
expect(toggleSpy).toHaveBeenCalledWith(expect.anything(), "corp-1", "r-1", undefined);
|
||||
});
|
||||
|
||||
it("record edit 编辑字段", async () => {
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any);
|
||||
spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any);
|
||||
spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any);
|
||||
const editSpy = spyOn(api, "editRecord").mockResolvedValue({ id: "r-1" } as any);
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{
|
||||
area: "platform",
|
||||
action: "record",
|
||||
args: ["edit", "platform-1", "entity-1", "r-1"],
|
||||
options: { data: '{"name":"更新后的名称"}' },
|
||||
raw: [],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("字段更新成功");
|
||||
expect(editSpy).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
"corp-1",
|
||||
expect.objectContaining({
|
||||
dataLinkEntityId: "entity-1",
|
||||
dataLinkId: "r-1",
|
||||
form: { name: "更新后的名称" },
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("record recompute 触发台账重算", async () => {
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any);
|
||||
spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any);
|
||||
spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any);
|
||||
const recomputeSpy = spyOn(api, "recomputeRecordLedger").mockResolvedValue({ id: "ok" });
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "record", args: ["recompute", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("台账重算任务已成功触发");
|
||||
expect(recomputeSpy).toHaveBeenCalledWith(expect.anything(), "corp-1", "r-1");
|
||||
});
|
||||
});
|
||||
@@ -21,8 +21,8 @@ function cell(value: unknown): string {
|
||||
return String(value);
|
||||
}
|
||||
|
||||
async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, entityIndex = 1) {
|
||||
const appTarget = requiredTarget(parsed, 0, "hose-use platform <子命令> <应用 ID|名称>");
|
||||
async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) {
|
||||
const appTarget = requiredTarget(parsed, appIndex, "hose-use platform <子命令> <应用 ID|名称>");
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, appTarget);
|
||||
@@ -60,13 +60,18 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
|
||||
case "records":
|
||||
case "data":
|
||||
case "search": return handleRecords(parsed, runtime);
|
||||
case "record":
|
||||
case "record-get":
|
||||
case "record-toggle":
|
||||
case "record-edit":
|
||||
case "record-recompute": return handleRecordAction(parsed, runtime);
|
||||
case "permissions":
|
||||
case "permission":
|
||||
case "auth": return handlePermissions(parsed, runtime);
|
||||
case "imports":
|
||||
case "import-jobs": return handleImports(parsed, runtime);
|
||||
default:
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, permissions, imports\n`, exitCode: 1 };
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, record, permissions, imports\n`, exitCode: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,9 +132,17 @@ async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
const data = fields.length ? page.data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields)) : page.data;
|
||||
const result = { platform: resolved.platform, entity: resolved.entity, query: { start, count, filterBy, fields }, total: page.total, returned: data.length, data };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
|
||||
const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? item.dataLink as Record<string, unknown> : item;
|
||||
return [i + 1, cell(item.id), cell(source.name ?? source["名称"]), cell(source.code ?? source["编码"]), item.active === false ? "停用" : "启用", cell(item.updateTime)];
|
||||
const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record<string, unknown>) : item;
|
||||
const id = source.id ?? item.id;
|
||||
const active = source.active ?? item.active;
|
||||
const updateTime = source.updateTime ?? item.updateTime;
|
||||
const nameVal = source.name ?? source["名称"] ?? (nameField ? source[nameField.name] : undefined) ?? source[`E_${resolved.entity!.id}_name`];
|
||||
const codeVal = source.code ?? source["编码"] ?? (codeField ? source[codeField.name] : undefined) ?? source[`E_${resolved.entity!.id}_code`];
|
||||
const formattedTime = typeof updateTime === "number" ? new Date(updateTime).toLocaleString("zh-CN", { hour12: false }) : cell(updateTime);
|
||||
return [i + 1, cell(id), cell(nameVal), cell(codeVal), active === false ? "停用" : "启用", formattedTime];
|
||||
});
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -155,3 +168,140 @@ async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const action = parsed.action?.toLowerCase() || "record";
|
||||
let subAction: string;
|
||||
let appIndex: number;
|
||||
let entityIndex: number;
|
||||
let recordIdIndex: number;
|
||||
|
||||
if (action.startsWith("record-")) {
|
||||
subAction = action.replace("record-", "");
|
||||
appIndex = 0;
|
||||
entityIndex = 1;
|
||||
recordIdIndex = 2;
|
||||
} else {
|
||||
const firstArg = parsed.args[0]?.toLowerCase();
|
||||
if (["get", "show", "detail", "toggle", "state", "edit", "update", "recompute", "recalc"].includes(firstArg)) {
|
||||
subAction = firstArg;
|
||||
appIndex = 1;
|
||||
entityIndex = 2;
|
||||
recordIdIndex = 3;
|
||||
} else {
|
||||
subAction = "get";
|
||||
appIndex = 0;
|
||||
entityIndex = 1;
|
||||
recordIdIndex = 2;
|
||||
}
|
||||
}
|
||||
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform record <动作> <应用> <业务对象> <记录ID>");
|
||||
const recordId = requiredTarget(parsed, recordIdIndex, "hose-use platform record <动作> <应用> <业务对象> <记录ID>");
|
||||
|
||||
switch (subAction) {
|
||||
case "get":
|
||||
case "show":
|
||||
case "detail": {
|
||||
const detail = await api.getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
if (runtime.jsonMode) return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const record = ((detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>);
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const nameVal = record.name ?? record["名称"] ?? (nameField ? record[nameField.name] : undefined) ?? record[`E_${resolved.entity.id}_name`];
|
||||
const codeVal = record.code ?? record["编码"] ?? (codeField ? record[codeField.name] : undefined) ?? record[`E_${resolved.entity.id}_code`];
|
||||
|
||||
const formatTime = (time: unknown) => typeof time === "number" ? new Date(time).toLocaleString("zh-CN", { hour12: false }) : cell(time);
|
||||
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [
|
||||
["记录 ID", cell(record.id ?? recordId)],
|
||||
["业务对象", `${resolved.entity.name} (${resolved.entity.id})`],
|
||||
["名称", cell(nameVal)],
|
||||
["编码", cell(codeVal)],
|
||||
["状态", record.active === false ? "🔴 停用" : "🟢 启用"],
|
||||
["创建时间", formatTime(record.createTime)],
|
||||
["更新时间", formatTime(record.updateTime)],
|
||||
];
|
||||
|
||||
for (const field of resolved.entity.fields) {
|
||||
if (field.name === nameField?.name || field.name === codeField?.name) continue;
|
||||
const val = record[field.name] ?? record[`E_${resolved.entity.id}_${field.name}`] ?? (record.form as Record<string, unknown> | undefined)?.[field.name] ?? record[field.label];
|
||||
if (val !== undefined && val !== null && val !== "") {
|
||||
let displayVal = val;
|
||||
if (field.type === "date" && typeof val === "number") {
|
||||
displayVal = new Date(val).toLocaleDateString("zh-CN");
|
||||
} else if (field.type === "money" && typeof val === "object" && val !== null && "standard" in (val as any)) {
|
||||
displayVal = `${(val as any).standard} ${(val as any).standardStrCode || "CNY"}`;
|
||||
}
|
||||
rows.push([`${field.label} (${field.name})`, cell(displayVal)]);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== 记录详情: [${resolved.platform.name}] ${resolved.entity.name} (${recordId}) ======\n${printTable(["字段/属性", "值"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "toggle":
|
||||
case "state": {
|
||||
const explicitState = parsed.options.state !== undefined
|
||||
? booleanOption(parsed.options, ["state"], true)
|
||||
: parsed.options.active !== undefined
|
||||
? booleanOption(parsed.options, ["active"], true)
|
||||
: undefined;
|
||||
const res = await api.toggleRecordState(resolved.clients.ekbClient, resolved.corpId, recordId, explicitState);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, recordId: res.recordId, active: res.active, app: resolved.platform.name, entity: resolved.entity.name }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const label = res.active ? "🟢 启用" : "🔴 停用";
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 状态已成功切换为 [${label}]。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "edit":
|
||||
case "update": {
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d", "f"]);
|
||||
let form: Record<string, unknown> = {};
|
||||
if (dataStr) {
|
||||
try {
|
||||
form = JSON.parse(dataStr);
|
||||
} catch {
|
||||
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
||||
}
|
||||
}
|
||||
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
||||
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, {
|
||||
dataLinkEntityId: resolved.entity.id,
|
||||
dataLinkId: recordId,
|
||||
form,
|
||||
active: activeOpt,
|
||||
});
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 字段更新成功。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "recompute":
|
||||
case "recalc": {
|
||||
const result = await api.recomputeRecordLedger(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ success: true, recordId, result }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 台账重算任务已成功触发。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
default:
|
||||
throw new Error(`未知 record 动作: ${subAction}。支持: get, toggle, edit, recompute`);
|
||||
}
|
||||
}
|
||||
@@ -31,10 +31,14 @@ 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 record toggle <应用> <业务对象> <记录ID> [--state=true|false]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> --data='{"field": "val"}'
|
||||
hose-use platform record recompute <应用> <业务对象> <记录ID>
|
||||
hose-use platform permissions <应用 ID|名称> [对象 ID|名称]
|
||||
hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
```
|
||||
|
||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||
|
||||
写入、编辑、启停用和 Excel 上传暂不在本域开放。对象元数据中的操作标识只代表前端声明的能力,不能直接当作已确认的写入接口。
|
||||
单条业务对象记录支持通过 `record get`(详情)、`record toggle`(启停用)、`record edit`(字段编辑更新)以及 `record recompute`(台账重算)进行维护。Excel 批量上传与流程引擎触发暂不在本域开放。
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
type DatalinkImportJob,
|
||||
type DatalinkPlatformDetail,
|
||||
type DatalinkRecord,
|
||||
type DatalinkRecordDetail,
|
||||
type DatalinkRecordEditPayload,
|
||||
type DatalinkRecordPage,
|
||||
type DatalinkRecordQuery,
|
||||
} from "./types.js";
|
||||
@@ -176,3 +178,103 @@ export async function getImportResult(
|
||||
});
|
||||
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>;
|
||||
}
|
||||
|
||||
/** 重算业务对象记录下的台账信息。 */
|
||||
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());
|
||||
}
|
||||
@@ -1,5 +1,14 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { getPlatform, listPlatformEntities, listPlatforms, searchEntityRecords } from "./api.js";
|
||||
import {
|
||||
editRecord,
|
||||
getPlatform,
|
||||
getRecordDetail,
|
||||
listPlatformEntities,
|
||||
listPlatforms,
|
||||
recomputeRecordLedger,
|
||||
searchEntityRecords,
|
||||
toggleRecordState,
|
||||
} from "./api.js";
|
||||
import { buildKeywordFilter, selectRecordFields } from "./services.js";
|
||||
|
||||
const platform = {
|
||||
@@ -85,4 +94,78 @@ describe("DataLink Domain - 应用、业务对象与记录查询", () => {
|
||||
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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -66,6 +66,71 @@ export const datalinkTools = [
|
||||
return { jobs, latestResult: result };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_get",
|
||||
description: "获取单条业务对象记录的完整详情(模板、字段值、可见性及历史等)",
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { recordId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.getRecordDetail(ekbClient, corp.credentials.corpId, params.recordId);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_toggle",
|
||||
description: "切换业务对象记录的停启用状态 (active: true <-> false)",
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
state: z.boolean().optional().describe("目标状态 (true 为启用,false 为停用,不传则自动翻转)"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { recordId: string; state?: boolean }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
const result = await api.toggleRecordState(ekbClient, corp.credentials.corpId, params.recordId, params.state);
|
||||
return { success: true, ...result };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_edit",
|
||||
description: "编辑更新业务对象记录的字段值",
|
||||
parameters: z.object({
|
||||
entityId: z.string().describe("业务对象 ID"),
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
form: z.record(z.string(), z.unknown()).describe("待更新的表单字段键值对"),
|
||||
active: z.boolean().optional().describe("停启用状态"),
|
||||
visibility: z.record(z.string(), z.unknown()).optional().describe("可见性配置"),
|
||||
}),
|
||||
handler: async (
|
||||
clients: unknown,
|
||||
params: {
|
||||
entityId: string;
|
||||
recordId: string;
|
||||
form: Record<string, unknown>;
|
||||
active?: boolean;
|
||||
visibility?: Record<string, unknown>;
|
||||
}
|
||||
) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.editRecord(ekbClient, corp.credentials.corpId, {
|
||||
dataLinkEntityId: params.entityId,
|
||||
dataLinkId: params.recordId,
|
||||
form: params.form,
|
||||
active: params.active,
|
||||
visibility: params.visibility,
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_recompute",
|
||||
description: "重新计算指定业务对象记录下的全部台账信息",
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { recordId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.recomputeRecordLedger(ekbClient, corp.credentials.corpId, params.recordId);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export type DatalinkTool = (typeof datalinkTools)[number];
|
||||
@@ -92,3 +92,30 @@ export interface DatalinkPermissionSnapshot {
|
||||
platform: DatalinkPlatformDetail;
|
||||
entity?: DatalinkEntity;
|
||||
}
|
||||
|
||||
export interface DatalinkRecordDetail {
|
||||
dataLink?: DatalinkRecord;
|
||||
template?: unknown;
|
||||
entity?: unknown;
|
||||
actions?: unknown[];
|
||||
flowCounts?: Record<string, unknown>;
|
||||
ledger?: Record<string, unknown>;
|
||||
ledgers?: unknown[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface DatalinkRecordEditPayload {
|
||||
dataLinkEntityId: string;
|
||||
dataLinkId: string;
|
||||
active?: boolean;
|
||||
form: Record<string, unknown>;
|
||||
visibility?: {
|
||||
fullVisible?: boolean;
|
||||
staffs?: string[];
|
||||
roles?: string[];
|
||||
departments?: string[];
|
||||
departmentsIncludeChildren?: boolean;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
[key: string]: unknown;
|
||||
}
|
||||
Reference in new issue
Block a user