351 lines
21 KiB
TypeScript
351 lines
21 KiB
TypeScript
import * as api from "../../domains/datalink/api.js";
|
|
import { buildKeywordFilter, resolveEntity, resolvePlatform, selectRecordFields } from "../../domains/datalink/services.js";
|
|
import { createClientsForCorp } from "../helpers.js";
|
|
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
|
import { printJson, printTable } from "../printer.js";
|
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
|
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
|
|
|
function requiredTarget(parsed: CliParsedArgs, index: number, usage: string): string {
|
|
const target = parsed.args[index]?.trim();
|
|
if (!target) throw new Error(`请提供目标参数: ${usage}`);
|
|
return target;
|
|
}
|
|
|
|
function splitFields(value?: string): string[] {
|
|
return value ? value.split(",").map((field) => field.trim()).filter(Boolean) : [];
|
|
}
|
|
|
|
function cell(value: unknown): string {
|
|
if (value === undefined || value === null) return "";
|
|
if (typeof value === "object") return JSON.stringify(value);
|
|
return String(value);
|
|
}
|
|
|
|
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);
|
|
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${appTarget}`);
|
|
|
|
const entityTarget = parsed.args[entityIndex]?.trim();
|
|
if (!entityTarget) return { clients, corpId, platform, entity: undefined };
|
|
const entity = await resolveEntity(clients.ekbClient, corpId, platform, entityTarget);
|
|
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${entityTarget}`);
|
|
return { clients, corpId, platform, entity };
|
|
}
|
|
|
|
export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
|
if (!runtime.selectedCorp) {
|
|
return { stdout: "", stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n", exitCode: 1 };
|
|
}
|
|
|
|
const action = parsed.action || "list";
|
|
const isWorkbench = action === "workbench" || booleanOption(parsed.options, ["workbench", "w"], false);
|
|
if (isWorkbench) {
|
|
const { handleAppCommand } = await import("./app.js");
|
|
return handleAppCommand(parsed, runtime);
|
|
}
|
|
|
|
switch (action) {
|
|
case "list":
|
|
case "ls":
|
|
case "apps": return handleList(parsed, runtime);
|
|
case "get":
|
|
case "show": return handleGet(parsed, runtime);
|
|
case "entities":
|
|
case "objects": return handleEntities(parsed, runtime);
|
|
case "schema":
|
|
case "fields": return handleSchema(parsed, runtime);
|
|
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, record, permissions, imports\n`, exitCode: 1 };
|
|
}
|
|
}
|
|
|
|
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
|
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
|
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
|
const platforms = isAll
|
|
? await api.listAllPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId)
|
|
: await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
|
|
|
|
if (runtime.jsonMode) return { stdout: printJson({ count: platforms.length, all: isAll, platforms }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
|
if (platforms.length === 0) return { stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无自建应用\n`, stderr: "", exitCode: 0 };
|
|
const rows = platforms.map((p, i) => [i + 1, p.id, p.name, p.code, p.active ? "🟢 已启用" : "⚪ 未启用"]);
|
|
const label = isAll ? "自建应用与模板全量列表" : "自建应用列表";
|
|
return { stdout: `====== [${runtime.selectedCorp!.name}] ${label} (共 ${platforms.length} 个) ======\n${printTable(["#", "自建应用 ID", "应用名称", "编码", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
|
|
}
|
|
|
|
async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
|
const { platform } = await resolveAppAndEntity(parsed, runtime);
|
|
if (runtime.jsonMode) return { stdout: printJson(platform, runtime.outputOptions), stderr: "", exitCode: 0 };
|
|
return { stdout: `====== 自建应用详情: ${platform.name} ======\n${printTable(["字段", "值"], [
|
|
["ID", platform.id], ["编码", platform.code], ["状态", platform.active ? "已启用" : "未启用"],
|
|
["管理员数量", platform.adminIds.length], ["可见人员数量", platform.staffIds.length],
|
|
["可见角色数量", platform.roleIds.length], ["可见部门数量", platform.departmentIds.length],
|
|
["包含子部门", platform.departmentsIncludeChildren ? "是" : "否"],
|
|
])}\n`, stderr: "", exitCode: 0 };
|
|
}
|
|
|
|
async function handleEntities(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
|
const { clients, corpId, platform } = await resolveAppAndEntity(parsed, runtime);
|
|
const entities = await api.listPlatformEntities(clients.ekbClient, corpId, platform.id);
|
|
const keyword = stringOption(parsed.options, ["keyword", "q"])?.toLowerCase();
|
|
const filtered = keyword ? entities.filter((entity) => [entity.id, entity.name, entity.code].some((value) => value.toLowerCase().includes(keyword))) : entities;
|
|
if (runtime.jsonMode) return { stdout: printJson({ platform, keyword, total: entities.length, count: filtered.length, entities: filtered }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
|
const rows = filtered.map((entity, i) => [i + 1, entity.id, entity.name, entity.code, entity.fields.length, entity.active ? "🟢 已启用" : "⚪ 未启用"]);
|
|
return { stdout: `====== 应用 [${platform.name}] 业务对象 (匹配 ${filtered.length} / 共 ${entities.length} 个) ======\n${printTable(["#", "对象 ID", "对象名称", "编码", "字段数", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
|
|
}
|
|
|
|
async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
|
const resolved = await resolveAppAndEntity(parsed, runtime);
|
|
const entities = resolved.entity ? [resolved.entity] : await api.listPlatformEntities(resolved.clients.ekbClient, resolved.corpId, resolved.platform.id);
|
|
const fieldKeyword = stringOption(parsed.options, ["keyword", "field", "name"])?.toLowerCase();
|
|
const output = entities.map((entity) => ({ ...entity, fields: fieldKeyword ? entity.fields.filter((field) => [field.name, field.label, field.type].some((value) => value.toLowerCase().includes(fieldKeyword))) : entity.fields }));
|
|
if (runtime.jsonMode) return { stdout: printJson({ platform: resolved.platform, count: output.length, entities: output }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
|
const rows = output.flatMap((entity) => entity.fields.map((field): Array<string | number | boolean | null | undefined> => [entity.name, field.name, field.label, field.type, field.optional === false ? "必填" : "可选", cell(field.entity)]));
|
|
return { stdout: `====== 应用 [${resolved.platform.name}] 字段定义 ======\n${printTable(["业务对象", "字段名", "显示名", "类型", "必填性", "引用对象"], rows)}\n`, stderr: "", exitCode: 0 };
|
|
}
|
|
|
|
async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
|
const resolved = await resolveAppAndEntity(parsed, runtime);
|
|
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
|
|
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
|
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
|
|
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
|
const count = numberOption(parsed.options, ["count", "limit"], 20);
|
|
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
|
|
const page = await api.searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
|
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;
|
|
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 };
|
|
}
|
|
|
|
async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
|
const resolved = await resolveAppAndEntity(parsed, runtime);
|
|
const appPermission = { adminIds: resolved.platform.adminIds, staffIds: resolved.platform.staffIds, roleIds: resolved.platform.roleIds, departmentIds: resolved.platform.departmentIds, departmentsIncludeChildren: resolved.platform.departmentsIncludeChildren };
|
|
const result = resolved.entity ? { platform: resolved.platform, entity: resolved.entity, appPermission } : { platform: resolved.platform, appPermission };
|
|
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
|
const rows: Array<Array<string | number | boolean | null | undefined>> = [["应用管理员", resolved.platform.adminIds.length], ["应用可见人员", resolved.platform.staffIds.length], ["应用可见角色", resolved.platform.roleIds.length], ["应用可见部门", resolved.platform.departmentIds.length]];
|
|
if (resolved.entity) rows.push(["对象可见性", cell(resolved.entity.visibility)], ["首页可见性", cell(resolved.entity.homeVisibility)], ["导出权限", cell(resolved.entity.exportVisibility)], ["数据过滤", cell(resolved.entity.dataFilter)]);
|
|
return { stdout: `====== 权限信息: ${resolved.platform.name}${resolved.entity ? ` / ${resolved.entity.name}` : ""} ======\n${printTable(["权限项", "值"], rows)}\n`, stderr: "", exitCode: 0 };
|
|
}
|
|
|
|
async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
|
const resolved = await resolveAppAndEntity(parsed, runtime);
|
|
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform imports <应用> <业务对象>");
|
|
const [jobs, latestResult] = await Promise.all([
|
|
api.listImportJobs(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
|
|
api.getImportResult(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
|
|
]);
|
|
const result = { platform: resolved.platform, entity: resolved.entity, jobs, latestResult };
|
|
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;
|
|
requireMutationConfirmation(
|
|
parsed,
|
|
runtime,
|
|
"切换业务对象记录状态",
|
|
`hose-use platform record toggle ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
|
);
|
|
if (isDryRun(parsed, runtime)) {
|
|
return mutationPreview(parsed, runtime, "切换业务对象记录状态", recordId, {
|
|
corpId: resolved.corpId,
|
|
platformId: resolved.platform.id,
|
|
entityId: resolved.entity.id,
|
|
active: explicitState ?? "toggle",
|
|
});
|
|
}
|
|
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 changes = {
|
|
dataLinkEntityId: resolved.entity.id,
|
|
dataLinkId: recordId,
|
|
form,
|
|
active: activeOpt ?? null,
|
|
};
|
|
requireMutationConfirmation(
|
|
parsed,
|
|
runtime,
|
|
"编辑业务对象记录",
|
|
`hose-use platform record edit ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
|
);
|
|
if (isDryRun(parsed, runtime)) {
|
|
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, changes);
|
|
}
|
|
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": {
|
|
requireMutationConfirmation(
|
|
parsed,
|
|
runtime,
|
|
"触发业务对象记录台账重算",
|
|
`hose-use platform record recompute ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
|
);
|
|
if (isDryRun(parsed, runtime)) {
|
|
return mutationPreview(parsed, runtime, "触发业务对象记录台账重算", recordId, {
|
|
corpId: resolved.corpId,
|
|
platformId: resolved.platform.id,
|
|
entityId: resolved.entity.id,
|
|
});
|
|
}
|
|
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`);
|
|
}
|
|
}
|