diff --git a/src/cli/commands/platform.test.ts b/src/cli/commands/platform.test.ts index 4484746..eb53e25 100644 --- a/src/cli/commands/platform.test.ts +++ b/src/cli/commands/platform.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, spyOn, afterEach } from "bun:test"; -import { handlePlatformCommand } from "./platform.js"; +import { handlePlatformCommand } from "./platform/index.js"; import * as api from "../../domains/datalink/api.js"; import * as services from "../../domains/datalink/services.js"; import * as helpers from "../helpers.js"; diff --git a/src/cli/commands/platform/app-info.ts b/src/cli/commands/platform/app-info.ts new file mode 100644 index 0000000..075f1a7 --- /dev/null +++ b/src/cli/commands/platform/app-info.ts @@ -0,0 +1,79 @@ +import { + getImportResult, + listImportJobs, + listAllPlatforms, + listPlatformEntities, + listPlatforms, +} from "../../../domains/datalink/services.js"; +import { createClientsForCorp } from "../../helpers.js"; +import { booleanOption, stringOption } from "../../parser.js"; +import { printJson, printTable } from "../../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; +import { cell, resolveAppAndEntity } from "./shared.js"; + +export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const clients = await createClientsForCorp(runtime.selectedCorp!); + const isAll = booleanOption(parsed.options, ["all", "a"], false); + const platforms = isAll + ? await listAllPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId) + : await 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 }; +} + +export async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + 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 }; +} + +export async function handleEntities(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const { clients, corpId, platform } = await resolveAppAndEntity(parsed, runtime); + const entities = await 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 }; +} + +export async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const resolved = await resolveAppAndEntity(parsed, runtime); + const entities = resolved.entity ? [resolved.entity] : await 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 => [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 }; +} + +export async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + 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> = [["应用管理员", 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 }; +} + +export async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const resolved = await resolveAppAndEntity(parsed, runtime); + if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform imports <应用> <业务对象>"); + const [jobs, latestResult] = await Promise.all([ + listImportJobs(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id), + 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 }; +} diff --git a/src/cli/commands/platform/index.ts b/src/cli/commands/platform/index.ts new file mode 100644 index 0000000..3c7dee5 --- /dev/null +++ b/src/cli/commands/platform/index.ts @@ -0,0 +1,50 @@ +import { booleanOption } from "../../parser.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; +import { handleList, handleGet, handleEntities, handleSchema, handlePermissions, handleImports } from "./app-info.js"; +import { handleRecords, handleAudit } from "./records.js"; +import { handleRecordAction } from "./record-actions.js"; + +export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + 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 }; + } +} diff --git a/src/cli/commands/platform.ts b/src/cli/commands/platform/record-actions.ts similarity index 51% rename from src/cli/commands/platform.ts rename to src/cli/commands/platform/record-actions.ts index 7825d8c..93dac1e 100644 --- a/src/cli/commands/platform.ts +++ b/src/cli/commands/platform/record-actions.ts @@ -1,282 +1,21 @@ import { readFileSync } from "node:fs"; -import * as api from "../../domains/datalink/services.js"; import { - auditEntityRecords, batchSafeEditRecords, - buildKeywordFilter, + buildSafeRecordEditPayload, + editRecord, fetchAllEntityRecords, - resolveEntity, - resolvePlatform, - selectRecordFields, + getRecordDetail, + recomputeRecordLedger, + toggleRecordState, 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 { - 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 { - 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 { - 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 { - 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 { - 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 => [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 { - 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 => { - const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record) : 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 { - 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 { - 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> = [["应用管理员", 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 { - 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 }; -} + 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 ""; @@ -308,7 +47,7 @@ async function handleDirectRecordGet( ): Promise { const clients = await createClientsForCorp(runtime.selectedCorp!); const corpId = runtime.selectedCorp!.credentials.corpId; - const detail = await api.getRecordDetail(clients.ekbClient, corpId, recordId); + const detail = await getRecordDetail(clients.ekbClient, corpId, recordId); if (runtime.jsonMode) { return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 }; } @@ -563,7 +302,7 @@ async function handleBatchEdit( }; } -async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): Promise { +export async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const action = parsed.action?.toLowerCase() || "record"; let subAction: string; let appIndex: number; @@ -625,7 +364,7 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P case "get": case "show": case "detail": { - const detail = await api.getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId); + 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); const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name")); @@ -686,7 +425,7 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P active: explicitState ?? "toggle", }); } - const res = await api.toggleRecordState(resolved.clients.ekbClient, resolved.corpId, recordId, explicitState); + 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), @@ -714,7 +453,7 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P `hose-use platform record edit ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes` ); - let payload: api.SafeRecordEditOptions extends never ? never : ReturnType; + let payload: SafeRecordEditOptions extends never ? never : ReturnType; if (isRaw) { payload = { dataLinkEntityId: resolved.entity.id, @@ -725,14 +464,14 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P } else { let detail: Record = {}; try { - detail = await api.getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId); + 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 = api.buildSafeRecordEditPayload({ + payload = buildSafeRecordEditPayload({ entityId: resolved.entity.id, recordId, detail, @@ -745,7 +484,7 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P if (isDryRun(parsed, runtime)) { return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, payload); } - const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, 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`, @@ -768,7 +507,7 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P entityId: resolved.entity.id, }); } - const result = await api.recomputeRecordLedger(resolved.clients.ekbClient, resolved.corpId, recordId); + 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`, @@ -780,4 +519,3 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P throw new Error(`未知 record 动作: ${subAction}。支持: get, toggle, edit, batch-edit, recompute`); } } - diff --git a/src/cli/commands/platform/records.ts b/src/cli/commands/platform/records.ts new file mode 100644 index 0000000..2485fc4 --- /dev/null +++ b/src/cli/commands/platform/records.ts @@ -0,0 +1,131 @@ +import { + auditEntityRecords, + buildKeywordFilter, + fetchAllEntityRecords, + searchEntityRecords, + selectRecordFields, +} from "../../../domains/datalink/services.js"; +import { booleanOption, numberOption, stringOption } from "../../parser.js"; +import { printJson, printTable, printKeyValue } from "../../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; +import { cell, resolveAppAndEntity, splitFields } from "./shared.js"; + +export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + 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 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 => { + const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record) : 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 }; +} + +export async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + 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, + }; +} diff --git a/src/cli/commands/platform/shared.ts b/src/cli/commands/platform/shared.ts new file mode 100644 index 0000000..f91125b --- /dev/null +++ b/src/cli/commands/platform/shared.ts @@ -0,0 +1,33 @@ +import { resolveEntity, resolvePlatform } from "../../../domains/datalink/services.js"; +import { createClientsForCorp } from "../../helpers.js"; +import type { CliParsedArgs, CliRuntime } from "../../types.js"; + +export function requiredTarget(parsed: CliParsedArgs, index: number, usage: string): string { + const target = parsed.args[index]?.trim(); + if (!target) throw new Error(`请提供目标参数: ${usage}`); + return target; +} + +export function splitFields(value?: string): string[] { + return value ? value.split(",").map((field) => field.trim()).filter(Boolean) : []; +} + +export function cell(value: unknown): string { + if (value === undefined || value === null) return ""; + if (typeof value === "object") return JSON.stringify(value); + return String(value); +} + +export 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 }; +} diff --git a/src/cli/registry.ts b/src/cli/registry.ts index 34de1fc..c5b4ccc 100644 --- a/src/cli/registry.ts +++ b/src/cli/registry.ts @@ -2,7 +2,7 @@ import { handleAuthCommand } from "./commands/auth.js"; import { handleCorpsCommand } from "./commands/corps/index.js"; import { handleConfigCommand } from "./commands/config.js"; import { handleWorkflowCommand } from "./commands/workflow/index.js"; -import { handlePlatformCommand } from "./commands/platform.js"; +import { handlePlatformCommand } from "./commands/platform/index.js"; import { handleAppCommand } from "./commands/app.js"; import { handleMenuCommand } from "./commands/menu.js"; import { handleSkillCommand } from "./commands/skill.js";