feat(P19AI1-1,P19AI1-2): 实现AI建议引擎与权限门禁后端
这个提交包含在:
@@ -0,0 +1,142 @@
|
||||
const { AiProviderError, buildAiProvider, __testables } = require("../../../src/services/ai/provider");
|
||||
|
||||
describe("AI provider service", () => {
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("preserves base path for openai-compatible chat completions endpoint", () => {
|
||||
expect(__testables.resolveChatCompletionsUrl("https://example.com/v1")).toBe(
|
||||
"https://example.com/v1/chat/completions",
|
||||
);
|
||||
expect(__testables.resolveChatCompletionsUrl("https://example.com/v1/")).toBe(
|
||||
"https://example.com/v1/chat/completions",
|
||||
);
|
||||
expect(__testables.resolveChatCompletionsUrl("https://example.com/chat/completions")).toBe(
|
||||
"https://example.com/chat/completions",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns deterministic mock suggestion payload", async () => {
|
||||
const provider = buildAiProvider({ aiProvider: "mock" });
|
||||
const result = await provider.generateSuggestion({
|
||||
targetType: "reimbursement",
|
||||
snapshot: {
|
||||
targetId: "r-1",
|
||||
formNumber: "BX-001",
|
||||
status: "reviewing",
|
||||
totalAmount: "123.00",
|
||||
itemCount: 2,
|
||||
budgetHint: { exceedsBudget: false, exceedsThreshold: true },
|
||||
invoiceSummary: { abnormalCount: 1 },
|
||||
},
|
||||
promptSpec: { systemPrompt: "system", userPrompt: "user" },
|
||||
});
|
||||
|
||||
expect(result.provider).toBe("mock");
|
||||
expect(result.suggestion.summary).toContain("BX-001");
|
||||
expect(result.suggestion.riskHints.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("maps http 4xx failures to upstream_4xx", async () => {
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 400,
|
||||
json: vi.fn().mockResolvedValue({ error: "bad_request" }),
|
||||
});
|
||||
|
||||
const provider = buildAiProvider({
|
||||
aiProvider: "http",
|
||||
aiBaseUrl: "https://example.com/v1",
|
||||
aiModel: "gpt-test",
|
||||
aiTimeoutMs: 500,
|
||||
});
|
||||
|
||||
await expect(
|
||||
provider.generateSuggestion({
|
||||
targetType: "reimbursement",
|
||||
snapshot: {},
|
||||
promptSpec: { systemPrompt: "system", userPrompt: "user" },
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "upstream_4xx" });
|
||||
});
|
||||
|
||||
it("maps http 5xx failures to upstream_5xx", async () => {
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 503,
|
||||
json: vi.fn().mockResolvedValue({ error: "service_unavailable" }),
|
||||
});
|
||||
|
||||
const provider = buildAiProvider({
|
||||
aiProvider: "http",
|
||||
aiBaseUrl: "https://example.com/v1",
|
||||
aiModel: "gpt-test",
|
||||
aiTimeoutMs: 500,
|
||||
});
|
||||
|
||||
await expect(
|
||||
provider.generateSuggestion({
|
||||
targetType: "purchase_request",
|
||||
snapshot: {},
|
||||
promptSpec: { systemPrompt: "system", userPrompt: "user" },
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "upstream_5xx" });
|
||||
});
|
||||
|
||||
it("maps aborted requests to timeout", async () => {
|
||||
global.fetch = vi.fn().mockRejectedValue({ name: "AbortError" });
|
||||
|
||||
const provider = buildAiProvider({
|
||||
aiProvider: "http",
|
||||
aiBaseUrl: "https://example.com/v1",
|
||||
aiModel: "gpt-test",
|
||||
aiTimeoutMs: 500,
|
||||
});
|
||||
|
||||
await expect(
|
||||
provider.generateSuggestion({
|
||||
targetType: "asset_card",
|
||||
snapshot: {},
|
||||
promptSpec: { systemPrompt: "system", userPrompt: "user" },
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "timeout" });
|
||||
});
|
||||
|
||||
it("rejects invalid json payload from upstream", async () => {
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
choices: [{ message: { content: "```json\nnot-valid-json\n```" } }],
|
||||
usage: {},
|
||||
}),
|
||||
});
|
||||
|
||||
const provider = buildAiProvider({
|
||||
aiProvider: "http",
|
||||
aiBaseUrl: "https://example.com/v1",
|
||||
aiModel: "gpt-test",
|
||||
aiTimeoutMs: 500,
|
||||
});
|
||||
|
||||
await expect(
|
||||
provider.generateSuggestion({
|
||||
targetType: "asset_card",
|
||||
snapshot: {},
|
||||
promptSpec: { systemPrompt: "system", userPrompt: "user" },
|
||||
}),
|
||||
).rejects.toBeInstanceOf(AiProviderError);
|
||||
|
||||
await expect(
|
||||
provider.generateSuggestion({
|
||||
targetType: "asset_card",
|
||||
snapshot: {},
|
||||
promptSpec: { systemPrompt: "system", userPrompt: "user" },
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "invalid_response" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
const {
|
||||
buildAssetSnapshot,
|
||||
buildPurchaseSnapshot,
|
||||
buildReimbursementSnapshot,
|
||||
} = require("../../../src/services/ai/sanitizer");
|
||||
|
||||
describe("AI sanitizer", () => {
|
||||
it("keeps reimbursement whitelist fields only", () => {
|
||||
const snapshot = buildReimbursementSnapshot({
|
||||
id: "r-1",
|
||||
form_number: "BX-001",
|
||||
status: "paid",
|
||||
reimbursement_date: new Date("2026-03-10T00:00:00.000Z"),
|
||||
total_amount: 123.45,
|
||||
items: [
|
||||
{ amount: 100, expense_type: { category: "travel" }, description: "敏感长文本" },
|
||||
],
|
||||
invoice_pool_items: [{ status: "verified", invoice_number: "123456" }],
|
||||
owner: { id: "owner-1", name: "张三" },
|
||||
owner_id: "owner-1",
|
||||
payment_voucher_no: "PV-001",
|
||||
budgetHint: { controlMode: "warn", exceedsThreshold: true, exceedsBudget: false, nextUsagePercent: 90 },
|
||||
pendingWorkflow: { stepName: "财务复核", assigneeRole: "finance_mgr" },
|
||||
});
|
||||
|
||||
expect(snapshot).toEqual(
|
||||
expect.objectContaining({
|
||||
formNumber: "BX-001",
|
||||
status: "paid",
|
||||
totalAmount: "123.45",
|
||||
itemCount: 1,
|
||||
}),
|
||||
);
|
||||
expect(snapshot).not.toHaveProperty("owner");
|
||||
expect(snapshot).not.toHaveProperty("paymentVoucherNo");
|
||||
expect(JSON.stringify(snapshot)).not.toContain("123456");
|
||||
expect(JSON.stringify(snapshot)).not.toContain("张三");
|
||||
});
|
||||
|
||||
it("keeps purchase whitelist fields only", () => {
|
||||
const snapshot = buildPurchaseSnapshot({
|
||||
id: "p-1",
|
||||
request_no: "PR-001",
|
||||
status: "approved",
|
||||
title: "办公电脑采购计划办公电脑采购计划办公电脑采购计划办公电脑采购计划办公电脑采购计划",
|
||||
currency_code: "CNY",
|
||||
total_amount: 8888,
|
||||
supplier: { code: "SUP-1", name: "海音达供应商" },
|
||||
legal_entity: { code: "HY", name: "海音达" },
|
||||
cost_center: { code: "IT001", name: "IT中心" },
|
||||
budget_pool: { code: "B-001", name: "年度预算" },
|
||||
items: [{ is_asset_candidate: true, description: "敏感描述" }],
|
||||
order_archive: { po_no: "PO-001", contract_no: "CT-001", archived_at: new Date("2026-03-10T00:00:00.000Z") },
|
||||
submitter: { id: "u-1", name: "李四" },
|
||||
external_code: "ERP-001",
|
||||
reason: "不要进入提示的大段原因",
|
||||
});
|
||||
|
||||
expect(snapshot).toEqual(
|
||||
expect.objectContaining({
|
||||
requestNo: "PR-001",
|
||||
totalAmount: "8888.00",
|
||||
assetCandidateCount: 1,
|
||||
}),
|
||||
);
|
||||
expect(snapshot).not.toHaveProperty("submitter");
|
||||
expect(JSON.stringify(snapshot)).not.toContain("ERP-001");
|
||||
expect(JSON.stringify(snapshot)).not.toContain("不要进入提示");
|
||||
});
|
||||
|
||||
it("keeps asset whitelist fields only", () => {
|
||||
const snapshot = buildAssetSnapshot({
|
||||
id: "a-1",
|
||||
asset_no: "ZC-001",
|
||||
name: "ThinkPad X1 Carbon ThinkPad X1 Carbon ThinkPad X1 Carbon ThinkPad X1 Carbon ThinkPad X1 Carbon",
|
||||
status: "in_use",
|
||||
category: { code: "LAPTOP", name: "笔记本电脑", document_category: { code: "ASSET_STD" } },
|
||||
legal_entity: { code: "HY", name: "海音达" },
|
||||
cost_center: { code: "IT001", name: "IT中心" },
|
||||
purchase_request: { request_no: "PR-001", title: "办公电脑采购" },
|
||||
location: "上海办公室-A区",
|
||||
activated_at: new Date("2026-03-10T00:00:00.000Z"),
|
||||
retired_at: null,
|
||||
assignee_employee_id: "emp-1",
|
||||
assignee: { id: "emp-1", employee_no: "E001", name: "张三" },
|
||||
external_code: "ERP-ASSET-001",
|
||||
});
|
||||
|
||||
expect(snapshot).toEqual(
|
||||
expect.objectContaining({
|
||||
assetNo: "ZC-001",
|
||||
assignmentState: "assigned",
|
||||
location: "上海办公室-A区",
|
||||
}),
|
||||
);
|
||||
expect(snapshot).not.toHaveProperty("assignee");
|
||||
expect(JSON.stringify(snapshot)).not.toContain("张三");
|
||||
expect(JSON.stringify(snapshot)).not.toContain("ERP-ASSET-001");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,243 @@
|
||||
const suggestions = require("../../../src/services/ai/suggestions");
|
||||
const { buildReimbursementPrompt } = require("../../../src/services/ai/prompts");
|
||||
const { AppError } = require("../../../src/utils/AppError");
|
||||
|
||||
function buildFeatureFlagRecord({
|
||||
overrideMode = "force_on",
|
||||
rolloutType = "global",
|
||||
departmentIds = [],
|
||||
} = {}) {
|
||||
const now = new Date("2026-03-10T00:00:00.000Z");
|
||||
return {
|
||||
id: "flag-ai-assist",
|
||||
flag_key: "ai_assist",
|
||||
override_mode: overrideMode,
|
||||
rollout_type: rolloutType,
|
||||
department_ids: departmentIds,
|
||||
note: "unit-test",
|
||||
version: 1,
|
||||
created_at: now,
|
||||
created_by: null,
|
||||
updated_at: now,
|
||||
updated_by: null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildRequest(permissionCodes, employeeId = "employee-1") {
|
||||
return {
|
||||
id: "req-1",
|
||||
ip: "127.0.0.1",
|
||||
headers: { "user-agent": "vitest" },
|
||||
employee: {
|
||||
id: employeeId,
|
||||
permissionCodes,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildBudgetPool(overrides = {}) {
|
||||
return {
|
||||
id: "budget-1",
|
||||
code: "B-001",
|
||||
name: "年度预算",
|
||||
department_id: "dept-1",
|
||||
legal_entity_id: null,
|
||||
cost_center_id: null,
|
||||
allocated_amount: 1000,
|
||||
used_amount: 920,
|
||||
warning_threshold_percent: 90,
|
||||
status: "active",
|
||||
archived_at: null,
|
||||
period_start: new Date("2026-03-01T00:00:00.000Z"),
|
||||
period_end: new Date("2026-03-31T00:00:00.000Z"),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildPrisma({
|
||||
reimbursement = null,
|
||||
purchaseRequest = null,
|
||||
asset = null,
|
||||
budgetPools = [],
|
||||
flagRecord = buildFeatureFlagRecord(),
|
||||
auditCreate = vi.fn().mockResolvedValue({ id: "audit-1" }),
|
||||
} = {}) {
|
||||
return {
|
||||
featureFlag: {
|
||||
findUnique: vi.fn().mockImplementation(async ({ where }) => {
|
||||
if (where.flag_key === "ai_assist") {
|
||||
return flagRecord;
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
findMany: vi.fn().mockResolvedValue(flagRecord ? [flagRecord] : []),
|
||||
},
|
||||
reimbursementForm: {
|
||||
findUnique: vi.fn().mockResolvedValue(reimbursement),
|
||||
},
|
||||
purchaseRequest: {
|
||||
findUnique: vi.fn().mockResolvedValue(purchaseRequest),
|
||||
},
|
||||
assetCard: {
|
||||
findUnique: vi.fn().mockResolvedValue(asset),
|
||||
},
|
||||
budgetPool: {
|
||||
findMany: vi.fn().mockResolvedValue(budgetPools),
|
||||
},
|
||||
auditLog: {
|
||||
create: auditCreate,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("AI suggestions service", () => {
|
||||
it("builds reimbursement suggestion with prompt hash and provider meta", async () => {
|
||||
const prisma = buildPrisma({
|
||||
reimbursement: {
|
||||
id: "r-1",
|
||||
form_number: "BX-001",
|
||||
submitter_id: "employee-2",
|
||||
owner_id: "employee-1",
|
||||
department_id: "dept-1",
|
||||
reimbursement_date: new Date("2026-03-10T00:00:00.000Z"),
|
||||
total_amount: 120,
|
||||
status: "reviewing",
|
||||
items: [{ id: "item-1", amount: 120, expense_type: { category: "travel" } }],
|
||||
invoice_pool_items: [{ status: "pending" }],
|
||||
workflow_instances: [
|
||||
{
|
||||
workflow_tasks: [
|
||||
{
|
||||
step_name: "财务复核",
|
||||
assignee_role: "finance_mgr",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
budgetPools: [buildBudgetPool()],
|
||||
});
|
||||
|
||||
const result = await suggestions.generateReimbursementSuggestion(
|
||||
prisma,
|
||||
{ aiAssistEnabled: true, aiProvider: "mock", budgetControlMode: "warn" },
|
||||
buildRequest(["expense.view_own", "ai.assist"]),
|
||||
"r-1",
|
||||
);
|
||||
|
||||
const expectedPrompt = buildReimbursementPrompt(result.sourceSnapshot);
|
||||
expect(result.providerMeta.provider).toBe("mock");
|
||||
expect(result.providerMeta.promptHash).toBe(
|
||||
suggestions.__testables.buildPromptHash(expectedPrompt),
|
||||
);
|
||||
expect(result.riskHints.length).toBeLessThanOrEqual(3);
|
||||
expect(result.nextActions.length).toBeLessThanOrEqual(3);
|
||||
expect(result.sourceSnapshot).not.toHaveProperty("owner");
|
||||
expect(prisma.auditLog.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
action: "AI_SUGGESTION_REQUESTED",
|
||||
extra: expect.objectContaining({
|
||||
featureFlag: "ai_assist",
|
||||
promptHash: result.providerMeta.promptHash,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("blocks purchase suggestion when AI gate is disabled by department rollout", async () => {
|
||||
const prisma = buildPrisma({
|
||||
flagRecord: buildFeatureFlagRecord({
|
||||
overrideMode: "force_on",
|
||||
rolloutType: "department_allowlist",
|
||||
departmentIds: ["dept-2"],
|
||||
}),
|
||||
purchaseRequest: {
|
||||
id: "p-1",
|
||||
request_no: "PR-001",
|
||||
applicant_id: "employee-1",
|
||||
submitter_id: "employee-1",
|
||||
department_id: "dept-1",
|
||||
title: "办公电脑采购",
|
||||
currency_code: "CNY",
|
||||
total_amount: 6000,
|
||||
status: "approved",
|
||||
supplier: { code: "SUP-1", name: "供应商" },
|
||||
legal_entity: { code: "HY", name: "海音达" },
|
||||
cost_center: { code: "IT001", name: "IT中心" },
|
||||
budget_pool: { code: "B-001", name: "年度预算" },
|
||||
items: [{ is_asset_candidate: true }],
|
||||
order_archive: null,
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
suggestions.generatePurchaseSuggestion(
|
||||
prisma,
|
||||
{ aiAssistEnabled: true, aiProvider: "mock" },
|
||||
buildRequest(["procurement.view_all", "ai.assist"]),
|
||||
"p-1",
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
statusCode: 409,
|
||||
details: expect.objectContaining({
|
||||
ai: "disabled",
|
||||
featureFlagReason: "department_not_allowed",
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects asset own-view access when actor is not assignee", async () => {
|
||||
const prisma = buildPrisma({
|
||||
asset: {
|
||||
id: "a-1",
|
||||
assignee_employee_id: "employee-1",
|
||||
asset_no: "ZC-001",
|
||||
name: "Laptop",
|
||||
status: "in_use",
|
||||
category: { code: "LAPTOP", name: "笔记本电脑", document_category: { code: "ASSET_STD" } },
|
||||
legal_entity: { code: "HY", name: "海音达" },
|
||||
cost_center: { code: "IT001", name: "IT中心" },
|
||||
purchase_request: null,
|
||||
location: "办公室",
|
||||
activated_at: new Date("2026-03-10T00:00:00.000Z"),
|
||||
retired_at: null,
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
suggestions.generateAssetSuggestion(
|
||||
prisma,
|
||||
{ aiAssistEnabled: true, aiProvider: "mock" },
|
||||
buildRequest(["asset.view_own", "ai.assist"], "employee-2"),
|
||||
"a-1",
|
||||
),
|
||||
).rejects.toBeInstanceOf(AppError);
|
||||
|
||||
await expect(
|
||||
suggestions.generateAssetSuggestion(
|
||||
prisma,
|
||||
{ aiAssistEnabled: true, aiProvider: "mock" },
|
||||
buildRequest(["asset.view_own", "ai.assist"], "employee-2"),
|
||||
"a-1",
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 403, code: "PERM_001" });
|
||||
});
|
||||
|
||||
it("normalizes malformed provider payload to capped structured items", () => {
|
||||
const normalized = suggestions.normalizeProviderSuggestion("reimbursement", {
|
||||
summary: "x".repeat(140),
|
||||
riskHints: [{ level: "critical", code: "", title: "", detail: "" }],
|
||||
nextActions: [{ code: "", label: "", reason: "" }],
|
||||
});
|
||||
|
||||
expect(normalized.summary.length).toBeLessThanOrEqual(120);
|
||||
expect(normalized.riskHints[0]).toEqual(
|
||||
expect.objectContaining({ level: "low", code: "risk_1" }),
|
||||
);
|
||||
expect(normalized.nextActions[0]).toEqual(
|
||||
expect.objectContaining({ code: "action_1", label: "建议动作 1" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
在新工单中引用
屏蔽一个用户