Files
hose-use/src/cli/commands/platform/record-actions.ts
T

564 lines
21 KiB
TypeScript

import { readFileSync } from "node:fs";
import {
batchSafeEditRecords,
buildSafeRecordEditPayload,
editRecord,
fetchAllEntityRecords,
filterRecordsByPredicate,
getRecordDetail,
parseSetClause,
recomputeRecordLedger,
toggleRecordState,
type BatchEditTargetItem,
type SafeRecordEditOptions,
} 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";
import { cell, requiredTarget, resolveAppAndEntity, splitFields } from "./shared.js";
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 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 <应用> <业务对象> (--where='<expr>' | --ids=<id1,id2> | --filter=<expr>) (--set='<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 whereClause = stringOption(parsed.options, ["where"]);
const setClause = stringOption(parsed.options, ["set"]);
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 && !setClause) {
throw new Error("请通过 --set='字段=值'、--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 (setClause) {
uniformPatch = parseSetClause(setClause, resolved.entity);
} else 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 && (whereClause || filterBy)) {
const page = await fetchAllEntityRecords(
resolved.clients.ekbClient,
resolved.corpId,
resolved.entity.id,
{ filterBy }
);
let records = page.data;
if (whereClause) {
records = filterRecordsByPredicate(records, whereClause, resolved.entity);
}
recordIds = records
.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) {
if (whereClause) {
return {
stdout: `未找到符合条件 [--where="${whereClause}"] 的记录,无需更新。\n`,
stderr: "",
exitCode: 0,
};
}
throw new Error("请通过 --where=<条件>、--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 || "-",
]);
const outputLines = [
`====== 批量安全编辑业务对象记录 (${dryRun ? "Dry-Run 预览" : "已执行"}) ======`,
`应用: ${resolved.platform.name} (${resolved.platform.id}) | 业务对象: ${resolved.entity.name} (${resolved.entity.id})`,
`总计: ${results.length} | 成功/预览: ${succeeded} | 失败: ${failed}`,
];
if (uniformPatch) {
outputLines.push(`应用变更 Patch: ${JSON.stringify(uniformPatch)}`);
}
outputLines.push(printTable(["#", "记录 ID", "状态", "合并后字段数", "错误信息"], rows));
if (dryRun) {
outputLines.push("");
outputLines.push("💡 这是 Dry-Run 预演模式,数据未发生任何改变。如需真正执行修改,请追加 --yes(或 --confirm)参数。");
}
outputLines.push("");
return {
stdout: outputLines.join("\n"),
stderr: "",
exitCode: failed > 0 ? 1 : 0,
};
}
export 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" ||
action === "batch-update"
) {
return handleBatchEdit(parsed, runtime, 0, 1);
}
if (action.startsWith("record-")) {
subAction = action.replace("record-", "");
appIndex = 0;
entityIndex = 1;
recordIdIndex = 2;
} else if (action === "update") {
subAction = "update";
appIndex = 0;
entityIndex = 1;
recordIdIndex = 2;
} else {
const firstArg = parsed.args[0]?.toLowerCase();
if (
[
"get",
"show",
"detail",
"toggle",
"state",
"edit",
"update",
"batch-edit",
"batch-update",
"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" || subAction === "batch-update") {
return handleBatchEdit(parsed, runtime, appIndex, entityIndex);
}
const whereClause = stringOption(parsed.options, ["where"]);
if ((subAction === "update" || subAction === "edit") && (whereClause || parsed.args.length <= recordIdIndex)) {
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 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 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 setClause = stringOption(parsed.options, ["set"]);
const form = setClause ? parseSetClause(setClause, resolved.entity) : 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: SafeRecordEditOptions extends never ? never : ReturnType<typeof buildSafeRecordEditPayload>;
if (isRaw) {
payload = {
dataLinkEntityId: resolved.entity.id,
dataLinkId: recordId,
form,
active: activeOpt,
};
} else {
let detail: Record<string, unknown> = {};
try {
detail = await 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 = 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 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 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`);
}
}