import { KyInstance } from "ky"; import { BusinessError, NotFoundError, ValidationError } from "../../core/errors.js"; import { ApprovalRepository } from "./repository.js"; import { parseRuleBody } from "./parser.js"; import { ApprovalDecision, ApprovalFindingRecord, ApprovalGatewayBlockedError, ApprovalRunRecord, FindingCheckStatus, isValidFindingCheckStatus, } from "./types.js"; import { ApprovalGatewayPolicy, defaultGatewayPolicy, evaluateGatewayPolicy, GatewayPolicyConfig, } from "./gateway.js"; import { getBillByCodeOrId, approveBill, rejectBill, commentBill } from "../bill/tools.js"; import type { FormattedBill } from "../bill/types.js"; export interface InjectPointsResult { run: ApprovalRunRecord; findings: ApprovalFindingRecord[]; bill: FormattedBill; scope: string; } export interface DecideAuditOptions { requestedAction?: "approve" | "reject" | "comment"; apply?: boolean; comment?: string; gatewayConfig?: Partial; } export interface DecideAuditResult { run: ApprovalRunRecord; decision: ApprovalDecision; decisionSummary: string; hardFailedCount: number; elasticFailedCount: number; suggestFailedCount: number; specialFailedCount: number; appliedAction?: "approve" | "reject" | "comment"; actionResult?: unknown; } export class ApprovalService { private repo: ApprovalRepository; private gatewayPolicy: ApprovalGatewayPolicy; constructor(repo?: ApprovalRepository, gatewayPolicy?: ApprovalGatewayPolicy) { this.repo = repo ?? new ApprovalRepository(); this.gatewayPolicy = gatewayPolicy ?? defaultGatewayPolicy; } /** * 第一步:规则注入,提取单据明细级审核要点清单 */ public async injectAuditPoints( client: KyInstance, corpId: string, documentSn: string, options: { scope?: string | number } = {} ): Promise { // 1. 获取单据详情 const bills = await getBillByCodeOrId(client, corpId, documentSn); if (bills.length === 0) { throw new NotFoundError(`在当前企业下未找到单号或 ID 为 [${documentSn}] 的单据`); } const bill = bills[0]; const actualSn = bill.billCode || documentSn; // 2. 匹配适用场景 (Scope) let scopeDetail = options.scope !== undefined ? this.repo.getScopeDetail(options.scope) : null; if (!scopeDetail) { const allScopes = this.repo.listScopes(); if (allScopes.length === 0) { throw new BusinessError("规约库中暂无任何生效规则,请先使用 hose-use rule add <场景> <正文> 新增规则"); } // 自动启发式场景匹配 const candidates = [bill.title, bill.stage, bill.billName].filter(Boolean) as string[]; let matchedSummary = allScopes.find((s) => candidates.some((c) => c.includes(s.scope) || s.scope.includes(c)) ); // 差旅特化匹配 if (!matchedSummary && candidates.some((c) => /差旅|出差|trip|hotel|住宿/i.test(c))) { matchedSummary = allScopes.find((s) => /差旅|出差/i.test(s.scope)); } // 严禁静默回退到首个场景:用错规则集审单据(如差旅规则审办公费)比直接报错危险得多 if (!matchedSummary) { const available = allScopes.map((s) => s.scope).join("、"); if (options.scope !== undefined) { throw new NotFoundError(`指定场景 [${options.scope}] 不存在或无效,当前可用场景: ${available}`); } throw new ValidationError( `无法为单据 [${documentSn}] 自动匹配适用场景,请通过 --scope 显式指定。当前可用场景: ${available}` ); } scopeDetail = this.repo.getScopeDetail(matchedSummary.index); } if (!scopeDetail || scopeDetail.rules.length === 0) { throw new NotFoundError(`适用场景 [${options.scope ?? "自动匹配"}] 下暂无任何生效规则`); } // 3. 提取所有规则的 AST 条款要点 const clauseInputs: Array<{ ruleId: string; ruleCode: number; clauseText: string; strictness: any; }> = []; for (const rule of scopeDetail.rules) { const parsed = parseRuleBody(rule.body); for (const clause of parsed.clauses) { clauseInputs.push({ ruleId: rule.id, ruleCode: rule.code, clauseText: clause.action, strictness: clause.strictness, }); } } if (clauseInputs.length === 0) { throw new BusinessError(`场景 [${scopeDetail.scope}] 下的规则正文中未解析出任何合法判定要点 ([动作]{级别})`); } // 4. 为单据创建/重置审批运行记录 const run = this.repo.createOrResetApprovalRun({ documentSn: actualSn, flowId: bill.billId, corpId, scope: scopeDetail.scope, decision: "PENDING", matchedRulesCount: clauseInputs.length, failedRulesCount: 0, documentSnapshot: JSON.stringify(bill), }); // 5. 注入待核验要点清单 (Checklist) const findings = this.repo.injectFindings( run.id, clauseInputs.map((c) => ({ ruleId: c.ruleId, clauseText: c.clauseText, strictness: c.strictness, checkStatus: "PENDING", })) ); return { run, findings, bill, scope: scopeDetail.scope, }; } /** * 查看单据当前审核清单状态 */ public getAuditChecklist(documentSn: string, corpId?: string) { return this.repo.getAuditChecklist(documentSn, corpId); } /** * 第二步:对注入的要点逐项进行事实核验判定 */ public evaluateAuditPoints( documentSn: string, evaluations: Array<{ index?: number; id?: string; status: FindingCheckStatus; evidence?: string; reasoning?: string; }>, corpId?: string, ): ApprovalFindingRecord[] { const { run, findings } = this.repo.getAuditChecklist(documentSn, corpId); if (!run || findings.length === 0) { throw new ApprovalGatewayBlockedError( `[审批链路阻断] 单据 [${documentSn}] 尚未注入任何审核要点清单(要点列表为空)。\n` + `在没有注入审核要点的情况下,无法进行事实核验!\n` + `请先执行: hose-aipro points ${documentSn} 注入审核要点清单。` ); } if (evaluations.some(item => !isValidFindingCheckStatus(item.status))) { throw new ValidationError("核验状态必须为 PENDING、PASS、FAIL 或 SKIP"); } for (const item of evaluations) { let target: ApprovalFindingRecord | undefined; if (item.id) { target = findings.find((f) => f.id === item.id); } else if (item.index !== undefined) { target = findings[item.index - 1]; } if (!target) { throw new NotFoundError(`未找到要点: ${item.id ?? `#${item.index}`}`); } this.repo.updateFinding(target.id, { checkStatus: item.status, evidence: item.evidence, reasoning: item.reasoning, }); } return this.repo.getFindingsByRunId(run.id); } /** * 第三步:确定性网关裁决与下游流转 */ public async decideAudit( client: KyInstance, corpId: string, documentSn: string, options: DecideAuditOptions = {} ): Promise { const { run, findings } = this.repo.getAuditChecklist(documentSn, corpId); if (!run) { throw new ApprovalGatewayBlockedError( `[审批链路阻断] 单据 [${documentSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` + `网关卡点生效:审核要点未注入前,审批链路物理切断,绝对禁止进入审批决策!\n` + `请先执行: hose-aipro points ${documentSn} 注入审核要点。` ); } // 确定性网关仲裁:由独立的可配置网关策略脚本执行(执行核心门禁与裁决计算) const gatewayResult = evaluateGatewayPolicy( { documentSn, findings, requestedAction: options.requestedAction, opinion: options.comment, }, options.gatewayConfig ?? this.gatewayPolicy.getConfig() ); const { decision, decisionSummary, hardFailedCount, elasticFailedCount, suggestFailedCount, specialFailedCount, } = gatewayResult; // 4. 更新数据库中的运行记录状态 this.repo.updateApprovalRun(run.id, { decision, decisionSummary, failedRulesCount: gatewayResult.analysis.failedFindings.length, }); let appliedAction = options.requestedAction; let actionResult: unknown = undefined; // 5. 如果开启了 --apply,由网关在内部安全受控地调用下游接口。 // 远端失败时把本地运行标记为 ERROR,避免数据库显示“已决策”但实际未执行。 if (options.apply) { if (!appliedAction) { appliedAction = decision === "REJECT" ? "reject" : decision === "APPROVE" || decision === "PASS_WITH_NOTE" ? "approve" : "comment"; } try { if (appliedAction === "reject") { actionResult = await rejectBill(client, corpId, documentSn, { comment: decisionSummary, }); } else if (appliedAction === "approve") { actionResult = await approveBill(client, corpId, documentSn, { comment: decisionSummary, }); } else { actionResult = await commentBill(client, corpId, documentSn, { comment: decisionSummary, }); } } catch (error) { const message = error instanceof Error ? error.message : String(error); this.repo.updateApprovalRun(run.id, { decision: "ERROR", decisionSummary: `${decisionSummary}\n[下游执行失败] ${message}`, }); throw error; } } const updatedRun = this.repo.getRunById(run.id)!; return { run: updatedRun, decision, decisionSummary, hardFailedCount, elasticFailedCount, suggestFailedCount, specialFailedCount, appliedAction, actionResult, }; } }