feat(P19AI1-1,P19AI1-2): 实现AI建议引擎与权限门禁后端
这个提交包含在:
@@ -45,6 +45,13 @@ describe("Permission Constants", () => {
|
||||
});
|
||||
|
||||
|
||||
it("grants ai.assist only to finance manager and admin", () => {
|
||||
expect(hasPermission(resolvePermissionsForRoles(["finance_mgr"]), "ai.assist")).toBe(true);
|
||||
expect(hasPermission(resolvePermissionsForRoles(["finance"]), "ai.assist")).toBe(false);
|
||||
expect(hasPermission(resolvePermissionsForRoles(["manager"]), "ai.assist")).toBe(false);
|
||||
expect(hasPermission(resolvePermissionsForRoles(["admin"]), "ai.assist")).toBe(true);
|
||||
});
|
||||
|
||||
it("grants asset permissions to configured roles", () => {
|
||||
expect(hasPermission(resolvePermissionsForRoles(["employee"]), "asset.view_own")).toBe(true);
|
||||
expect(hasPermission(resolvePermissionsForRoles(["manager"]), "asset.view_all")).toBe(true);
|
||||
|
||||
@@ -174,17 +174,28 @@ describe("evaluateFeatureFlag", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("leave holiday calendar flag", () => {
|
||||
it("uses the dedicated env gate", async () => {
|
||||
describe("feature flag env gates", () => {
|
||||
it("uses the dedicated leave holiday calendar env gate", async () => {
|
||||
const result = await evaluateFeatureFlag({
|
||||
prisma: buildPrisma(),
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: false },
|
||||
config: { aiAssistEnabled: true, erpSyncEnabled: true, invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: false },
|
||||
flagKey: FEATURE_FLAG_KEYS.leaveHolidayCalendar,
|
||||
});
|
||||
|
||||
expect(result.enabled).toBe(false);
|
||||
expect(result.reason).toBe("env_hard_off");
|
||||
});
|
||||
|
||||
it("uses the dedicated ai assist env gate", async () => {
|
||||
const result = await evaluateFeatureFlag({
|
||||
prisma: buildPrisma(),
|
||||
config: { aiAssistEnabled: false, erpSyncEnabled: true, invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: true },
|
||||
flagKey: FEATURE_FLAG_KEYS.aiAssist,
|
||||
});
|
||||
|
||||
expect(result.enabled).toBe(false);
|
||||
expect(result.reason).toBe("env_hard_off");
|
||||
});
|
||||
});
|
||||
|
||||
describe("listFeatureFlags", () => {
|
||||
@@ -201,14 +212,15 @@ describe("listFeatureFlags", () => {
|
||||
invoiceVerificationEnabled: true,
|
||||
});
|
||||
|
||||
expect(items).toHaveLength(3);
|
||||
expect(items).toHaveLength(4);
|
||||
expect(items.map((item) => item.flagKey).sort()).toEqual([
|
||||
FEATURE_FLAG_KEYS.aiAssist,
|
||||
FEATURE_FLAG_KEYS.erpSync,
|
||||
FEATURE_FLAG_KEYS.invoiceVerification,
|
||||
FEATURE_FLAG_KEYS.leaveHolidayCalendar,
|
||||
]);
|
||||
|
||||
const missingItem = items.find((item) => item.flagKey === FEATURE_FLAG_KEYS.leaveHolidayCalendar);
|
||||
const missingItem = items.find((item) => item.flagKey === FEATURE_FLAG_KEYS.aiAssist);
|
||||
expect(missingItem.id).toBeNull();
|
||||
expect(missingItem.effectiveEnabled).toBe(false);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
const Fastify = require("fastify");
|
||||
|
||||
const { AppError } = require("../../../src/utils/AppError");
|
||||
const aiRoutes = require("../../../src/routes/ai");
|
||||
|
||||
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 buildPrisma({
|
||||
reimbursement = null,
|
||||
purchaseRequest = null,
|
||||
asset = null,
|
||||
flagRecord = buildFeatureFlagRecord(),
|
||||
} = {}) {
|
||||
return {
|
||||
featureFlag: {
|
||||
findUnique: vi.fn().mockImplementation(async ({ where }) => {
|
||||
if (where.flag_key === "ai_assist") {
|
||||
return flagRecord;
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
},
|
||||
reimbursementForm: {
|
||||
findUnique: vi.fn().mockResolvedValue(reimbursement),
|
||||
},
|
||||
purchaseRequest: {
|
||||
findUnique: vi.fn().mockResolvedValue(purchaseRequest),
|
||||
},
|
||||
assetCard: {
|
||||
findUnique: vi.fn().mockResolvedValue(asset),
|
||||
},
|
||||
budgetPool: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn().mockResolvedValue({ id: "audit-1" }),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function buildTestApp({ employee, prisma, config }) {
|
||||
const app = Fastify();
|
||||
|
||||
app.decorate("prisma", prisma);
|
||||
app.decorate("config", {
|
||||
aiAssistEnabled: true,
|
||||
aiProvider: "mock",
|
||||
budgetControlMode: "warn",
|
||||
...config,
|
||||
});
|
||||
app.decorate("authenticate", async (request) => {
|
||||
if (!request.headers.authorization) {
|
||||
throw new AppError({
|
||||
code: "AUTH_001",
|
||||
message: "未登录",
|
||||
statusCode: 401,
|
||||
});
|
||||
}
|
||||
request.employee = employee;
|
||||
});
|
||||
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
if (error instanceof AppError) {
|
||||
return reply.status(error.statusCode).send({
|
||||
requestId: request.id,
|
||||
error: {
|
||||
code: error.code,
|
||||
message: error.message,
|
||||
details: error.details ?? {},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return reply.status(500).send({
|
||||
requestId: request.id,
|
||||
error: {
|
||||
code: "SYS_001",
|
||||
message: "服务器内部错误",
|
||||
details: {},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
await app.register(aiRoutes, { prefix: "/api" });
|
||||
return app;
|
||||
}
|
||||
|
||||
describe("AI routes", () => {
|
||||
it("returns AI status for authenticated user", async () => {
|
||||
const app = await buildTestApp({
|
||||
employee: { id: "employee-1", permissionCodes: [] },
|
||||
prisma: buildPrisma(),
|
||||
config: { aiAssistEnabled: false },
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/ai/status",
|
||||
headers: { authorization: "Bearer test-token" },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().data).toEqual(
|
||||
expect.objectContaining({
|
||||
enabled: false,
|
||||
permissions: { canAccess: false },
|
||||
featureFlag: expect.objectContaining({ effectiveReason: "env_hard_off" }),
|
||||
}),
|
||||
);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("returns 401 when auth header is missing", async () => {
|
||||
const app = await buildTestApp({
|
||||
employee: { id: "employee-1", permissionCodes: ["ai.assist"] },
|
||||
prisma: buildPrisma(),
|
||||
});
|
||||
|
||||
const response = await app.inject({ method: "GET", url: "/api/ai/status" });
|
||||
|
||||
expect(response.statusCode).toBe(401);
|
||||
expect(response.json().error.code).toBe("AUTH_001");
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("rejects reimbursement suggestion when actor lacks ai.assist", async () => {
|
||||
const app = await buildTestApp({
|
||||
employee: { id: "employee-1", permissionCodes: ["expense.view_own"] },
|
||||
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: [],
|
||||
invoice_pool_items: [],
|
||||
workflow_instances: [],
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/ai/suggestions/reimbursements/11111111-1111-4111-8111-111111111111",
|
||||
headers: { authorization: "Bearer test-token" },
|
||||
payload: {},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
expect(response.json().error.code).toBe("PERM_001");
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("returns 409 when purchase suggestion is disabled by department gate", async () => {
|
||||
const app = await buildTestApp({
|
||||
employee: { id: "employee-1", permissionCodes: ["procurement.view_all", "ai.assist"] },
|
||||
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,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/ai/suggestions/purchase-requests/22222222-2222-4222-8222-222222222222",
|
||||
headers: { authorization: "Bearer test-token" },
|
||||
payload: {},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(409);
|
||||
expect(response.json().error.details).toEqual(
|
||||
expect.objectContaining({ ai: "disabled", featureFlagReason: "department_not_allowed" }),
|
||||
);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("enforces reimbursement own-view permission on suggestion route", 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: [],
|
||||
invoice_pool_items: [],
|
||||
workflow_instances: [],
|
||||
},
|
||||
});
|
||||
|
||||
const ownerApp = await buildTestApp({
|
||||
employee: { id: "employee-1", permissionCodes: ["expense.view_own", "ai.assist"] },
|
||||
prisma,
|
||||
});
|
||||
const ownerResponse = await ownerApp.inject({
|
||||
method: "POST",
|
||||
url: "/api/ai/suggestions/reimbursements/11111111-1111-4111-8111-111111111111",
|
||||
headers: { authorization: "Bearer test-token" },
|
||||
payload: {},
|
||||
});
|
||||
|
||||
expect(ownerResponse.statusCode).toBe(200);
|
||||
expect(ownerResponse.json().data.targetType).toBe("reimbursement");
|
||||
await ownerApp.close();
|
||||
|
||||
const outsiderApp = await buildTestApp({
|
||||
employee: { id: "employee-9", permissionCodes: ["expense.view_own", "ai.assist"] },
|
||||
prisma,
|
||||
});
|
||||
const outsiderResponse = await outsiderApp.inject({
|
||||
method: "POST",
|
||||
url: "/api/ai/suggestions/reimbursements/11111111-1111-4111-8111-111111111111",
|
||||
headers: { authorization: "Bearer test-token" },
|
||||
payload: {},
|
||||
});
|
||||
|
||||
expect(outsiderResponse.statusCode).toBe(403);
|
||||
expect(outsiderResponse.json().error.code).toBe("PERM_001");
|
||||
await outsiderApp.close();
|
||||
});
|
||||
|
||||
it("enforces asset assignee own-view permission on suggestion route", async () => {
|
||||
const prisma = buildPrisma({
|
||||
asset: {
|
||||
id: "a-1",
|
||||
asset_no: "ZC-001",
|
||||
name: "Laptop",
|
||||
status: "in_use",
|
||||
assignee_employee_id: "employee-1",
|
||||
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,
|
||||
},
|
||||
});
|
||||
|
||||
const ownerApp = await buildTestApp({
|
||||
employee: { id: "employee-1", permissionCodes: ["asset.view_own", "ai.assist"] },
|
||||
prisma,
|
||||
});
|
||||
const ownerResponse = await ownerApp.inject({
|
||||
method: "POST",
|
||||
url: "/api/ai/suggestions/assets/33333333-3333-4333-8333-333333333333",
|
||||
headers: { authorization: "Bearer test-token" },
|
||||
payload: {},
|
||||
});
|
||||
|
||||
expect(ownerResponse.statusCode).toBe(200);
|
||||
expect(ownerResponse.json().data.targetType).toBe("asset_card");
|
||||
await ownerApp.close();
|
||||
|
||||
const outsiderApp = await buildTestApp({
|
||||
employee: { id: "employee-9", permissionCodes: ["asset.view_own", "ai.assist"] },
|
||||
prisma,
|
||||
});
|
||||
const outsiderResponse = await outsiderApp.inject({
|
||||
method: "POST",
|
||||
url: "/api/ai/suggestions/assets/33333333-3333-4333-8333-333333333333",
|
||||
headers: { authorization: "Bearer test-token" },
|
||||
payload: {},
|
||||
});
|
||||
|
||||
expect(outsiderResponse.statusCode).toBe(403);
|
||||
expect(outsiderResponse.json().error.code).toBe("PERM_001");
|
||||
await outsiderApp.close();
|
||||
});
|
||||
});
|
||||
@@ -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" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
在新工单中引用
屏蔽一个用户