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, field.fieldKey, field.displayName].some( (value) => typeof value === "string" && 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 => { const roleTag = field.role === "title" ? "⭐ 主标题 (_name)" : field.role === "code" ? "🔢 业务编码 (_code)" : field.role === "system" ? "⚙️ 系统字段" : "📝 业务字段"; return [ entity.name, field.fieldKey ?? field.name, field.label, field.type, roleTag, field.optional === false ? "必填" : "可选", cell(field.entity), ]; }) ); const table = printTable( ["业务对象", "物理字段键 (fieldKey / 接口参数名)", "界面名称 (label)", "类型", "角色说明", "必填性", "引用对象"], rows ); const tips = [ "", "💡 字段命名与工作流配置避坑提示:", " 1. 物理字段键 (fieldKey / 接口参数名): 在工作流节点映射 (如 ekuaibao-datalink-create) 和 API 请求中,必须使用此键 (例如 E_..._费用金额),切勿使用中文显示名。", " 2. 结尾 _name: 代表实体的业务主名称/标题 (界面通常显示为单据/计划名称);", " 3. 结尾 _code: 代表业务编号/单号 (界面通常显示为单据/计划编码);若设置了 autoNumber 规则,创建时会自动生成流水号。", "", ].join("\n"); return { stdout: `====== 应用 [${resolved.platform.name}] 字段定义 (共 ${rows.length} 个字段) ======\n${table}\n${tips}`, 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 }; } export async function handleGenProps(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const resolved = await resolveAppAndEntity(parsed, runtime); if (!resolved.entity) { throw new Error("请提供业务对象 ID、编码或名称: hose-use platform gen-props <应用> <业务对象> [--lang=mvel|js]"); } const lang = (stringOption(parsed.options, ["lang", "language"]) || "mvel").toLowerCase(); const entity = resolved.entity; const entityId = entity.id; const entityName = entity.name; const prefix = entityId ? `${entityId}_` : ""; if (runtime.jsonMode) { return { stdout: printJson( { platform: resolved.platform, entity: { id: entity.id, name: entity.name, code: entity.code, prefix, fields: entity.fields.map((f) => ({ fieldKey: f.name, label: f.label, type: f.type, suffix: f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name, })), }, }, runtime.outputOptions ), stderr: "", exitCode: 0, }; } const lines: string[] = []; if (lang === "js" || lang === "javascript") { lines.push(`// ====== 自建应用实体代码模板 [${entityName}] (JS / QuickJS) ======`); lines.push(`const ENTITY_ID = "${entityId}";`); lines.push(`const FIELD_PREFIX = "${prefix}";`); lines.push(""); lines.push("// ── 字段物理键定义 ──"); lines.push("const FIELDS = {"); for (const f of entity.fields) { const suffix = f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name; const safeLabel = f.label.replace(/"/g, '\\"'); lines.push(` "${safeLabel}": FIELD_PREFIX + "${suffix}", // ${f.type || "text"}${f.optional === false ? " [必填]" : ""}`); } lines.push("};"); lines.push(""); lines.push("// ── 写入数据对象示例 ──"); lines.push("const recordData = {"); for (const f of entity.fields) { const safeLabel = f.label.replace(/"/g, '\\"'); lines.push(` [FIELDS["${safeLabel}"]]: "", // ${f.label}`); } lines.push("};"); } else { // 默认 MVEL 模板 lines.push(`// ====== 自建应用实体代码模板 [${entityName}] (MVEL) ======`); lines.push(`String TARGET_ENTITY_ID = "${entityId}";`); lines.push(`String FIELD_PREFIX = "${prefix}";`); lines.push(""); lines.push("// ── 物理字段键常量 ──"); for (const f of entity.fields) { const suffix = f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name; const constName = `FIELD_${f.label.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, "_")}`; lines.push(`String ${constName} = FIELD_PREFIX + "${suffix}"; // ${f.label} (${f.type || "text"})${f.optional === false ? " [必填]" : ""}`); } lines.push(""); lines.push("// ── DataLink 行构建模板 (row.put) ──"); lines.push("Map row = new HashMap();"); for (const f of entity.fields) { const constName = `FIELD_${f.label.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, "_")}`; lines.push(`row.put(${constName}, ""); // ${f.label}`); } } return { stdout: `${lines.join("\n")}\n`, stderr: "", exitCode: 0, }; }