784 lines
36 KiB
TypeScript
784 lines
36 KiB
TypeScript
import { readFileSync } from "node:fs";
|
|
import * as api from "../../domains/datalink/services.js";
|
|
import {
|
|
auditEntityRecords,
|
|
batchSafeEditRecords,
|
|
buildKeywordFilter,
|
|
fetchAllEntityRecords,
|
|
resolveEntity,
|
|
resolvePlatform,
|
|
selectRecordFields,
|
|
type BatchEditTargetItem,
|
|
} from "../../domains/datalink/services.js";
|
|
import { createClientsForCorp } from "../helpers.js";
|
|
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
|
import { printJson, printKeyValue, 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 "audit":
|
|
case "check":
|
|
case "health": return handleAudit(parsed, runtime);
|
|
case "record":
|
|
case "record-get":
|
|
case "record-toggle":
|
|
case "record-edit":
|
|
case "record-batch-edit":
|
|
case "batch-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, audit, 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 fetchAll = booleanOption(parsed.options, ["all", "a"], false);
|
|
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
|
const count = numberOption(parsed.options, ["count", "limit"], 20);
|
|
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
|
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
|
|
const page = fetchAll
|
|
? await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize })
|
|
: 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: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, 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}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
|
}
|
|
|
|
async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
|
const resolved = await resolveAppAndEntity(parsed, runtime);
|
|
if (!resolved.entity) {
|
|
throw new Error("请提供业务对象 ID、编码或名称: hose-use platform audit <应用> <业务对象> [--check-fields=字段1,字段2] [--active-only]");
|
|
}
|
|
const checkFields = splitFields(stringOption(parsed.options, ["check-fields", "checkFields", "fields"]));
|
|
const activeOnly = booleanOption(parsed.options, ["active-only", "activeOnly"], false);
|
|
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (activeOnly ? "(active==true)" : undefined);
|
|
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
|
|
|
const page = await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, {
|
|
filterBy,
|
|
pageSize,
|
|
});
|
|
const report = auditEntityRecords(page.data, resolved.entity, {
|
|
checkFields,
|
|
activeOnly,
|
|
total: page.total,
|
|
});
|
|
|
|
const output = {
|
|
platform: { id: resolved.platform.id, name: resolved.platform.name, code: resolved.platform.code },
|
|
entity: { id: resolved.entity.id, name: resolved.entity.name, code: resolved.entity.code },
|
|
...report,
|
|
};
|
|
if (runtime.jsonMode) {
|
|
return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: 0 };
|
|
}
|
|
|
|
const issueRows = report.issues.map((issue, idx) => [
|
|
idx + 1,
|
|
issue.recordId,
|
|
issue.recordCode || "-",
|
|
issue.recordName || "-",
|
|
issue.active ? "🟢 启用" : "🔴 停用",
|
|
issue.type,
|
|
issue.fieldLabel,
|
|
issue.message,
|
|
]);
|
|
|
|
const patchRows = report.suggestedPatches.map((patch, idx) => [
|
|
idx + 1,
|
|
patch.id,
|
|
patch.code || "-",
|
|
patch.name || "-",
|
|
JSON.stringify(patch.form),
|
|
patch.reason,
|
|
]);
|
|
|
|
const outLines = [
|
|
`====== 台账数据健康度体检: [${resolved.platform.name}] ${resolved.entity.name} (${resolved.entity.id}) ======`,
|
|
printKeyValue({
|
|
"总记录数": report.totalRecords,
|
|
"本次体检记录数": report.auditedRecords,
|
|
"健康记录数": report.healthyRecords,
|
|
"异常记录数": report.affectedRecordCount,
|
|
"总问题项数": report.issueCount,
|
|
"关键字段缺失 (MISSING_FIELD)": report.summary.missingFieldCount,
|
|
"引用对象已停用 (DISABLED_REFERENCE)": report.summary.disabledReferenceCount,
|
|
"跨表同名维度待回填 (CROSS_LEDGER_MISSING_SYNC)": report.summary.crossLedgerMissingSyncCount,
|
|
"跨表同名维度不一致 (CROSS_LEDGER_MISMATCH)": report.summary.crossLedgerMismatchCount,
|
|
}),
|
|
"",
|
|
"── 异常诊断明细 ──",
|
|
issueRows.length
|
|
? printTable(["#", "记录 ID", "编码", "名称", "状态", "问题类型", "字段", "详细说明"], issueRows)
|
|
: "✅ 未发现任何字段缺失、停用引用或跨表维度不一致问题",
|
|
];
|
|
|
|
if (patchRows.length > 0) {
|
|
outLines.push("");
|
|
outLines.push(`── 💡 建议自动回填修复清单 (共 ${patchRows.length} 条记录,可通过 platform record batch-edit 执行) ──`);
|
|
outLines.push(printTable(["#", "记录 ID", "编码", "名称", "建议 Patch Form", "依据"], patchRows));
|
|
}
|
|
|
|
return {
|
|
stdout: `${outLines.join("\n")}\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 };
|
|
}
|
|
|
|
function formatDirectRecordFieldValue(val: unknown): string {
|
|
if (val === undefined || val === null || val === "") return "";
|
|
if (typeof val === "object" && !Array.isArray(val)) {
|
|
const obj = val as Record<string, unknown>;
|
|
if ("standard" in obj) {
|
|
return `${obj.standard} ${obj.standardStrCode || obj.standardUnit || "CNY"}`;
|
|
}
|
|
const nestedDl =
|
|
obj.data && typeof obj.data === "object" && (obj.data as Record<string, unknown>).dataLink
|
|
? ((obj.data as Record<string, unknown>).dataLink as Record<string, unknown>)
|
|
: undefined;
|
|
if (nestedDl && typeof nestedDl === "object") {
|
|
const eId = String(nestedDl.entityId || "");
|
|
const title =
|
|
nestedDl[`E_${eId}_name`] ?? nestedDl.name ?? nestedDl[`E_${eId}_code`] ?? nestedDl.code ?? "";
|
|
return `${obj.id || nestedDl.id}${title ? ` (${title})` : ""}`;
|
|
}
|
|
if (typeof obj.id === "string" && (obj.name || obj.code)) {
|
|
return `${obj.name || obj.code} (${obj.id})`;
|
|
}
|
|
}
|
|
return cell(val);
|
|
}
|
|
|
|
async function handleDirectRecordGet(
|
|
recordId: string,
|
|
runtime: CliRuntime
|
|
): Promise<CliResult> {
|
|
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
|
const corpId = runtime.selectedCorp!.credentials.corpId;
|
|
const detail = await api.getRecordDetail(clients.ekbClient, 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 entityId = String(record.entityId || "");
|
|
const nameKey = entityId ? `E_${entityId}_name` : "name";
|
|
const codeKey = entityId ? `E_${entityId}_code` : "code";
|
|
const nameVal = record.name ?? record["名称"] ?? record[nameKey];
|
|
const codeVal = record.code ?? record["编码"] ?? record[codeKey];
|
|
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)],
|
|
["业务对象 ID (entityId)", entityId || "-"],
|
|
["名称", cell(nameVal)],
|
|
["编码", cell(codeVal)],
|
|
["状态", record.active === false ? "🔴 停用" : "🟢 启用"],
|
|
["创建时间", formatTime(record.createTime)],
|
|
["更新时间", formatTime(record.updateTime)],
|
|
];
|
|
|
|
const skipKeys = new Set([
|
|
"id",
|
|
"entityId",
|
|
"name",
|
|
"code",
|
|
nameKey,
|
|
codeKey,
|
|
"active",
|
|
"createTime",
|
|
"updateTime",
|
|
"visibility",
|
|
"form",
|
|
]);
|
|
|
|
for (const [k, v] of Object.entries(record)) {
|
|
if (skipKeys.has(k)) continue;
|
|
if (v !== undefined && v !== null && v !== "") {
|
|
const label = entityId && k.startsWith(`E_${entityId}_`) ? `${k.slice(`E_${entityId}_`.length)} (${k})` : k;
|
|
rows.push([label, formatDirectRecordFieldValue(v)]);
|
|
}
|
|
}
|
|
|
|
if (record.form && typeof record.form === "object" && !Array.isArray(record.form)) {
|
|
for (const [k, v] of Object.entries(record.form as Record<string, unknown>)) {
|
|
if (v !== undefined && v !== null && v !== "") {
|
|
rows.push([k, formatDirectRecordFieldValue(v)]);
|
|
}
|
|
}
|
|
}
|
|
|
|
return {
|
|
stdout: `====== 记录详情 (${recordId}) ======\n${printTable(["字段/属性", "值"], rows)}\n`,
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
|
|
function parseJsonDataOption(parsed: CliParsedArgs): Record<string, unknown> {
|
|
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
|
|
const filePath = stringOption(parsed.options, ["file", "f"]);
|
|
if (dataStr) {
|
|
try {
|
|
return JSON.parse(dataStr) as Record<string, unknown>;
|
|
} catch {
|
|
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
|
}
|
|
}
|
|
if (filePath) {
|
|
try {
|
|
return JSON.parse(readFileSync(filePath, "utf8")) as Record<string, unknown>;
|
|
} catch (error) {
|
|
throw new Error(`无法读取或解析 JSON 文件 [${filePath}]: ${error instanceof Error ? error.message : String(error)}`);
|
|
}
|
|
}
|
|
return {};
|
|
}
|
|
|
|
async function handleBatchEdit(
|
|
parsed: CliParsedArgs,
|
|
runtime: CliRuntime,
|
|
appIndex: number,
|
|
entityIndex: number
|
|
): Promise<CliResult> {
|
|
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
|
|
if (!resolved.entity) {
|
|
throw new Error(
|
|
"用法: hose-use platform record batch-edit <应用> <业务对象> (--ids=<id1,id2> | --filter=<expr>) (--data='<json>' | --file=<patch.json>) [--concurrency=8] [--dry-run] [--yes]"
|
|
);
|
|
}
|
|
|
|
const idsOpt = stringOption(parsed.options, ["ids", "id"]);
|
|
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]);
|
|
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
|
|
const filePath = stringOption(parsed.options, ["file", "f"]);
|
|
const concurrency = numberOption(parsed.options, ["concurrency", "c"], 8);
|
|
const activeOpt =
|
|
parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
|
|
|
if (!dataStr && !filePath) {
|
|
throw new Error("请通过 --data='<json>' 或 --file=<patch.json> 提供要批量更新的字段内容");
|
|
}
|
|
|
|
requireMutationConfirmation(
|
|
parsed,
|
|
runtime,
|
|
"批量编辑业务对象记录",
|
|
`hose-use platform record batch-edit ${resolved.platform.id} ${resolved.entity.id} --yes`
|
|
);
|
|
|
|
let fileContent: unknown;
|
|
if (filePath) {
|
|
try {
|
|
fileContent = JSON.parse(readFileSync(filePath, "utf8"));
|
|
} catch (error) {
|
|
throw new Error(`无法读取或解析 JSON 文件 [${filePath}]: ${error instanceof Error ? error.message : String(error)}`);
|
|
}
|
|
}
|
|
|
|
let uniformPatch: Record<string, unknown> | undefined;
|
|
if (dataStr) {
|
|
try {
|
|
uniformPatch = JSON.parse(dataStr) as Record<string, unknown>;
|
|
} catch {
|
|
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
|
}
|
|
} else if (
|
|
fileContent &&
|
|
typeof fileContent === "object" &&
|
|
!Array.isArray(fileContent) &&
|
|
!Object.values(fileContent as Record<string, unknown>).every(
|
|
(v) => v && typeof v === "object" && !Array.isArray(v) && !("standard" in (v as Record<string, unknown>))
|
|
)
|
|
) {
|
|
uniformPatch = fileContent as Record<string, unknown>;
|
|
}
|
|
|
|
const targets: BatchEditTargetItem[] = [];
|
|
if (Array.isArray(fileContent)) {
|
|
for (const entry of fileContent) {
|
|
if (!entry || typeof entry !== "object") continue;
|
|
const item = entry as Record<string, unknown>;
|
|
const recordId = String(item.id ?? item.recordId ?? item.dataLinkId ?? "").trim();
|
|
const patchForm =
|
|
(item.form as Record<string, unknown>) ??
|
|
(item.data as Record<string, unknown>) ??
|
|
uniformPatch ??
|
|
{};
|
|
if (recordId) {
|
|
targets.push({
|
|
recordId,
|
|
patchForm,
|
|
active: typeof item.active === "boolean" ? item.active : activeOpt,
|
|
});
|
|
}
|
|
}
|
|
} else if (!uniformPatch && fileContent && typeof fileContent === "object") {
|
|
for (const [recordId, patchVal] of Object.entries(fileContent as Record<string, unknown>)) {
|
|
if (patchVal && typeof patchVal === "object" && !Array.isArray(patchVal)) {
|
|
targets.push({
|
|
recordId,
|
|
patchForm: patchVal as Record<string, unknown>,
|
|
active: activeOpt,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
if (targets.length === 0) {
|
|
if (!uniformPatch) {
|
|
throw new Error("未解析到有效的批量更新内容");
|
|
}
|
|
let recordIds = splitFields(idsOpt);
|
|
if (recordIds.length === 0 && filterBy) {
|
|
const page = await fetchAllEntityRecords(
|
|
resolved.clients.ekbClient,
|
|
resolved.corpId,
|
|
resolved.entity.id,
|
|
{ filterBy }
|
|
);
|
|
recordIds = page.data
|
|
.map((r) => {
|
|
const dl =
|
|
r.dataLink && typeof r.dataLink === "object"
|
|
? (r.dataLink as Record<string, unknown>)
|
|
: r;
|
|
return String(dl.id ?? r.id ?? "").trim();
|
|
})
|
|
.filter(Boolean);
|
|
}
|
|
if (recordIds.length === 0) {
|
|
throw new Error("请通过 --ids=<id1,id2,...> 或 --filter=<表达式> 指定要批量更新的目标记录");
|
|
}
|
|
for (const id of recordIds) {
|
|
targets.push({
|
|
recordId: id,
|
|
patchForm: uniformPatch,
|
|
active: activeOpt,
|
|
});
|
|
}
|
|
}
|
|
|
|
const dryRun = isDryRun(parsed, runtime);
|
|
const results = await batchSafeEditRecords(
|
|
resolved.clients.ekbClient,
|
|
resolved.corpId,
|
|
resolved.entity,
|
|
targets,
|
|
{ concurrency, dryRun }
|
|
);
|
|
|
|
const succeeded = results.filter((r) => r.status === "updated" || r.status === "preview").length;
|
|
const failed = results.filter((r) => r.status === "failed").length;
|
|
const summary = {
|
|
dryRun,
|
|
platformId: resolved.platform.id,
|
|
entityId: resolved.entity.id,
|
|
total: results.length,
|
|
succeeded,
|
|
failed,
|
|
items: results,
|
|
};
|
|
|
|
if (runtime.jsonMode) {
|
|
return {
|
|
stdout: printJson(summary, runtime.outputOptions),
|
|
stderr: "",
|
|
exitCode: failed > 0 ? 1 : 0,
|
|
};
|
|
}
|
|
|
|
const rows = results.map((item, idx) => [
|
|
idx + 1,
|
|
item.recordId,
|
|
item.status === "preview" ? "🔍 预览 (dry-run)" : item.status === "updated" ? "✅ 已更新" : "❌ 失败",
|
|
item.payload ? Object.keys(item.payload.form).length : "-",
|
|
item.error || "-",
|
|
]);
|
|
|
|
return {
|
|
stdout: [
|
|
`====== 批量安全编辑业务对象记录 (${dryRun ? "Dry-Run 预览" : "已执行"}) ======`,
|
|
`应用: ${resolved.platform.name} (${resolved.platform.id}) | 业务对象: ${resolved.entity.name} (${resolved.entity.id})`,
|
|
`总计: ${results.length} | 成功/预览: ${succeeded} | 失败: ${failed}`,
|
|
printTable(["#", "记录 ID", "状态", "合并后字段数", "错误信息"], rows),
|
|
"",
|
|
].join("\n"),
|
|
stderr: "",
|
|
exitCode: failed > 0 ? 1 : 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 === "batch-edit" || action === "record-batch-edit") {
|
|
return handleBatchEdit(parsed, runtime, 0, 1);
|
|
}
|
|
|
|
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",
|
|
"batch-edit",
|
|
"recompute",
|
|
"recalc",
|
|
].includes(firstArg)
|
|
) {
|
|
subAction = firstArg;
|
|
appIndex = 1;
|
|
entityIndex = 2;
|
|
recordIdIndex = 3;
|
|
} else {
|
|
subAction = "get";
|
|
appIndex = 0;
|
|
entityIndex = 1;
|
|
recordIdIndex = 2;
|
|
}
|
|
}
|
|
|
|
if (subAction === "batch-edit") {
|
|
return handleBatchEdit(parsed, runtime, appIndex, entityIndex);
|
|
}
|
|
|
|
// 支持 hose-use platform record get <recordId> 或 hose-use platform record <recordId> 免应用/实体直接查询
|
|
const remainingArgs = parsed.args.slice(appIndex);
|
|
if (["get", "show", "detail"].includes(subAction) && remainingArgs.length === 1) {
|
|
return handleDirectRecordGet(remainingArgs[0].trim(), runtime);
|
|
}
|
|
|
|
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 form = parseJsonDataOption(parsed);
|
|
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
|
const isRaw = booleanOption(parsed.options, ["raw"], false);
|
|
|
|
requireMutationConfirmation(
|
|
parsed,
|
|
runtime,
|
|
"编辑业务对象记录",
|
|
`hose-use platform record edit ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
|
);
|
|
|
|
let payload: api.SafeRecordEditOptions extends never ? never : ReturnType<typeof api.buildSafeRecordEditPayload>;
|
|
if (isRaw) {
|
|
payload = {
|
|
dataLinkEntityId: resolved.entity.id,
|
|
dataLinkId: recordId,
|
|
form,
|
|
active: activeOpt,
|
|
};
|
|
} else {
|
|
let detail: Record<string, unknown> = {};
|
|
try {
|
|
detail = await api.getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
|
|
} catch (error) {
|
|
// 在部分仅 mock 了 editRecord 的单元测试中,ekbClient.get 可能未定义,此时退化为空基础详情以兼容测试
|
|
if (typeof (resolved.clients.ekbClient as any)?.get === "function") {
|
|
throw error;
|
|
}
|
|
}
|
|
payload = api.buildSafeRecordEditPayload({
|
|
entityId: resolved.entity.id,
|
|
recordId,
|
|
detail,
|
|
fields: resolved.entity.fields,
|
|
patchForm: form,
|
|
active: activeOpt,
|
|
});
|
|
}
|
|
|
|
if (isDryRun(parsed, runtime)) {
|
|
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, payload);
|
|
}
|
|
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, payload);
|
|
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, batch-edit, recompute`);
|
|
}
|
|
}
|
|
|