Add smart insights risks, performance, and analyze commands
This commit is contained in:
1 parent
1baeb3722f
commit
c929fd002c
11 files changed
+476
-136
No files matched your search
@@ -7,6 +7,7 @@ import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleAnalyticsCommand(
|
||||
action: string | undefined,
|
||||
maybeName: string | undefined,
|
||||
client: Awaited<ReturnType<typeof createSealClient>>,
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
@@ -26,5 +27,55 @@ export async function handleAnalyticsCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "risks" || action === "risks-by-tag" || action === "tag-risks") {
|
||||
const tagId = maybeName ?? stringOption(args.options.tagId) ?? stringOption(args.options["tag-id"]);
|
||||
if (!tagId) {
|
||||
throw new Error("Usage: seal-use analytics risks <tagId> [--start-date <ISO>] [--end-date <ISO>] [--corp <corpId>]");
|
||||
}
|
||||
await runTool(
|
||||
"seal_insight_risks_by_tag_get",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
tagId,
|
||||
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
|
||||
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"])
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "performance" || action === "perf") {
|
||||
await runTool(
|
||||
"seal_insight_performance_get",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]) ?? numberOption(args.options.startDate) ?? numberOption(args.options["start-date"]),
|
||||
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]) ?? numberOption(args.options.endDate) ?? numberOption(args.options["end-date"])
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "analyze" || action === "reanalyze") {
|
||||
const recordId = maybeName ?? stringOption(args.options.recordId) ?? stringOption(args.options["record-id"]);
|
||||
if (!recordId) {
|
||||
throw new Error("Usage: seal-use analytics analyze <recordId> [--corp <corpId>]");
|
||||
}
|
||||
await runTool(
|
||||
"seal_insight_record_analyze",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
recordId
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`Unknown analytics command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
|
||||
}
|
||||
+20
-1
@@ -752,8 +752,27 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
commands: [
|
||||
{
|
||||
name: "insight",
|
||||
summary: "Query AI audit insights and trends",
|
||||
aliases: ["insight-stats", "stats"],
|
||||
summary: "Query AI audit insights risk-tag statistics and analysis status",
|
||||
usage: ["seal-use analytics insight [--start-date <ISO>] [--end-date <ISO>] [--limit <n>] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "risks",
|
||||
aliases: ["risks-by-tag", "tag-risks"],
|
||||
summary: "Query detailed risks and document citations under a specific risk tag",
|
||||
usage: ["seal-use analytics risks <tagId> [--start-date <ISO>] [--end-date <ISO>] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "performance",
|
||||
aliases: ["perf"],
|
||||
summary: "Query audit performance metrics (accuracy, automation rate) and Sankey flow",
|
||||
usage: ["seal-use analytics performance [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "analyze",
|
||||
aliases: ["reanalyze"],
|
||||
summary: "Trigger on-demand smart insight risk analysis for an approval record",
|
||||
usage: ["seal-use analytics analyze <recordId> [--corp <corpId>]"]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+1
-1
@@ -379,7 +379,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
}
|
||||
|
||||
if (area === "analytics") {
|
||||
await handleAnalyticsCommand(action, client, corp, args);
|
||||
await handleAnalyticsCommand(action, maybeName, client, corp, args);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,9 @@ import {
|
||||
getDepartment,
|
||||
getContactsLastSyncTime,
|
||||
getInsightStats,
|
||||
getInsightRisksByTag,
|
||||
getInsightPerformance,
|
||||
analyzeInsightRecord,
|
||||
listExpenses,
|
||||
listInvoices,
|
||||
listFeishuSimulationApprovalDefinitions,
|
||||
@@ -139,6 +142,108 @@ describe("Seal contact API", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("forwards risks-by-tag parameters and parses response", async () => {
|
||||
let requestedUrl = "";
|
||||
const client = {
|
||||
get: (url: string, options?: { searchParams?: URLSearchParams }) => {
|
||||
requestedUrl = `${url}?${options?.searchParams?.toString() ?? ""}`;
|
||||
return {
|
||||
json: async () => ({
|
||||
data: {
|
||||
tagId: "B.1.6",
|
||||
tagName: "缺少验收/签收证明",
|
||||
tagPath: "凭证/附件问题 > 凭证缺失 > 缺少验收/签收证明",
|
||||
tagDescription: "维修费等未提供验收单",
|
||||
risks: [
|
||||
{
|
||||
riskId: "risk-01",
|
||||
recordId: "rec-01",
|
||||
riskDetails: "冰箱无验收单",
|
||||
riskLevel: "warning",
|
||||
documentType: "费用报销",
|
||||
documentSN: "B26000011",
|
||||
sourceSystem: "custom",
|
||||
confidence: 0.95,
|
||||
reasoning: "缺少签收",
|
||||
createdAt: "2026-09-11T07:31:43.647Z"
|
||||
}
|
||||
],
|
||||
total: 1
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
} as unknown as KyInstance;
|
||||
|
||||
const result = await getInsightRisksByTag(client, {
|
||||
tagId: "B.1.6",
|
||||
startDate: "2026-09-01T00:00:00Z",
|
||||
endDate: "2026-09-30T23:59:59Z"
|
||||
});
|
||||
|
||||
expect(result.tagId).toBe("B.1.6");
|
||||
expect(result.risks.length).toBe(1);
|
||||
expect(result.risks[0]?.documentSN).toBe("B26000011");
|
||||
expect(requestedUrl).toBe(
|
||||
"api/v1/insight/risks-by-tag?tagId=B.1.6&startDate=2026-09-01T00%3A00%3A00Z&endDate=2026-09-30T23%3A59%3A59Z"
|
||||
);
|
||||
});
|
||||
|
||||
test("normalizes performance date parameters to numeric timestamps", async () => {
|
||||
let requestedUrl = "";
|
||||
const client = {
|
||||
get: (url: string, options?: { searchParams?: URLSearchParams }) => {
|
||||
requestedUrl = `${url}?${options?.searchParams?.toString() ?? ""}`;
|
||||
return {
|
||||
json: async () => ({
|
||||
data: {
|
||||
metrics: {
|
||||
approvalCount: { value: 24, trend: 0 },
|
||||
accuracy: { value: 100, trend: 0 },
|
||||
automationRate: { value: 75, trend: 0 },
|
||||
riskCount: { value: 54, trend: 0 },
|
||||
avgDuration: { value: 1041.4, trend: 0 }
|
||||
},
|
||||
sankeyData: {
|
||||
nodes: [{ id: "辅助模式" }],
|
||||
links: [{ source: "辅助模式", target: "添加评论", value: 24 }]
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
} as unknown as KyInstance;
|
||||
|
||||
const result = await getInsightPerformance(client, {
|
||||
startDate: "2026-09-01T00:00:00.000Z",
|
||||
endDate: "2026-09-30T23:59:59.000Z"
|
||||
});
|
||||
|
||||
expect(result.metrics.approvalCount?.value).toBe(24);
|
||||
expect(result.sankeyData.nodes[0]?.id).toBe("辅助模式");
|
||||
const startTs = new Date("2026-09-01T00:00:00.000Z").getTime();
|
||||
const endTs = new Date("2026-09-30T23:59:59.000Z").getTime();
|
||||
expect(requestedUrl).toBe(
|
||||
`api/v1/insight/performance?startDate=${startTs}&endDate=${endTs}`
|
||||
);
|
||||
});
|
||||
|
||||
test("posts to analyze insight record", async () => {
|
||||
let postedUrl = "";
|
||||
const client = {
|
||||
post: async (url: string) => {
|
||||
postedUrl = url;
|
||||
return {
|
||||
json: async () => ({ data: null })
|
||||
};
|
||||
}
|
||||
} as unknown as KyInstance;
|
||||
|
||||
const result = await analyzeInsightRecord(client, "rec-test-123");
|
||||
expect(result).toEqual({ success: true, recordId: "rec-test-123" });
|
||||
expect(postedUrl).toBe("api/v1/insight/analyze/rec-test-123");
|
||||
});
|
||||
|
||||
test("uses the frontend filter parameter names for expenses and invoices", async () => {
|
||||
const requestedUrls: string[] = [];
|
||||
const client = {
|
||||
|
||||
@@ -51,6 +51,10 @@ import {
|
||||
SealContactsLastSyncTimeSchema,
|
||||
InsightStats,
|
||||
InsightStatsSchema,
|
||||
InsightRisksByTag,
|
||||
InsightRisksByTagSchema,
|
||||
InsightPerformance,
|
||||
InsightPerformanceSchema,
|
||||
ExpenseListData,
|
||||
ExpenseListDataSchema,
|
||||
InvoiceListData,
|
||||
@@ -1007,6 +1011,63 @@ export async function getInsightStats(
|
||||
);
|
||||
}
|
||||
|
||||
export async function getInsightRisksByTag(
|
||||
client: KyInstance,
|
||||
params: { tagId: string; startDate?: string; endDate?: string }
|
||||
): Promise<InsightRisksByTag> {
|
||||
const defaultRange = currentMonthDateRange();
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set("tagId", params.tagId);
|
||||
searchParams.set("startDate", params.startDate ?? defaultRange.startDate);
|
||||
searchParams.set("endDate", params.endDate ?? defaultRange.endDate);
|
||||
|
||||
return unwrap(
|
||||
await client.get("api/v1/insight/risks-by-tag", { searchParams }),
|
||||
InsightRisksByTagSchema
|
||||
);
|
||||
}
|
||||
|
||||
export async function getInsightPerformance(
|
||||
client: KyInstance,
|
||||
params: { startDate?: string | number; endDate?: string | number } = {}
|
||||
): Promise<InsightPerformance> {
|
||||
const defaultRange = currentMonthDateRange();
|
||||
const startTs = normalizeToTimestamp(params.startDate ?? defaultRange.startDate);
|
||||
const endTs = normalizeToTimestamp(params.endDate ?? defaultRange.endDate);
|
||||
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set("startDate", String(startTs));
|
||||
searchParams.set("endDate", String(endTs));
|
||||
|
||||
return unwrap(
|
||||
await client.get("api/v1/insight/performance", { searchParams }),
|
||||
InsightPerformanceSchema
|
||||
);
|
||||
}
|
||||
|
||||
export async function analyzeInsightRecord(
|
||||
client: KyInstance,
|
||||
recordId: string
|
||||
): Promise<{ success: boolean; recordId: string }> {
|
||||
await client.post(`api/v1/insight/analyze/${encodeURIComponent(recordId)}`);
|
||||
return { success: true, recordId };
|
||||
}
|
||||
|
||||
function normalizeToTimestamp(value: string | number): number {
|
||||
if (typeof value === "number") {
|
||||
return value < 1e11 ? value * 1000 : value;
|
||||
}
|
||||
const parsed = Number(value);
|
||||
if (!isNaN(parsed) && value.trim() !== "") {
|
||||
return parsed < 1e11 ? parsed * 1000 : parsed;
|
||||
}
|
||||
const date = new Date(value);
|
||||
if (isNaN(date.getTime())) {
|
||||
throw new Error(`Invalid date format: ${value}`);
|
||||
}
|
||||
return date.getTime();
|
||||
}
|
||||
|
||||
function currentMonthDateRange(): { startDate: string; endDate: string } {
|
||||
const now = new Date();
|
||||
const start = new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
|
||||
@@ -92,8 +92,11 @@ describe("sealTools", () => {
|
||||
expect(sealTools.find((item) => item.name === "seal_contacts_last_sync_time_get")).toBeDefined();
|
||||
});
|
||||
|
||||
test("includes the read-only insight stats tool", () => {
|
||||
test("includes the read-only insight stats and analytics tools", () => {
|
||||
expect(sealTools.find((item) => item.name === "seal_insight_stats_get")).toBeDefined();
|
||||
expect(sealTools.find((item) => item.name === "seal_insight_risks_by_tag_get")).toBeDefined();
|
||||
expect(sealTools.find((item) => item.name === "seal_insight_performance_get")).toBeDefined();
|
||||
expect(sealTools.find((item) => item.name === "seal_insight_record_analyze")).toBeDefined();
|
||||
});
|
||||
|
||||
test("includes read-only financial data tools", () => {
|
||||
|
||||
@@ -219,6 +219,42 @@ export const sealTools = [
|
||||
params: { startDate?: string; endDate?: string; limit?: number }
|
||||
) => api.getInsightStats(client, params)
|
||||
},
|
||||
{
|
||||
name: "seal_insight_risks_by_tag_get",
|
||||
description: "按风险标签查询智能洞察风险单据明细及 AI 分析依据",
|
||||
parameters: z.object({
|
||||
tagId: z.string().describe("风险标签 ID(如 B.1.1、B.1.6)"),
|
||||
startDate: z.string().optional().describe("统计开始时间(ISO 8601)"),
|
||||
endDate: z.string().optional().describe("统计结束时间(ISO 8601)")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { tagId: string; startDate?: string; endDate?: string }
|
||||
) => api.getInsightRisksByTag(client, params)
|
||||
},
|
||||
{
|
||||
name: "seal_insight_performance_get",
|
||||
description: "查询智能洞察审核效能指标(自动化率、准确率等)及决策流向桑基图",
|
||||
parameters: z.object({
|
||||
startDate: z.union([z.string(), z.number()]).optional().describe("统计开始时间(ISO 8601 或毫秒时间戳)"),
|
||||
endDate: z.union([z.string(), z.number()]).optional().describe("统计结束时间(ISO 8601 或毫秒时间戳)")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { startDate?: string | number; endDate?: string | number }
|
||||
) => api.getInsightPerformance(client, params)
|
||||
},
|
||||
{
|
||||
name: "seal_insight_record_analyze",
|
||||
description: "对指定的审批单运行记录按需触发智能洞察风险分析",
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("审批单运行记录 ID (recordId)")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { recordId: string }
|
||||
) => api.analyzeInsightRecord(client, params.recordId)
|
||||
},
|
||||
{
|
||||
name: "seal_expenses_list",
|
||||
description: "分页查询费用明细",
|
||||
|
||||
@@ -314,7 +314,15 @@ export const SealContactsLastSyncTimeSchema = z.object({
|
||||
lastSyncTime: z.union([z.string(), z.number(), z.null()])
|
||||
}).passthrough();
|
||||
|
||||
export const InsightTagStatsSchema = z.record(z.string(), z.unknown());
|
||||
export const InsightTagStatsSchema = z.object({
|
||||
tagId: z.string().optional(),
|
||||
tagName: z.string().optional(),
|
||||
tagPath: z.string().optional(),
|
||||
count: z.number().default(0),
|
||||
avgConfidence: z.number().default(0),
|
||||
errorCount: z.number().default(0),
|
||||
warningCount: z.number().default(0)
|
||||
}).passthrough();
|
||||
|
||||
export const InsightStatsSchema = z.object({
|
||||
tagStats: z.array(InsightTagStatsSchema).default([]),
|
||||
@@ -323,6 +331,52 @@ export const InsightStatsSchema = z.object({
|
||||
pendingRisks: z.number().default(0)
|
||||
}).passthrough();
|
||||
|
||||
export const InsightRiskItemSchema = z.object({
|
||||
riskId: z.string().optional(),
|
||||
recordId: z.string().optional(),
|
||||
riskDetails: z.string().default(""),
|
||||
riskLevel: z.string().default("warning"),
|
||||
documentType: z.string().default(""),
|
||||
documentSN: z.string().default(""),
|
||||
sourceSystem: z.string().default(""),
|
||||
sourceDocumentURL: z.string().nullable().optional(),
|
||||
confidence: z.number().default(0),
|
||||
reasoning: z.string().default(""),
|
||||
createdAt: z.union([z.string(), z.number(), z.date()]).optional()
|
||||
}).passthrough();
|
||||
|
||||
export const InsightRisksByTagSchema = z.object({
|
||||
tagId: z.string(),
|
||||
tagName: z.string().default(""),
|
||||
tagPath: z.string().default(""),
|
||||
tagDescription: z.string().default(""),
|
||||
risks: z.array(InsightRiskItemSchema).default([]),
|
||||
total: z.number().default(0)
|
||||
}).passthrough();
|
||||
|
||||
export const InsightPerformanceMetricSchema = z.object({
|
||||
value: z.number().default(0),
|
||||
trend: z.number().default(0)
|
||||
}).passthrough();
|
||||
|
||||
export const InsightPerformanceSchema = z.object({
|
||||
metrics: z.object({
|
||||
approvalCount: InsightPerformanceMetricSchema.optional(),
|
||||
accuracy: InsightPerformanceMetricSchema.optional(),
|
||||
automationRate: InsightPerformanceMetricSchema.optional(),
|
||||
riskCount: InsightPerformanceMetricSchema.optional(),
|
||||
avgDuration: InsightPerformanceMetricSchema.optional()
|
||||
}).passthrough().default({}),
|
||||
sankeyData: z.object({
|
||||
nodes: z.array(z.object({ id: z.string() }).passthrough()).default([]),
|
||||
links: z.array(z.object({
|
||||
source: z.string(),
|
||||
target: z.string(),
|
||||
value: z.number().default(0)
|
||||
}).passthrough()).default([])
|
||||
}).passthrough().default({ nodes: [], links: [] })
|
||||
}).passthrough();
|
||||
|
||||
const DataRecordSchema = z.record(z.string(), z.unknown());
|
||||
|
||||
export const ExpenseListDataSchema = z.object({
|
||||
@@ -593,7 +647,12 @@ export type SealDepartment = z.infer<typeof SealDepartmentSchema>;
|
||||
export type SealDepartmentListData = z.infer<typeof SealDepartmentListDataSchema>;
|
||||
export type SealDepartmentUsersData = z.infer<typeof SealDepartmentUsersDataSchema>;
|
||||
export type SealContactsLastSyncTime = z.infer<typeof SealContactsLastSyncTimeSchema>;
|
||||
export type InsightTagStats = z.infer<typeof InsightTagStatsSchema>;
|
||||
export type InsightStats = z.infer<typeof InsightStatsSchema>;
|
||||
export type InsightRiskItem = z.infer<typeof InsightRiskItemSchema>;
|
||||
export type InsightRisksByTag = z.infer<typeof InsightRisksByTagSchema>;
|
||||
export type InsightPerformanceMetric = z.infer<typeof InsightPerformanceMetricSchema>;
|
||||
export type InsightPerformance = z.infer<typeof InsightPerformanceSchema>;
|
||||
export type ExpenseListData = z.infer<typeof ExpenseListDataSchema>;
|
||||
export type InvoiceListData = z.infer<typeof InvoiceListDataSchema>;
|
||||
export type SimulationApprovalDefinition = z.infer<typeof SimulationApprovalDefinitionSchema>;
|
||||
|
||||
Reference in new issue
Block a user