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, 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 "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 <单号>, schema, link <单号>`); } }