import { afterEach, expect, mock, spyOn, test } from "bun:test"; import { getDatabase, closeDatabase } from "../../../core/db/index.js"; import { ApprovalRepository } from "../../../domains/approval/repository.js"; import * as bills from "../../../domains/bill/tools.js"; import { handleAiProDecide } from "./session.js"; afterEach(() => { closeDatabase(); }); for (const action of ["approve", "reject"] as const) { test(`blocks cross-corp ${action} before creating a client or changing the run`, async () => { const repo = new ApprovalRepository(getDatabase(":memory:")); const run = repo.createApprovalRun({ documentSn: "SAME-SN", corpId: "corp-A" }); repo.injectFindings(run.id, [{ clauseText: "invoice", strictness: "硬性", checkStatus: action === "approve" ? "PASS" : "FAIL" }]); const getClient = mock(async () => ({ client: {} as any, corpId: "corp-B" })); await expect(handleAiProDecide({ repo, corpId: "corp-B", command: action, positional: [action, run.shortId!], parsed: { options: { apply: true, yes: true, opinion: "checked" } }, getClient } as any)).rejects.toThrow("不一致"); expect(getClient).not.toHaveBeenCalled(); expect(repo.getRunById(run.id)?.decision).toBe("PENDING"); }); } test("uses the checked corp client for same-corp approval", async () => { const repo = new ApprovalRepository(getDatabase(":memory:")); const run = repo.createApprovalRun({ documentSn: "SAME-SN", corpId: "corp-A" }); repo.injectFindings(run.id, [{ clauseText: "invoice", strictness: "硬性", checkStatus: "PASS" }]); const approve = spyOn(bills, "approveBill").mockResolvedValue({} as any); const client = {} as any; try { const result = await handleAiProDecide({ repo, corpId: "corp-A", command: "approve", positional: ["approve", run.shortId!], parsed: { options: { apply: true, yes: true, opinion: "checked" } }, getClient: async () => ({ client, corpId: "corp-A" }), rawArgs: [], operator: "staff" } as any); expect(result.exitCode).toBe(0); expect(approve).toHaveBeenCalledWith(client, "corp-A", "SAME-SN", { comment: "checked" }); } finally { approve.mockRestore(); } });