import { getRawBillFlow } from "../../../domains/bill/tools.js"; import { formatValidationIssues, validateBillDraft, loadBillValidationOptions, type BillDraftForm, } from "../../../domains/bill/draft-validation.js"; import { stringOption } from "../../parser.js"; import { printJson } from "../../printer.js"; import type { CliResult } from "../../types.js"; import type { BillActionContext } from "./context.js"; /** * `hose-use bill validate <单号|ID>` * * 读取单据的原始表单,校验派生字段(金额/币种/发票总额/明细草稿状态)是否自洽。 * 这是写入前的最后一道闸门:合思服务端只做弱校验,币种混加、发票总额不同步都能存进去。 */ export async function handleValidate(ctx: BillActionContext): Promise { 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 validate <单号|ID>"); } const raw = await getRawBillFlow(await ctx.getClient(), corpId, target); const flow = raw && typeof raw.flowId === "object" ? (raw.flowId as Record) : undefined; const form = flow && typeof flow.form === "object" ? (flow.form as BillDraftForm) : undefined; if (!flow || !form) { 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 issues = validateBillDraft(form, await loadBillValidationOptions(await ctx.getClient(), corpId, form)); const errors = issues.filter((item) => item.severity === "error"); const warnings = issues.filter((item) => item.severity === "warning"); const billCode = typeof form.title === "string" ? form.title : target; const code = typeof (form as Record).code === "string" ? String((form as Record).code) : target; if (runtime.jsonMode) { return { stdout: printJson( { found: true, corpId, code, title: billCode, ok: errors.length === 0, errorCount: errors.length, warningCount: warnings.length, issues, }, runtime.outputOptions ), stderr: "", exitCode: errors.length === 0 ? 0 : 1, }; } const header = `====== 单据校验 (${code}) ======\n` + ` 企业 : ${corp.name}\n` + ` 标题 : ${billCode}\n` + ` 结论 : ${errors.length === 0 ? "✅ 通过" : "❌ 未通过"}(错误 ${errors.length} / 警告 ${warnings.length})\n`; const body = issues.length > 0 ? formatValidationIssues(issues) : " ✅ 派生字段与必填项一致"; return { stdout: `${header}\n${body}\n`, stderr: "", exitCode: errors.length === 0 ? 0 : 1, }; }