import { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; import { printJson, printTable } from "../printer.js"; import { stringOption, numberOption } from "../parser.js"; import { createEkbClient } from "../../core/auth/ekb.js"; import { searchAndFormatBills, getBillByCodeOrId, getBillFlow, getBillRisk, getBillReferences, getFieldDictionary, } from "../../domains/bill/tools.js"; export async function handleBillCommand( parsed: CliParsedArgs, runtime: CliRuntime ): Promise { const corp = runtime.selectedCorp; if (!corp) { throw new Error( "未指定或未找到有效企业。请通过 --corp= 指定企业,或运行 hose auth login 登录。" ); } const client = await createEkbClient(corp); const action = parsed.action?.toLowerCase(); const corpId = corp.corpId || corp.id; switch (action) { case "list": case "search": case undefined: { const code = stringOption(parsed.options, ["code", "c"]); const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]); const stage = stringOption(parsed.options, ["stage"]); const state = stringOption(parsed.options, ["state", "s"]); const count = numberOption(parsed.options, ["count", "limit", "n"], 20); const result = await searchAndFormatBills(client, corpId, { code, keyword, stage, state, count, }); if (runtime.jsonMode) { return { stdout: printJson( { corpId, corpName: corp.name, total: result.total, returned: result.returned, items: result.items, }, runtime.outputOptions ), stderr: "", exitCode: 0, }; } const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", "提交时间"]; const rows = result.items.map((b, idx) => [ idx + 1, b.billCode, b.billName, b.stage || "-", b.state || "-", b.amount || "-", b.submitDate || b.createTime || "-", ]); const tableOutput = printTable(headers, rows); const title = `====== 单据与费用明细列表 (企业: ${corp.name} | 总数: ${result.total} | 本次返回: ${result.returned}) ======\n`; const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`; return { stdout: title + tableOutput + tip, stderr: "", exitCode: 0, }; } case "get": case "show": case "find": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); if (!target) { throw new Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>"); } const bills = await getBillByCodeOrId(client, corpId, target); if (bills.length === 0) { if (runtime.jsonMode) { return { stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }), stderr: "", exitCode: 1, }; } return { stdout: "", stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到单号或 ID 为 [${target}] 的单据\n`, exitCode: 1, }; } if (runtime.jsonMode) { return { stdout: printJson( { corpId, corpName: corp.name, count: bills.length, bills, }, runtime.outputOptions ), stderr: "", exitCode: 0, }; } const outputs: string[] = []; for (let i = 0; i < bills.length; i++) { const b = bills[i]; outputs.push(`\n====== 单据详情 [${i + 1}/${bills.length}] (单号: ${b.billCode}) ======`); outputs.push(` 单据 ID : ${b.billId}`); outputs.push(` 单据名称 : ${b.billName}`); if (b.title) outputs.push(` 单据标题 : ${b.title}`); if (b.stage) outputs.push(` 业务阶段 : ${b.stage}`); if (b.state) outputs.push(` 审批状态 : ${b.state}`); if (b.amount) outputs.push(` 单据金额 : ${b.amount}`); if (b.submitterId) outputs.push(` 提交人员 : ${b.submitterId}`); if (b.submitDate) outputs.push(` 提交时间 : ${b.submitDate}`); outputs.push(` 创建时间 : ${b.createTime}`); outputs.push(` 更新时间 : ${b.updateTime}`); outputs.push(`\n --- 结构化表单字段明细 ---`); const detailEntries = Object.entries(b.details); if (detailEntries.length === 0) { outputs.push(` (无额外字段数据)`); } else { const maxKeyLen = Math.max(...detailEntries.map(([k]) => k.length), 0); for (const [k, v] of detailEntries) { const formattedVal = typeof v === "object" ? JSON.stringify(v) : String(v); outputs.push(` ${k.padEnd(maxKeyLen + 2)}: ${formattedVal}`); } } } return { stdout: outputs.join("\n") + "\n", stderr: "", exitCode: 0, }; } case "schema": case "schemas": case "entities": { const { entities } = await getFieldDictionary(client, corpId, true); if (runtime.jsonMode) { return { stdout: printJson( { corpId, corpName: corp.name, totalEntities: entities.length, entities, }, runtime.outputOptions ), stderr: "", exitCode: 0, }; } const headers = ["#", "实体 ID", "实体名称", "类型", "字段数"]; const rows = entities.map((e, idx) => [ idx + 1, e.id, e.name || "-", e.type || "-", e.fields.length, ]); const tableOutput = printTable(headers, rows); const title = `====== 单据实体与数据模型字典 (企业: ${corp.name} | 共 ${entities.length} 个实体) ======\n`; return { stdout: title + tableOutput + "\n", stderr: "", exitCode: 0, }; } case "flow": case "records": case "timeline": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose bill flow <单号|ID>"); const flow = await getBillFlow(client, corpId, target); if (!flow) { if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 }; return { stdout: "", stderr: `[NOT FOUND] 未找到单据流程: ${target}\n`, exitCode: 1 }; } if (runtime.jsonMode) { return { stdout: printJson({ corpId, corpName: corp.name, ...flow }, runtime.outputOptions), stderr: "", exitCode: 0 }; } const historyRows = flow.history.map((entry) => [ entry.time ? new Date(entry.time).toLocaleString("zh-CN") : "-", entry.nodeName || "-", entry.action || "-", entry.operator?.name || (entry.automatic ? "系统" : "-"), entry.comment || "-", ]); const pendingRows = flow.pending.map((node) => [ node.state || "-", node.name || "-", node.type || "-", node.approver?.name || node.approvers?.map((person) => person.name).filter(Boolean).join(", ") || "-", ]); const output = [ `====== 审批流程 (单号: ${flow.billCode || target} | 状态: ${flow.state || "-"}) ======`, `流程 ID: ${flow.flowId || "-"} 当前节点: ${flow.currentNode || "-"}`, "", "--- 历史流转 ---", flow.history.length ? printTable(["时间", "节点", "动作", "处理人", "意见"], historyRows) : " (暂无历史记录)", "", "--- 后续节点 ---", flow.pending.length ? printTable(["状态", "节点", "类型", "审批人"], pendingRows) : " (暂无后续节点)", "", ].join("\n"); return { stdout: output, stderr: "", exitCode: 0 }; } case "risk": case "review": case "warnings": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose bill risk <单号|ID>"); const report = await getBillRisk(client, corpId, target); if (!report) { if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 }; return { stdout: "", stderr: `[NOT FOUND] 未找到单据风控结果: ${target}\n`, exitCode: 1 }; } if (runtime.jsonMode) { return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 }; } const warningRows = report.warnings.map((warning) => [ warning.riskLevel || "-", warning.type || "-", warning.controlName || warning.title || "-", warning.messages.join(";") || "-", ]); const output = [ `====== 单据风控审查 (流程: ${report.flowId}) ======`, `预算超限: ${report.budgetExceeded ? "是" : "否"}`, "", "--- 风险预警 ---", report.warnings.length ? printTable(["等级", "类型", "规则", "提示"], warningRows) : " (暂无风险预警)", `发票风险: ${report.invoiceWarnings.length} 条`, "", ].join("\n"); return { stdout: output, stderr: "", exitCode: 0 }; } case "refs": case "references": case "resolve": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose bill refs <单号|ID>"); const report = await getBillReferences(client, corpId, target); if (!report) { if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 }; return { stdout: "", stderr: `[NOT FOUND] 未找到单据引用: ${target}\n`, exitCode: 1 }; } if (runtime.jsonMode) { return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 }; } const person = (value: typeof report.submitter) => value ? `${value.name || "未解析"}${value.code ? ` (${value.code})` : ""} [${value.id}]` : "-"; const output = [ `====== 单据引用解析 (单号: ${report.billCode || target}) ======`, `标题: ${report.title || "-"}`, `提交人: ${person(report.submitter)}`, `归属人: ${person(report.owner)}`, `费用承担部门: ${report.department?.path || report.department?.name || "-"}${report.department?.id ? ` [${report.department.id}]` : ""}`, `法人实体: ${report.legalEntity ? `${report.legalEntity.name || "未解析"}${report.legalEntity.id ? ` [${report.legalEntity.id}]` : ""}` : "-"}`, `费用类型: ${report.feeTypes.length ? report.feeTypes.map((item) => `${item.name || "未解析"}${item.code ? ` (${item.code})` : ""} [${item.id}]`).join("、") : "-"}`, report.unresolved.length ? `未解析 ID: ${report.unresolved.join("、")}` : "引用均已解析", "", ].join("\n"); return { stdout: output, stderr: "", exitCode: 0 }; } case "link": case "url": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "c"]); if (!target) { return { stdout: "", stderr: "用法: hose bill link <单号或ID>", exitCode: 1, }; } const items = await getBillByCodeOrId(client, corpId, target); if (!items || items.length === 0) { return { stdout: "", stderr: `未找到单据: ${target}`, exitCode: 1, }; } const item = items[0]; const billId = item.billId; const billCode = item.billCode || target; const baseUrl = (corp.baseUrl || "https://app.ekuaibao.com").replace(/\/+$/, ""); const webUrl = `${baseUrl}/#/invoice/detail?id=${encodeURIComponent(billId)}&corporationId=${encodeURIComponent(corpId)}`; if (runtime.jsonMode) { return { stdout: printJson( { code: billCode, id: billId, corpId, corpName: corp.name, url: webUrl, }, runtime.outputOptions ), stderr: "", exitCode: 0, }; } const text = [ `====== 合思单据 Web 直达链接 ======`, ` 单据编号: ${billCode}`, ` 单据 ID : ${billId}`, ` 所属企业: ${corp.name} (${corpId})`, ` 直达链接:`, ` ${webUrl}`, ``, `Markdown 链接: [查看单据 ${billCode}](${webUrl})`, ].join("\n"); return { stdout: text + "\n", stderr: "", exitCode: 0, }; } default: throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号>, refs <单号>, flow <单号>, risk <单号>, schema, link <单号>`); } }