import { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; import { printJson, printTable } from "../printer.js"; import { booleanOption, stringOption, numberOption } from "../parser.js"; import { createEkbClient } from "../../core/auth/ekb.js"; import { searchAndFormatBills, getBillByCodeOrId, getBillFlow, formatBillFlowOperator, getBillRisk, getBillReferences, getBillRelations, getBillAttachments, downloadBillAttachments, getFieldDictionary, approveBill, rejectBill, transferBill, addNodeBill, commentBill, resolveBillStaffIds, } 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-use auth login 登录。" ); } const client = await createEkbClient(corp); const action = parsed.action?.toLowerCase(); const corpId = corp.corpId || corp.id; const actionTarget = () => parsed.args[0] || stringOption(parsed.options, ["code", "id"]); const requireWriteConfirmation = async () => { if (booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return; if (!process.stdin.isTTY || !process.stdout.isTTY) { throw new Error("审批动作会改变单据状态。请显式添加 --yes(或 --confirm)后重试。"); } const { prompt } = await import("../helpers.js"); const answer = await prompt("该操作会改变单据状态,确认继续?输入 yes 继续: "); if (!/^(y|yes|是)$/i.test(answer.trim())) throw new Error("已取消审批动作"); }; const listOption = (keys: string[]): string[] | undefined => { const value = stringOption(parsed.options, keys); if (!value) return undefined; const values = value.split(",").map((item) => item.trim()).filter(Boolean); return values.length ? values : undefined; }; const actionOptions = () => ({ currentStaffId: corp.staffId || corp.credentials.staffId, reminder: booleanOption(parsed.options, ["reminder", "remind"]), keepItSecret: booleanOption(parsed.options, ["keep-it-secret", "secret", "private"]), comment: stringOption(parsed.options, ["comment", "message", "opinion"]), participants: listOption(["participant", "participants"]), approverIds: listOption(["approver", "approver-id", "approverIds", "staff", "staff-id", "to"]), rejectTo: stringOption(parsed.options, ["reject-to", "rejectTo"]), resubmitMethod: (stringOption(parsed.options, ["resubmit-method", "resubmitMethod"]) || "TO_REJECTOR").toUpperCase() as "TO_REJECTOR" | "FROM_START", addNodeType: ((): "PRE_ADD_NODE" | "AFT_ADD_NODE" => { const mode = (stringOption(parsed.options, ["mode", "add-node-type", "addNodeType"]) || "pre").toLowerCase(); return mode === "post" || mode === "after" || mode === "aft" || mode === "aft_add_node" ? "AFT_ADD_NODE" : "PRE_ADD_NODE"; })(), }); const resolveApproverIds = async (values: string[] | undefined): Promise => { if (!values?.length) throw new Error("请通过 --approver-id、--staff 或 --to 指定员工 ID、工号或姓名"); return resolveBillStaffIds(client, corpId, values); }; switch (action) { case "approve": case "agree": { await requireWriteConfirmation(); const target = actionTarget(); if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill approve <单号|ID> --yes"); const result = await approveBill(client, corpId, target, actionOptions()); if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; return { stdout: `审批同意成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 }; } case "reject": case "deny": { await requireWriteConfirmation(); const target = actionTarget(); if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill reject <单号|ID> --comment <原因> --yes"); const options = actionOptions(); if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因"); const result = await rejectBill(client, corpId, target, options); if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; return { stdout: `驳回成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 }; } case "transfer": case "shift": { await requireWriteConfirmation(); const target = actionTarget(); if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill transfer <单号|ID> --approver-id <员工ID> --yes"); const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) }; const result = await transferBill(client, corpId, target, options); if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; return { stdout: `转交审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 }; } case "add-node": case "addnode": case "countersign": case "counter-sign": { await requireWriteConfirmation(); const target = actionTarget(); if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill add-node <单号|ID> --approver-id <员工ID> --yes"); const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) }; const result = await addNodeBill(client, corpId, target, options); if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; return { stdout: `加签审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 }; } case "comment": case "remark": { await requireWriteConfirmation(); const target = actionTarget(); if (!target) throw new Error("请提供单号或单据 ID: hose-use bill comment <单号|ID> --comment <内容> --yes"); const result = await commentBill(client, corpId, target, actionOptions()); if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; return { stdout: `单据评论成功\n单号: ${result.billCode || target}\n流程 ID: ${result.flowId}\n`, stderr: "", exitCode: 0 }; } 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, }; } const withRisk = booleanOption(parsed.options, ["risk", "with-risk", "audit"]); const riskReports = withRisk ? await Promise.all(bills.map((bill) => getBillRisk(client, corpId, bill.billId || bill.billCode))) : []; if (runtime.jsonMode) { return { stdout: printJson( { corpId, corpName: corp.name, count: bills.length, bills: bills.map((bill, index) => withRisk ? { ...bill, risk: riskReports[index] ?? null } : bill), }, 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}`); } } if (withRisk) { const risk = riskReports[i]; outputs.push(`\n --- 费控风控与合规风险提示 ---`); if (!risk) { outputs.push(" (未找到审批流程风控快照)"); } else { outputs.push(` 风控流程 ID : ${risk.flowId}`); outputs.push(` 预算超限 : ${risk.budgetExceeded ? "是" : "否"}`); if (risk.warnings.length === 0 && risk.invoiceWarnings.length === 0) { outputs.push(" 风险预警 : (暂无风险预警)"); } else { for (const warning of risk.warnings) { outputs.push(` [${warning.riskLevel || "提示"}] ${warning.controlName || warning.title || warning.type || "风控规则"}: ${warning.messages.join(";") || "-"}`); } outputs.push(` 发票风险 : ${risk.invoiceWarnings.length} 条`); } } } } 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-use 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 || "-", formatBillFlowOperator(entry.operator, entry.automatic, entry.operator?.id?.toLowerCase().includes("ebot")), entry.durationMs !== undefined ? `${Math.round(entry.durationMs / 1000)} 秒` : "-", entry.skipped ? "自动跳过" : 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-use 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 "budget": case "budgets": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose-use bill budget <单号|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, flowId: report.flowId, budgetExceeded: report.budgetExceeded, budget: report.budget || {} }, runtime.outputOptions), stderr: "", exitCode: 0 }; } const budget = report.budget || {}; const output = [ `====== 单据预算状态 (流程: ${report.flowId}) ======`, `预算超限: ${report.budgetExceeded ? "是" : "否"}`, `状态: ${typeof budget.status === "string" ? budget.status : "-"}`, `可用余额: ${budget.availableAmount ?? budget.available ?? "-"}`, `占用金额: ${budget.occupiedAmount ?? budget.occupied ?? "-"}`, `预算明细: ${Object.keys(budget).length ? JSON.stringify(budget) : "-"}`, "", ].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-use 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.dimensions.length ? report.dimensions.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 "relations": case "relation": case "links": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose-use bill relations <单号|ID>"); const report = await getBillRelations(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 rows: string[][] = []; const visit = (node: typeof report.relations[number], depth = 0) => { rows.push([ `${" ".repeat(depth)}${node.relation}`, node.code || node.id || "-", node.title || "-", node.amount || "-", ]); for (const child of node.children) visit(child, depth + 1); }; for (const node of report.relations) visit(node); const output = [ `====== 单据关联关系 (单号: ${report.billCode || target}) ======`, `标题: ${report.title || "-"}`, rows.length ? printTable(["关系", "关联 ID/单号", "标题/名称", "金额"], rows) : "暂无可识别的前置单据、冲借款或合同关联", "", ].join("\n"); return { stdout: output, stderr: "", exitCode: 0 }; } case "attachments": case "attachment": case "files": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose-use bill attachments <单号|ID>"); const report = await getBillAttachments(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 rows = report.attachments.map((item) => [item.fileName || "-", item.fileId || "-", item.key || "-", item.url || "-"]); const output = [ `====== 单据附件 (单号: ${report.billCode || target}) ======`, report.attachments.length ? printTable(["文件名", "fileId", "key", "URL"], rows) : "暂无附件或发票原件", "", ].join("\n"); return { stdout: output, stderr: "", exitCode: 0 }; } case "download": case "file-download": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose-use bill download <单号|ID>"); const outputDir = stringOption(parsed.options, ["output-dir", "dir"]) || `${process.cwd()}/downloads`; const fileId = stringOption(parsed.options, ["file-id", "file"]); const result = await downloadBillAttachments(client, corpId, target, outputDir, fileId); const summary = { corpId, corpName: corp.name, target: result.target, outputDir: result.outputDir, requestedFileId: result.requestedFileId, downloaded: result.downloaded, skipped: result.skipped, }; if (runtime.jsonMode) { return { stdout: printJson(summary, runtime.outputOptions), stderr: "", exitCode: 0 }; } const rows = result.downloaded.map((item) => [item.fileName || item.key || item.fileId || "-", item.bytes, item.path]); const output = [ `====== 单据附件下载 (单号: ${target}) ======`, `输出目录: ${result.outputDir}`, rows.length ? printTable(["文件名", "字节数", "本地路径"], rows) : "没有可下载的附件", result.skipped ? `跳过 ${result.skipped} 个缺少下载地址的附件` : "", "", ].filter(Boolean).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-use 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 <单号> [--risk], refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`); } }