304 lines
11 KiB
TypeScript
304 lines
11 KiB
TypeScript
import { getBillByCodeOrId, getBillRisk, searchAndFormatBills, traceBillFlowDetail } from "../../../domains/bill/tools.js";
|
||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||
import type { CliResult } from "../../types.js";
|
||
import type { BillActionContext } from "./context.js";
|
||
|
||
export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
||
const { parsed, runtime, corp, corpId } = ctx;
|
||
const mine = booleanOption(parsed.options, ["mine", "my", "self"]);
|
||
if (mine) {
|
||
const { handleTaskCommand } = await import("./../task.js");
|
||
return handleTaskCommand(
|
||
{
|
||
...parsed,
|
||
area: "task",
|
||
action: "submitted",
|
||
},
|
||
runtime
|
||
);
|
||
}
|
||
|
||
const code = stringOption(parsed.options, ["code", "c"]);
|
||
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
|
||
const searchFields = stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "sf"]);
|
||
const stage = stringOption(parsed.options, ["stage"]);
|
||
const state = stringOption(parsed.options, ["state", "s"]);
|
||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
|
||
const since = stringOption(parsed.options, ["since", "days", "d"]);
|
||
const startDate = stringOption(parsed.options, ["start-date", "startDate", "from", "start"]);
|
||
const endDate = stringOption(parsed.options, ["end-date", "endDate", "to", "end"]);
|
||
const rawOrder = stringOption(parsed.options, ["order", "sort", "direction"]);
|
||
const order = rawOrder && /asc/i.test(rawOrder) ? "ASC" : "DESC";
|
||
const filterBy = stringOption(parsed.options, ["filter-by", "filterBy", "filter"]);
|
||
const select = stringOption(parsed.options, ["select", "fields"]);
|
||
const distinct = booleanOption(parsed.options, ["distinct"]);
|
||
|
||
const result = await searchAndFormatBills(await ctx.getClient(), corpId, {
|
||
code,
|
||
keyword,
|
||
searchFields,
|
||
stage,
|
||
state,
|
||
count,
|
||
since,
|
||
startDate,
|
||
endDate,
|
||
order,
|
||
filterBy,
|
||
select,
|
||
distinct,
|
||
});
|
||
|
||
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 filterSummary: string[] = [];
|
||
if (since) filterSummary.push(`近 ${since}`);
|
||
if (startDate || endDate) filterSummary.push(`${startDate || "起"} ~ ${endDate || "止"}`);
|
||
if (code) filterSummary.push(`单号: ${code}`);
|
||
if (keyword) {
|
||
filterSummary.push(searchFields ? `关键字: ${keyword} (字段: ${searchFields})` : `关键字: ${keyword}`);
|
||
}
|
||
if (stage) filterSummary.push(`阶段: ${stage}`);
|
||
if (state) filterSummary.push(`状态: ${state}`);
|
||
const filterTag = filterSummary.length > 0 ? ` | 筛选: ${filterSummary.join(", ")}` : "";
|
||
|
||
const tableOutput = printTable(headers, rows);
|
||
const title = `====== 单据与费用明细列表 (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
|
||
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
|
||
|
||
return {
|
||
stdout: title + tableOutput + tip,
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
export async function handleGet(ctx: BillActionContext): Promise<CliResult> {
|
||
const { parsed, runtime, corp, corpId } = ctx;
|
||
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(await ctx.getClient(), 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(async (bill) => getBillRisk(await ctx.getClient(), 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,
|
||
};
|
||
}
|
||
|
||
export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
||
const { parsed, runtime, corp, corpId } = ctx;
|
||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "target", "flowId"]);
|
||
if (!target) {
|
||
throw new Error("请提供要穿透诊断的单号或单据/流程 ID: hose-use bill trace <单号|ID> 或 hose-use flow get <单号|ID>");
|
||
}
|
||
|
||
const client = await ctx.getClient();
|
||
const legacyInvoiceOption = ["no-invoice", "noInvoice", "basic"].some((key) => Object.hasOwn(parsed.options, key));
|
||
const compatibilityNotice = legacyInvoiceOption
|
||
? "提示: --no-invoice/--noInvoice/--basic 仅为旧版兼容参数;穿透诊断不补充加载发票详情,传入这些参数不会改变结果。\n"
|
||
: "";
|
||
const report = await traceBillFlowDetail(client, corpId, target);
|
||
|
||
if (!report.found) {
|
||
if (runtime.jsonMode) {
|
||
return {
|
||
stdout: printJson(report, runtime.outputOptions),
|
||
stderr: compatibilityNotice,
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
return {
|
||
stdout: "",
|
||
stderr: `${compatibilityNotice}[NOT FOUND] 在企业 [${corp.name}] 下未找到匹配 [${target}] 的单据或审批流实例\n 诊断提示: ${report.diagnostic.advice}\n`,
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
if (runtime.jsonMode) {
|
||
return {
|
||
stdout: printJson(
|
||
{
|
||
corpId,
|
||
corpName: corp.name,
|
||
...report,
|
||
},
|
||
runtime.outputOptions
|
||
),
|
||
stderr: compatibilityNotice,
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
const approverNames = report.pendingApprovers
|
||
.map((p) => (p.name ? `${p.name}${p.code ? ` (${p.code})` : ""}` : p.id))
|
||
.filter(Boolean)
|
||
.join("、");
|
||
|
||
const lines: string[] = [
|
||
`====== 单据全域穿透诊断 [${report.billCode || report.target}] ======`,
|
||
printKeyValue({
|
||
"单据编号": report.billCode || "-",
|
||
"单据 ID": report.billId || "-",
|
||
"流程实例 (flowId)": report.flowId || "-",
|
||
"单据类型": report.specificationName
|
||
? `${report.specificationName}${report.specificationId ? ` (${report.specificationId})` : ""}`
|
||
: "-",
|
||
"单据标题": report.title || "-",
|
||
"提报人员": report.submitter
|
||
? `${report.submitter.name || "-"}${report.submitter.id ? ` (${report.submitter.id})` : ""}`
|
||
: "-",
|
||
"归属部门": report.department || "-",
|
||
"提报时间": report.submitDate || "-",
|
||
"单据金额": report.amount || "-",
|
||
"全局流转状态": `${report.state || "-"} (${report.rawState || "-"})`,
|
||
}),
|
||
"",
|
||
"── 🩺 待办与审批诊断 ──",
|
||
` 阶段判定 : ${report.diagnostic.stageLabel}`,
|
||
` 当前驻留节点: ${report.currentNode?.name || "-"}${report.currentNode?.id ? ` (${report.currentNode.id})` : ""}`,
|
||
` 待办处理人: ${approverNames || "(当前无待办审批人)"}`,
|
||
` 是否可审批: ${report.diagnostic.canApprove === null ? "未知(需核对当前身份的实际待办与权限)" : report.diagnostic.canApprove ? "✅ 是 (支持执行同意/驳回)" : "❌ 否 (当前不可审批)"}`,
|
||
` 诊断结论 : ${report.diagnostic.summary}`,
|
||
` 排障建议 : ${report.diagnostic.advice}`,
|
||
];
|
||
|
||
if (report.timeline.length > 0) {
|
||
lines.push("");
|
||
lines.push("── ⏱️ 审批流转历史轨迹 (Timeline) ──");
|
||
const timelineRows = report.timeline.map((item) => [
|
||
`#${item.index}`,
|
||
item.time || "-",
|
||
item.nodeName || "-",
|
||
item.operator?.name || item.operator?.id || (item.automatic ? "自动执行" : "-"),
|
||
item.action || item.state || "-",
|
||
item.comment ? (item.comment.length > 30 ? item.comment.slice(0, 30) + "..." : item.comment) : "-",
|
||
]);
|
||
lines.push(
|
||
printTable(
|
||
["#", "时间", "节点名称", "操作人", "动作", "审批意见"],
|
||
timelineRows
|
||
)
|
||
);
|
||
}
|
||
|
||
return {
|
||
stdout: `${lines.join("\n")}\n`,
|
||
stderr: compatibilityNotice,
|
||
exitCode: 0,
|
||
};
|
||
}
|