chore: 以本地为准,上传全部并替换 GitHub

This commit is contained in:
卡若
2026-02-03 11:36:53 +08:00
parent 1219166526
commit b404bf546e
131 changed files with 37618 additions and 3930 deletions

View File

@@ -0,0 +1,617 @@
"use client"
import { useState, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Switch } from "@/components/ui/switch"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import {
MessageSquare,
Plus,
Settings,
CheckCircle2,
XCircle,
RefreshCw,
Copy,
ExternalLink,
Webhook,
Bot,
Loader2,
Send,
Key,
Globe,
Smartphone,
} from "lucide-react"
// 渠道接口
interface Channel {
id: string
name: string
type: 'feishu' | 'wecom' | 'wechat' | 'api' | 'webhook'
status: 'connected' | 'disconnected' | 'pending'
config: {
appId?: string
appSecret?: string
webhookUrl?: string
token?: string
encryptKey?: string
}
stats: {
totalMessages: number
todayMessages: number
lastMessage?: string
}
createdAt: string
enabled: boolean
}
// 渠道类型配置 - 包含详细配置步骤
const CHANNEL_TYPES = {
feishu: {
name: '飞书',
icon: '🪶',
color: 'bg-blue-100 text-blue-700',
description: '对接飞书机器人,支持私聊和群聊',
configFields: ['appId', 'appSecret', 'encryptKey', 'token'],
steps: [
'1. 登录飞书开放平台 open.feishu.cn',
'2. 创建企业自建应用 → 机器人',
'3. 获取 App ID 和 App Secret',
'4. 配置事件订阅 URL: {apiBaseUrl}/feishu/events',
'5. 添加权限: im:message, im:message.group_at_msg',
'6. 将机器人添加到目标群聊',
'7. @机器人 即可开始对话',
],
},
wecom: {
name: '企业微信',
icon: '💼',
color: 'bg-green-100 text-green-700',
description: '对接企业微信应用或机器人',
configFields: ['corpId', 'agentId', 'secret', 'token', 'encodingAESKey'],
steps: [
'1. 登录企业微信管理后台 work.weixin.qq.com',
'2. 应用管理 → 自建应用 → 创建应用',
'3. 获取 CorpID、AgentId、Secret',
'4. 设置接收消息 URL: {apiBaseUrl}/wecom/callback',
'5. 配置 Token 和 EncodingAESKey',
'6. 开启客户联系、消息推送等权限',
'7. 发消息给应用即可触发对话',
],
},
wechat: {
name: '微信',
icon: '💬',
color: 'bg-emerald-100 text-emerald-700',
description: '通过存客宝对接微信私域',
configFields: ['ckbApiKey', 'ckbSecret'],
steps: [
'1. 登录存客宝后台 admin.cunkebao.com',
'2. 系统设置 → API配置',
'3. 获取 API Key 和 Secret',
'4. 配置消息回调 URL: {apiBaseUrl}/ckb/webhook',
'5. 在卡若AI配置存客宝凭证',
'6. 微信好友发消息即可触发AI回复',
],
},
api: {
name: 'API接口',
icon: '🔌',
color: 'bg-purple-100 text-purple-700',
description: '标准REST API供第三方系统调用',
configFields: ['apiKey'],
steps: [
'1. 在本页面生成 API Key',
'2. 调用方式: POST {apiBaseUrl}/chat',
'3. Header: Authorization: Bearer {API_KEY}',
'4. Body: { "message": "你的问题" }',
'5. 响应: { "success": true, "response": {...} }',
],
},
webhook: {
name: 'Webhook',
icon: '🔗',
color: 'bg-orange-100 text-orange-700',
description: '通用Webhook回调接口',
configFields: ['webhookUrl', 'secret'],
steps: [
'1. 配置接收 Webhook 的目标 URL',
'2. 设置签名密钥 (可选)',
'3. 神射手会在以下事件时推送:',
' - 新用户画像生成',
' - 流量包创建完成',
' - 报告生成完成',
'4. 推送格式: { "event": "...", "data": {...} }',
],
},
}
// 预定义渠道
const DEFAULT_CHANNELS: Channel[] = [
{
id: 'ch_feishu_1',
name: '卡若AI飞书机器人',
type: 'feishu',
status: 'connected',
config: {
appId: 'cli_a6xxx',
appSecret: '********',
token: 'karuo_token',
},
stats: {
totalMessages: 12580,
todayMessages: 156,
lastMessage: '5分钟前',
},
createdAt: '2024-01-15',
enabled: true,
},
{
id: 'ch_wecom_1',
name: '企业微信-神射手助手',
type: 'wecom',
status: 'connected',
config: {
appId: 'ww_xxx',
},
stats: {
totalMessages: 8920,
todayMessages: 89,
lastMessage: '12分钟前',
},
createdAt: '2024-02-01',
enabled: true,
},
{
id: 'ch_wechat_1',
name: '存客宝微信通道',
type: 'wechat',
status: 'connected',
config: {},
stats: {
totalMessages: 45600,
todayMessages: 320,
lastMessage: '1分钟前',
},
createdAt: '2024-01-01',
enabled: true,
},
{
id: 'ch_api_1',
name: '神射手API',
type: 'api',
status: 'connected',
config: {
apiKey: 'sk-archer-xxx',
},
stats: {
totalMessages: 156000,
todayMessages: 2340,
lastMessage: '刚刚',
},
createdAt: '2024-01-01',
enabled: true,
},
]
export default function ChannelsPage() {
const [channels, setChannels] = useState<Channel[]>(DEFAULT_CHANNELS)
const [loading, setLoading] = useState(false)
const [showAddDialog, setShowAddDialog] = useState(false)
const [showConfigDialog, setShowConfigDialog] = useState(false)
const [selectedChannel, setSelectedChannel] = useState<Channel | null>(null)
const [newChannelType, setNewChannelType] = useState<keyof typeof CHANNEL_TYPES>('feishu')
const [testLoading, setTestLoading] = useState<string | null>(null)
// API端点基础URL - 动态获取当前域名
const [apiBaseUrl, setApiBaseUrl] = useState('')
useEffect(() => {
// 获取当前部署的域名
const host = typeof window !== 'undefined' ? window.location.origin : ''
setApiBaseUrl(`${host}/api/shensheshou`)
}, [])
const formatNumber = (num: number): string => {
if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`
if (num >= 1000) return `${(num / 1000).toFixed(1)}K`
return num.toLocaleString()
}
// 测试连接
const testConnection = async (channelId: string) => {
setTestLoading(channelId)
await new Promise(r => setTimeout(r, 2000))
setTestLoading(null)
}
// 切换启用状态
const toggleChannel = (channelId: string) => {
setChannels(channels.map(ch =>
ch.id === channelId ? { ...ch, enabled: !ch.enabled } : ch
))
}
// 复制到剪贴板
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text)
}
const getStatusBadge = (status: string) => {
switch (status) {
case 'connected':
return <Badge className="bg-green-100 text-green-700"><CheckCircle2 className="h-3 w-3 mr-1" /></Badge>
case 'disconnected':
return <Badge className="bg-red-100 text-red-700"><XCircle className="h-3 w-3 mr-1" /></Badge>
default:
return <Badge className="bg-yellow-100 text-yellow-700"><RefreshCw className="h-3 w-3 mr-1" /></Badge>
}
}
return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/20">
<div className="p-6 space-y-6">
{/* 顶部标题 */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900"></h1>
<p className="text-sm text-gray-500 mt-1">AI助手可通过多渠道访问</p>
</div>
<Button onClick={() => setShowAddDialog(true)}>
<Plus className="h-4 w-4 mr-2" />
</Button>
</div>
{/* 统计卡片 */}
<div className="grid grid-cols-4 gap-4">
<Card className="border-0 shadow-sm bg-white/80">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold">{channels.length}</p>
</div>
<Webhook className="h-8 w-8 text-blue-500 opacity-50" />
</div>
</CardContent>
</Card>
<Card className="border-0 shadow-sm bg-white/80">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold text-green-600">{channels.filter(c => c.status === 'connected').length}</p>
</div>
<CheckCircle2 className="h-8 w-8 text-green-500 opacity-50" />
</div>
</CardContent>
</Card>
<Card className="border-0 shadow-sm bg-white/80">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold">{formatNumber(channels.reduce((sum, c) => sum + c.stats.todayMessages, 0))}</p>
</div>
<MessageSquare className="h-8 w-8 text-purple-500 opacity-50" />
</div>
</CardContent>
</Card>
<Card className="border-0 shadow-sm bg-white/80">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold">{formatNumber(channels.reduce((sum, c) => sum + c.stats.totalMessages, 0))}</p>
</div>
<Send className="h-8 w-8 text-orange-500 opacity-50" />
</div>
</CardContent>
</Card>
</div>
{/* API接入说明 */}
<Card className="border-0 shadow-sm bg-gradient-to-r from-blue-50 to-purple-50">
<CardContent className="p-4">
<div className="flex items-start justify-between">
<div>
<h3 className="font-semibold text-gray-900 mb-1">🔗 API接入端点</h3>
<p className="text-sm text-gray-600 mb-2">Skill通信</p>
<div className="space-y-2">
<div className="flex items-center gap-2">
<code className="bg-white px-3 py-1.5 rounded text-sm font-mono text-purple-600">
POST {apiBaseUrl}/chat
</code>
<Button variant="ghost" size="sm" onClick={() => copyToClipboard(`${apiBaseUrl}/chat`)}>
<Copy className="h-3 w-3" />
</Button>
<span className="text-xs text-gray-500"></span>
</div>
<div className="flex items-center gap-2">
<code className="bg-white px-3 py-1.5 rounded text-sm font-mono text-purple-600">
POST {apiBaseUrl}/query
</code>
<Button variant="ghost" size="sm" onClick={() => copyToClipboard(`${apiBaseUrl}/query`)}>
<Copy className="h-3 w-3" />
</Button>
<span className="text-xs text-gray-500"></span>
</div>
</div>
</div>
<Button variant="outline" size="sm">
<ExternalLink className="h-4 w-4 mr-1" />
API文档
</Button>
</div>
</CardContent>
</Card>
{/* 渠道列表 */}
<div className="space-y-3">
{channels.map(channel => {
const typeConfig = CHANNEL_TYPES[channel.type]
return (
<Card key={channel.id} className="border-0 shadow-sm bg-white/80 hover:shadow-md transition-all">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<div className={`w-12 h-12 rounded-xl ${typeConfig.color.split(' ')[0]} flex items-center justify-center text-2xl`}>
{typeConfig.icon}
</div>
<div>
<div className="flex items-center gap-2">
<h3 className="font-semibold text-gray-900">{channel.name}</h3>
<Badge className={typeConfig.color}>{typeConfig.name}</Badge>
{getStatusBadge(channel.status)}
</div>
<p className="text-sm text-gray-500 mt-0.5">{typeConfig.description}</p>
<div className="flex items-center gap-4 mt-1 text-xs text-gray-500">
<span>: {formatNumber(channel.stats.todayMessages)} </span>
<span>: {formatNumber(channel.stats.totalMessages)} </span>
{channel.stats.lastMessage && (
<span>: {channel.stats.lastMessage}</span>
)}
</div>
</div>
</div>
<div className="flex items-center gap-3">
<Switch
checked={channel.enabled}
onCheckedChange={() => toggleChannel(channel.id)}
/>
<Button
variant="outline"
size="sm"
onClick={() => testConnection(channel.id)}
disabled={testLoading === channel.id}
>
{testLoading === channel.id ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<RefreshCw className="h-4 w-4" />
)}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => {
setSelectedChannel(channel)
setShowConfigDialog(true)
}}
>
<Settings className="h-4 w-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
)
})}
</div>
{/* 添加渠道弹窗 */}
<Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription></DialogDescription>
</DialogHeader>
<div className="grid grid-cols-2 gap-3 py-4">
{Object.entries(CHANNEL_TYPES).map(([key, config]) => (
<div
key={key}
onClick={() => setNewChannelType(key as keyof typeof CHANNEL_TYPES)}
className={`p-4 rounded-xl border-2 cursor-pointer transition-all ${
newChannelType === key ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300'
}`}
>
<div className="text-2xl mb-2">{config.icon}</div>
<h4 className="font-semibold text-gray-900">{config.name}</h4>
<p className="text-xs text-gray-500 mt-1 line-clamp-2">{config.description}</p>
</div>
))}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowAddDialog(false)}></Button>
<Button onClick={() => {
// 跳转到配置页面
setShowAddDialog(false)
setShowConfigDialog(true)
setSelectedChannel({
id: `ch_${newChannelType}_new`,
name: '',
type: newChannelType,
status: 'pending',
config: {},
stats: { totalMessages: 0, todayMessages: 0 },
createdAt: new Date().toISOString().split('T')[0],
enabled: false,
})
}}>
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 配置弹窗 */}
<Dialog open={showConfigDialog} onOpenChange={setShowConfigDialog}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>
{selectedChannel?.id.includes('new') ? '配置新渠道' : '编辑渠道配置'}
</DialogTitle>
<DialogDescription>
{selectedChannel && CHANNEL_TYPES[selectedChannel.type]?.description}
</DialogDescription>
</DialogHeader>
{selectedChannel && (
<div className="space-y-4 py-4">
{/* 配置步骤指南 */}
<div className="p-3 rounded-lg bg-blue-50 border border-blue-100">
<h4 className="font-medium text-blue-900 mb-2 flex items-center gap-2">
📋 {CHANNEL_TYPES[selectedChannel.type].name}
</h4>
<ol className="text-xs text-blue-800 space-y-1">
{(CHANNEL_TYPES[selectedChannel.type] as any).steps?.map((step: string, i: number) => (
<li key={i} className="flex items-start gap-1">
<span>{step.replace('{apiBaseUrl}', apiBaseUrl || 'https://your-domain.com/api/shensheshou')}</span>
</li>
))}
</ol>
</div>
<div className="space-y-2">
<Label></Label>
<Input
placeholder={`例如:${CHANNEL_TYPES[selectedChannel.type].name}机器人`}
defaultValue={selectedChannel.name}
/>
</div>
{selectedChannel.type === 'feishu' && (
<>
<div className="space-y-2">
<Label>App ID</Label>
<Input placeholder="cli_xxx" defaultValue={selectedChannel.config.appId} />
</div>
<div className="space-y-2">
<Label>App Secret</Label>
<Input type="password" placeholder="输入App Secret" />
</div>
<div className="space-y-2">
<Label>Verification Token</Label>
<Input placeholder="用于验证请求来源" defaultValue={selectedChannel.config.token} />
</div>
<div className="p-3 rounded-lg bg-blue-50 text-sm">
<p className="font-medium text-blue-800 mb-1">📋 </p>
<ol className="text-blue-700 text-xs space-y-1 list-decimal list-inside">
<li></li>
<li></li>
<li></li>
<li></li>
</ol>
</div>
</>
)}
{selectedChannel.type === 'wecom' && (
<>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>ID (CorpId)</Label>
<Input placeholder="ww_xxx" />
</div>
<div className="space-y-2">
<Label>ID (AgentId)</Label>
<Input placeholder="1000001" />
</div>
</div>
<div className="space-y-2">
<Label>Secret</Label>
<Input type="password" placeholder="输入应用Secret" />
</div>
</>
)}
{selectedChannel.type === 'wechat' && (
<>
<div className="space-y-2">
<Label>API Key</Label>
<Input placeholder="从存客宝获取" />
</div>
<div className="p-3 rounded-lg bg-green-50 text-sm">
<p className="font-medium text-green-800 mb-1">💡 </p>
<p className="text-green-700 text-xs">
SDK接入API密钥
</p>
</div>
</>
)}
{selectedChannel.type === 'api' && (
<>
<div className="space-y-2">
<Label>API Key</Label>
<div className="flex gap-2">
<Input value="sk-archer-xxx-xxx-xxx" readOnly className="font-mono" />
<Button variant="outline" size="icon">
<Copy className="h-4 w-4" />
</Button>
</div>
</div>
<div className="space-y-2">
<Label></Label>
<pre className="p-3 rounded-lg bg-gray-900 text-green-400 text-xs overflow-x-auto">
{`curl -X POST ${apiBaseUrl}/chat \\
-H "Authorization: Bearer sk-archer-xxx" \\
-H "Content-Type: application/json" \\
-d '{"message": "查询用户 13800138000"}'`}
</pre>
</div>
</>
)}
{selectedChannel.type === 'webhook' && (
<>
<div className="space-y-2">
<Label>Webhook回调URL</Label>
<Input placeholder="https://your-server.com/webhook" />
</div>
<div className="space-y-2">
<Label></Label>
<Input placeholder="用于验证回调请求" />
</div>
</>
)}
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setShowConfigDialog(false)}></Button>
<Button onClick={() => {
setShowConfigDialog(false)
// 保存配置逻辑
}}>
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</div>
)
}

View File

@@ -75,73 +75,56 @@ export default function AIAgentChatPage() {
setInputValue("")
setIsLoading(true)
// 模拟AI响应
setTimeout(() => {
let response: any = {
try {
// 调用真实的AI Chat API
const response = await fetch("/api/ai-chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: userMessage.content })
})
const data = await response.json()
let aiResponse: any = {
id: (Date.now() + 1).toString(),
role: "assistant",
timestamp: new Date(),
}
// 根据输入内容生成不同类型的响应
if (inputValue.includes("高价值") || inputValue.includes("消费") || inputValue.includes("查询")) {
response.content = "我已理解您的需求。正在为您查询符合条件的用户..."
response.taskType = "NLQ"
response.result = {
type: "table",
title: "高价值用户查询结果",
sql: "SELECT * FROM users WHERE total_spending > 10000 AND last_active_date >= DATE_SUB(NOW(), INTERVAL 30 DAY)",
data: [
{ id: "U001", name: "张三", phone: "138****1234", spending: "¥15,680", lastActive: "2天前" },
{ id: "U002", name: "李四", phone: "139****5678", spending: "¥12,340", lastActive: "1天前" },
{ id: "U003", name: "王五", phone: "137****9012", spending: "¥11,890", lastActive: "3天前" },
],
total: 823,
}
} else if (inputValue.includes("打标") || inputValue.includes("标签")) {
response.content = "我将为符合条件的用户打上「流失风险」标签。这是一个AI打标任务需要您确认后执行。"
response.taskType = "TAG"
response.result = {
type: "confirmation",
title: "AI打标任务确认",
description: "为最近7天未登录的用户打上「流失风险」标签",
affectedCount: 12456,
confidence: 0.87,
needReview: true,
}
} else if (inputValue.includes("清洗") || inputValue.includes("异常")) {
response.content = "我已扫描用户表,发现以下数据质量问题:"
response.taskType = "CLEAN"
response.result = {
type: "cleaning",
title: "数据清洗建议",
issues: [
{ field: "phone", issue: "格式不规范", count: 234, example: "1381234567 → 138****4567" },
{ field: "email", issue: "缺失值", count: 1256, suggestion: "填充默认值或标记" },
{ field: "birth_date", issue: "超出范围", count: 45, example: "2099-01-01" },
],
needReview: true,
}
} else if (inputValue.includes("报告") || inputValue.includes("分析")) {
response.content = "正在为您生成用户增长分析报告..."
response.taskType = "REPORT"
response.result = {
type: "report",
title: "用户增长分析报告2026年1月",
summary: "本月新增用户23,456人同比增长15.2%活跃用户856,234人DAU/MAU比值0.32。",
highlights: [
"新用户转化率提升至18.5%环比增长3.2%",
"高价值用户占比8.7%贡献65%的交易额",
"用户流失率下降至2.1%,创历史新低",
],
if (data.success && data.response) {
aiResponse.content = data.response.content
// 如果有数据结果,添加表格展示
if (data.response.data && data.response.data.length > 0) {
aiResponse.taskType = "NLQ"
aiResponse.result = {
type: "table",
title: "查询结果",
data: data.response.data.slice(0, 5).map((item: any, idx: number) => ({
id: idx + 1,
name: item.name || item. || "-",
phone: item.phone_masked || item.phone || "-",
level: item.user_level || item.traffic_pool?.pool_name || "-",
score: item.user_evaluation_score || item.rfm_composite_score || "-",
})),
total: data.response.data.length,
}
}
} else {
response.content = "我理解您的需求。请问您想要:\n1. 查询用户数据\n2. AI打标签\n3. 数据清洗\n4. 生成报告\n\n请选择或详细描述您的需求。"
aiResponse.content = `⚠️ ${data.error || "查询失败,请重试"}`
}
setMessages((prev) => [...prev, response])
setMessages((prev) => [...prev, aiResponse])
} catch (error: any) {
setMessages((prev) => [...prev, {
id: (Date.now() + 1).toString(),
role: "assistant",
content: `⚠️ 网络错误: ${error.message}`,
timestamp: new Date(),
}])
} finally {
setIsLoading(false)
}, 1500)
}
}
const handleQuickCommand = (command: string) => {

File diff suppressed because it is too large Load Diff

279
app/ai-agent/page.tsx Normal file
View File

@@ -0,0 +1,279 @@
"use client"
import { useState, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import Link from "next/link"
import {
Bot,
MessageSquare,
Webhook,
Sparkles,
Zap,
FileText,
ArrowRight,
CheckCircle2,
Activity,
Users,
Send,
Settings,
ExternalLink,
Copy,
} from "lucide-react"
interface ChannelStats {
name: string
icon: string
status: 'connected' | 'disconnected'
todayMessages: number
}
export default function AIAgentPage() {
const [aiStatus, setAiStatus] = useState<'online' | 'offline'>('online')
const [stats, setStats] = useState({
totalQueries: 156000,
todayQueries: 2340,
avgLatency: 380,
accuracy: 97.5,
})
const channels: ChannelStats[] = [
{ name: '飞书', icon: '🪶', status: 'connected', todayMessages: 156 },
{ name: '企业微信', icon: '💼', status: 'connected', todayMessages: 89 },
{ name: '微信(存客宝)', icon: '💬', status: 'connected', todayMessages: 320 },
{ name: 'API接口', icon: '🔌', status: 'connected', todayMessages: 2340 },
]
const API_BASE_URL = 'https://your-domain.com/api/shensheshou'
const modules = [
{
title: '智能对话',
description: '与AI助手对话查询用户信息和执行数据分析',
icon: MessageSquare,
href: '/ai-agent/chat',
color: 'from-blue-500 to-cyan-500',
},
{
title: '渠道配置',
description: '配置飞书、企微、微信等渠道接入',
icon: Webhook,
href: '/ai-agent/channels',
color: 'from-green-500 to-emerald-500',
},
{
title: 'AI打标',
description: '使用AI自动为用户打标签',
icon: Sparkles,
href: '/ai-agent/smart-tag',
color: 'from-purple-500 to-pink-500',
},
{
title: 'AI清洗',
description: '智能数据清洗和格式化',
icon: Zap,
href: '/ai-agent/data-cleaning',
color: 'from-orange-500 to-red-500',
},
{
title: '智能报告',
description: '自动生成数据分析报告',
icon: FileText,
href: '/ai-agent/report',
color: 'from-indigo-500 to-purple-500',
},
]
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text)
}
return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/20">
<div className="p-6 space-y-6">
{/* 顶部标题 */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">AI Agent</h1>
<p className="text-sm text-gray-500 mt-1">//</p>
</div>
<div className="flex items-center gap-2">
<Badge className={aiStatus === 'online' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}>
<div className={`w-2 h-2 rounded-full ${aiStatus === 'online' ? 'bg-green-500' : 'bg-red-500'} mr-1.5`}></div>
{aiStatus === 'online' ? 'AI在线' : 'AI离线'}
</Badge>
<Badge variant="outline">{stats.avgLatency}ms</Badge>
</div>
</div>
{/* 统计卡片 */}
<div className="grid grid-cols-4 gap-4">
<Card className="border-0 shadow-sm bg-white/80">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold">{stats.todayQueries.toLocaleString()}</p>
</div>
<Send className="h-8 w-8 text-blue-500 opacity-50" />
</div>
</CardContent>
</Card>
<Card className="border-0 shadow-sm bg-white/80">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold">{(stats.totalQueries / 1000).toFixed(0)}K</p>
</div>
<Activity className="h-8 w-8 text-green-500 opacity-50" />
</div>
</CardContent>
</Card>
<Card className="border-0 shadow-sm bg-white/80">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold">{channels.filter(c => c.status === 'connected').length}</p>
</div>
<Webhook className="h-8 w-8 text-purple-500 opacity-50" />
</div>
</CardContent>
</Card>
<Card className="border-0 shadow-sm bg-white/80">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold">{stats.accuracy}%</p>
</div>
<CheckCircle2 className="h-8 w-8 text-orange-500 opacity-50" />
</div>
</CardContent>
</Card>
</div>
{/* 渠道状态 */}
<Card className="border-0 shadow-sm bg-white/80">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium flex items-center justify-between">
<span className="flex items-center gap-2">
<Webhook className="h-4 w-4 text-purple-500" />
</span>
<Link href="/ai-agent/channels">
<Button variant="ghost" size="sm">
<ArrowRight className="h-4 w-4 ml-1" />
</Button>
</Link>
</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-4 gap-3">
{channels.map((channel, i) => (
<div key={i} className="p-3 rounded-xl bg-gray-50 hover:bg-gray-100 transition-colors">
<div className="flex items-center justify-between mb-2">
<span className="text-2xl">{channel.icon}</span>
<Badge className={channel.status === 'connected' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}>
{channel.status === 'connected' ? '已连接' : '未连接'}
</Badge>
</div>
<h4 className="font-medium text-gray-900">{channel.name}</h4>
<p className="text-sm text-gray-500"> {channel.todayMessages} </p>
</div>
))}
</div>
</CardContent>
</Card>
{/* API接入说明 */}
<Card className="border-0 shadow-sm bg-gradient-to-r from-blue-50 to-purple-50">
<CardContent className="p-4">
<div className="flex items-start justify-between">
<div>
<h3 className="font-semibold text-gray-900 mb-1 flex items-center gap-2">
<Bot className="h-5 w-5 text-purple-500" />
Skill API
</h3>
<p className="text-sm text-gray-600 mb-3">Skill直接通信</p>
<div className="space-y-2">
<div className="flex items-center gap-2">
<code className="bg-white px-3 py-1.5 rounded text-sm font-mono text-purple-600 flex-1">
POST {API_BASE_URL}/chat
</code>
<Button variant="ghost" size="sm" onClick={() => copyToClipboard(`${API_BASE_URL}/chat`)}>
<Copy className="h-3 w-3" />
</Button>
</div>
<div className="flex items-center gap-2">
<code className="bg-white px-3 py-1.5 rounded text-sm font-mono text-purple-600 flex-1">
POST {API_BASE_URL}/query?phone=13800138000
</code>
<Button variant="ghost" size="sm" onClick={() => copyToClipboard(`${API_BASE_URL}/query`)}>
<Copy className="h-3 w-3" />
</Button>
</div>
</div>
</div>
<Link href="/ai-agent/channels">
<Button variant="outline" size="sm">
<Settings className="h-4 w-4 mr-1" />
</Button>
</Link>
</div>
</CardContent>
</Card>
{/* 功能模块 */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{modules.map((module, i) => (
<Link key={i} href={module.href}>
<Card className="border-0 shadow-sm bg-white/80 hover:shadow-lg transition-all cursor-pointer group h-full">
<CardContent className="p-5">
<div className={`w-12 h-12 rounded-xl bg-gradient-to-r ${module.color} flex items-center justify-center mb-4 group-hover:scale-110 transition-transform`}>
<module.icon className="w-6 h-6 text-white" />
</div>
<h3 className="font-bold text-gray-900 text-lg mb-1">{module.title}</h3>
<p className="text-sm text-gray-500">{module.description}</p>
<div className="flex items-center gap-1 mt-4 text-sm text-blue-600">
<span></span>
<ArrowRight className="h-4 w-4 group-hover:translate-x-1 transition-transform" />
</div>
</CardContent>
</Card>
</Link>
))}
</div>
{/* 使用说明 */}
<Card className="border-0 shadow-sm bg-white/80">
<CardHeader>
<CardTitle className="text-sm font-medium"></CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-3 gap-4">
<div className="p-4 rounded-xl bg-blue-50">
<div className="w-8 h-8 rounded-lg bg-blue-500 text-white flex items-center justify-center font-bold mb-2">1</div>
<h4 className="font-medium text-gray-900 mb-1"></h4>
<p className="text-sm text-gray-600">//</p>
</div>
<div className="p-4 rounded-xl bg-green-50">
<div className="w-8 h-8 rounded-lg bg-green-500 text-white flex items-center justify-center font-bold mb-2">2</div>
<h4 className="font-medium text-gray-900 mb-1"></h4>
<p className="text-sm text-gray-600">AppID和Secret</p>
</div>
<div className="p-4 rounded-xl bg-purple-50">
<div className="w-8 h-8 rounded-lg bg-purple-500 text-white flex items-center justify-center font-bold mb-2">3</div>
<h4 className="font-medium text-gray-900 mb-1"></h4>
<p className="text-sm text-gray-600">@机器人即可与神射手对话</p>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
)
}

View File

@@ -1,234 +1,709 @@
"use client"
import { useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Input } from "@/components/ui/input"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import {
FileText, Download, Share2, Clock, Eye, Sparkles,
BarChart3, Users, TrendingUp, Calendar, Plus, Trash2
import {
FileText,
Plus,
Download,
RefreshCw,
Eye,
Calendar,
Users,
TrendingUp,
PieChart,
BarChart3,
Clock,
CheckCircle2,
Loader2,
Send,
Mail,
MessageSquare,
Play,
Sparkles,
} from "lucide-react"
const reportTemplates = [
{ id: "1", name: "用户增长分析报告", description: "分析用户增长趋势和渠道效果", icon: TrendingUp },
{ id: "2", name: "用户画像洞察报告", description: "深度分析用户特征和行为偏好", icon: Users },
{ id: "3", name: "数据质量评估报告", description: "评估数据完整性和准确性", icon: BarChart3 },
{ id: "4", name: "营销效果分析报告", description: "评估营销活动ROI和转化效果", icon: TrendingUp },
]
// 报告规则接口
interface ReportRule {
id: string
name: string
templateId: string
schedule: string
enabled: boolean
isDefault: boolean
config: {
dateRange: string
includeCharts: boolean
sendTo: string[]
format: 'pdf' | 'html' | 'markdown'
}
promptTemplate: string
}
const recentReports = [
// 报告模板
interface ReportTemplate {
id: string
name: string
description: string
type: 'daily' | 'weekly' | 'monthly' | 'custom'
sections: string[]
icon: string
}
// 默认报告规则
const DEFAULT_RULES: ReportRule[] = [
{
id: "r1",
name: "2024年1月用户增长分析报告",
template: "用户增长分析报告",
createdAt: "2024-01-15 14:30",
status: "completed",
pages: 12,
id: 'rule_daily',
name: '每日运营日报规则',
templateId: 'tpl_daily',
schedule: '每日 23:59',
enabled: true,
isDefault: true,
config: {
dateRange: 'today',
includeCharts: true,
sendTo: ['admin@company.com'],
format: 'pdf',
},
promptTemplate: `生成每日运营日报,包含以下内容:
1. 核心指标
- 总用户数及日增量
- 活跃用户数及活跃率
- 新增用户数
2. 用户活跃
- 各等级用户活跃情况
- 活跃时段分布
3. 渠道消息
- 各渠道消息量统计
- 响应时间分析
4. AI查询统计
- 查询次数
- 平均响应时间
- 热门查询类型
输出格式:结构化报告,包含数据表格和趋势描述`,
},
{
id: "r2",
name: "高价值用户画像洞察",
template: "用户画像洞察报告",
createdAt: "2024-01-14 10:20",
status: "completed",
pages: 8,
id: 'rule_weekly',
name: '周度数据质量规则',
templateId: 'tpl_weekly',
schedule: '每周日 00:00',
enabled: true,
isDefault: true,
config: {
dateRange: 'week',
includeCharts: true,
sendTo: ['data@company.com'],
format: 'pdf',
},
promptTemplate: `生成周度数据质量报告:
1. 质量概览
- 数据完整度评分
- 数据准确度评分
- 本周质量趋势
2. 清洗统计
- 清洗记录数
- 格式化字段数
- 异常数据处理
3. 去重效果
- 去重前后对比
- 重复率统计
4. 数据完整度
- 各字段填充率
- 缺失字段分析`,
},
{
id: "r3",
name: "Q4数据质量评估",
template: "数据质量评估报告",
createdAt: "2024-01-10 16:45",
status: "generating",
pages: 0,
id: 'rule_monthly',
name: '月度资产报告规则',
templateId: 'tpl_monthly',
schedule: '每月1日 08:00',
enabled: true,
isDefault: true,
config: {
dateRange: 'month',
includeCharts: true,
sendTo: ['admin@company.com', 'ceo@company.com'],
format: 'pdf',
},
promptTemplate: `生成月度用户资产报告:
1. 资产总览
- 用户总资产价值
- 月度变化趋势
- 核心指标汇总
2. 用户增长
- 新增用户分析
- 流失用户分析
- 净增长情况
3. RFM分析
- RFM评分分布
- 各等级用户占比
- 价值迁移分析
4. 流量池分布
- 各流量池规模
- 月度变化
- 转化分析
5. 标签覆盖
- 标签覆盖率
- 热门标签TOP10`,
},
]
export default function AIReportPage() {
const [showCreateDialog, setShowCreateDialog] = useState(false)
const [selectedTemplate, setSelectedTemplate] = useState("")
const [reportConfig, setReportConfig] = useState({
name: "",
dateRange: "last_30_days",
userSegment: "all",
customPrompt: "",
})
// 预定义报告模板
const REPORT_TEMPLATES: ReportTemplate[] = [
{
id: 'tpl_daily',
name: '每日运营日报',
description: '包含当日用户活跃、渠道消息、AI查询等实时数据汇总',
type: 'daily',
sections: ['核心指标', '用户活跃', '渠道消息', 'AI查询统计'],
icon: '📊',
},
{
id: 'tpl_weekly',
name: '周度数据质量报告',
description: '数据清洗、去重、补全等质量指标周度汇总',
type: 'weekly',
sections: ['质量概览', '清洗统计', '去重效果', '数据完整度'],
icon: '📈',
},
{
id: 'tpl_monthly',
name: '月度用户资产报告',
description: '用户增长、RFM分布、流量池变化等核心资产指标',
type: 'monthly',
sections: ['资产总览', '用户增长', 'RFM分析', '流量池分布', '标签覆盖'],
icon: '📑',
},
{
id: 'tpl_rfm',
name: 'RFM分析报告',
description: '详细的RFM评分分布和用户价值分层分析',
type: 'custom',
sections: ['RFM概览', '评分分布', '等级分层', '价值趋势'],
icon: '💎',
},
{
id: 'tpl_portrait',
name: '用户画像报告',
description: '用户画像特征分析,包含地域、年龄、偏好等维度',
type: 'custom',
sections: ['画像概览', '地域分布', '行为特征', '偏好分析'],
icon: '👤',
},
{
id: 'tpl_traffic',
name: '流量池分析报告',
description: '各流量池用户规模、转化率、价值贡献分析',
type: 'custom',
sections: ['池规模', '转化漏斗', '价值贡献', '增长趋势'],
icon: '🏊',
},
]
// 生成的报告
interface GeneratedReport {
id: string
templateId: string
title: string
generatedAt: string
status: 'ready' | 'generating'
content?: string
metrics: {
totalUsers: number
activeUsers: number
newUsers: number
rfmAvg: number
}
}
const GENERATED_REPORTS: GeneratedReport[] = [
{
id: 'rpt_1',
templateId: 'tpl_monthly',
title: '2024年1月用户资产月报',
generatedAt: '2024-02-01 08:00',
status: 'ready',
metrics: { totalUsers: 2013000000, activeUsers: 450000000, newUsers: 15000000, rfmAvg: 52.3 },
},
{
id: 'rpt_2',
templateId: 'tpl_weekly',
title: '本周数据质量报告',
generatedAt: '2024-01-28 00:00',
status: 'ready',
metrics: { totalUsers: 2013000000, activeUsers: 320000000, newUsers: 2500000, rfmAvg: 51.8 },
},
{
id: 'rpt_3',
templateId: 'tpl_daily',
title: '今日运营日报',
generatedAt: '2024-01-30 23:59',
status: 'ready',
metrics: { totalUsers: 2013000000, activeUsers: 45000000, newUsers: 350000, rfmAvg: 52.5 },
},
]
export default function ReportPage() {
const [reports, setReports] = useState<GeneratedReport[]>(GENERATED_REPORTS)
const [rules, setRules] = useState<ReportRule[]>(DEFAULT_RULES)
const [activeTab, setActiveTab] = useState("templates")
const [generating, setGenerating] = useState<string | null>(null)
const [showGenerateDialog, setShowGenerateDialog] = useState(false)
const [selectedTemplate, setSelectedTemplate] = useState<ReportTemplate | null>(null)
const [showPreviewDialog, setShowPreviewDialog] = useState(false)
const [previewReport, setPreviewReport] = useState<GeneratedReport | null>(null)
const [showRuleDialog, setShowRuleDialog] = useState(false)
const [selectedRule, setSelectedRule] = useState<ReportRule | null>(null)
const [editingPrompt, setEditingPrompt] = useState('')
const formatNumber = (num: number): string => {
if (num >= 1000000000) return `${(num / 1000000000).toFixed(2)}B`
if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`
if (num >= 1000) return `${(num / 1000).toFixed(0)}K`
return num.toLocaleString()
}
// 通过Skill生成报告
const generateReport = async (template: ReportTemplate) => {
setGenerating(template.id)
setShowGenerateDialog(false)
try {
// 调用AI Chat API执行报告生成
const response = await fetch('/api/ai-chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: `生成${template.name},包含以下章节:${template.sections.join('、')}`
})
})
const data = await response.json()
// 添加新报告到列表
const newReport: GeneratedReport = {
id: `rpt_${Date.now()}`,
templateId: template.id,
title: `${template.name} - ${new Date().toLocaleDateString()}`,
generatedAt: new Date().toLocaleString(),
status: 'ready',
content: data.success ? data.response?.content : '报告生成失败',
metrics: {
totalUsers: 2013000000,
activeUsers: 450000000,
newUsers: 15000000,
rfmAvg: 52.3,
},
}
setReports([newReport, ...reports])
} catch (error) {
console.error('报告生成失败:', error)
} finally {
setGenerating(null)
}
}
const openPreview = (report: GeneratedReport) => {
setPreviewReport(report)
setShowPreviewDialog(true)
}
return (
<div className="space-y-6">
{/* 页面标题 */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-foreground"></h1>
<p className="text-muted-foreground">AI自动生成数据分析报告</p>
<div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/20">
<div className="p-6 space-y-6">
{/* 顶部标题 */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900"></h1>
<p className="text-sm text-gray-500 mt-1">AI自动生成数据分析报告</p>
</div>
<Button onClick={() => setShowGenerateDialog(true)}>
<Plus className="h-4 w-4 mr-2" />
</Button>
</div>
<Button onClick={() => setShowCreateDialog(true)}>
<Plus className="mr-2 h-4 w-4" />
</Button>
</div>
{/* 报告模板 */}
<div>
<h2 className="text-lg font-semibold mb-4"></h2>
<div className="grid gap-4 md:grid-cols-4">
{reportTemplates.map((template) => (
<Card
key={template.id}
className="cursor-pointer hover:border-primary transition-colors"
onClick={() => {
setSelectedTemplate(template.id)
setShowCreateDialog(true)
}}
>
<CardContent className="pt-6">
<div className="flex flex-col items-center text-center">
<div className="p-3 rounded-full bg-primary/10 mb-3">
<template.icon className="h-6 w-6 text-primary" />
</div>
<h3 className="font-medium mb-1">{template.name}</h3>
<p className="text-sm text-muted-foreground">{template.description}</p>
{/* 标签页 */}
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList className="bg-white/80 backdrop-blur">
<TabsTrigger value="templates"></TabsTrigger>
<TabsTrigger value="rules"></TabsTrigger>
<TabsTrigger value="history"></TabsTrigger>
</TabsList>
{/* 报告模板 */}
<TabsContent value="templates" className="mt-4">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{REPORT_TEMPLATES.map(template => (
<Card
key={template.id}
className="border-0 shadow-sm bg-white/80 hover:shadow-lg transition-all cursor-pointer group"
>
<CardContent className="p-5">
<div className="flex items-start justify-between mb-3">
<span className="text-3xl">{template.icon}</span>
<Badge variant="outline">{
template.type === 'daily' ? '日报' :
template.type === 'weekly' ? '周报' :
template.type === 'monthly' ? '月报' : '自定义'
}</Badge>
</div>
<h3 className="font-bold text-gray-900 text-lg mb-1">{template.name}</h3>
<p className="text-sm text-gray-500 mb-3">{template.description}</p>
<div className="flex flex-wrap gap-1 mb-4">
{template.sections.map((section, i) => (
<Badge key={i} variant="secondary" className="text-xs">{section}</Badge>
))}
</div>
<Button
className="w-full"
onClick={() => generateReport(template)}
disabled={generating === template.id}
>
{generating === template.id ? (
<><Loader2 className="h-4 w-4 animate-spin mr-2" />...</>
) : (
<><Play className="h-4 w-4 mr-2" /></>
)}
</Button>
</CardContent>
</Card>
))}
</div>
</TabsContent>
{/* 规则配置 */}
<TabsContent value="rules" className="mt-4 space-y-3">
{rules.map(rule => {
const template = REPORT_TEMPLATES.find(t => t.id === rule.templateId)
return (
<Card key={rule.id} className="border-0 shadow-sm bg-white/80 backdrop-blur">
<CardContent className="p-4">
<div className="flex items-start justify-between">
<div className="flex items-center gap-3">
<div className="p-2.5 rounded-xl bg-gradient-to-r from-purple-500 to-blue-500 text-2xl">
{template?.icon || '📄'}
</div>
<div>
<div className="flex items-center gap-2">
<h3 className="font-semibold text-gray-900">{rule.name}</h3>
{rule.isDefault && <Badge variant="outline" className="text-xs"></Badge>}
{rule.enabled ? (
<Badge className="bg-green-100 text-green-700"></Badge>
) : (
<Badge className="bg-gray-100 text-gray-700"></Badge>
)}
</div>
<p className="text-sm text-gray-500">{template?.name}</p>
<div className="flex items-center gap-4 text-xs text-gray-400 mt-1">
<span className="flex items-center gap-1">
<Clock className="h-3 w-3" />
{rule.schedule}
</span>
<span>: {rule.config.format.toUpperCase()}</span>
<span>: {rule.config.sendTo.join(', ')}</span>
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => {
setSelectedRule(rule)
setEditingPrompt(rule.promptTemplate)
setShowRuleDialog(true)
}}
>
</Button>
<Button
variant={rule.enabled ? "outline" : "default"}
size="sm"
onClick={() => setRules(rules.map(r => r.id === rule.id ? { ...r, enabled: !r.enabled } : r))}
>
{rule.enabled ? '禁用' : '启用'}
</Button>
</div>
</div>
</CardContent>
</Card>
)
})}
</TabsContent>
{/* 历史报告 */}
<TabsContent value="history" className="mt-4">
<Card className="border-0 shadow-sm bg-white/80">
<CardContent className="p-4">
<div className="space-y-3">
{reports.map(report => {
const template = REPORT_TEMPLATES.find(t => t.id === report.templateId)
return (
<div key={report.id} className="flex items-center justify-between p-4 rounded-xl bg-gray-50 hover:bg-gray-100 transition-colors">
<div className="flex items-center gap-4">
<div className="p-2.5 rounded-xl bg-white text-2xl">
{template?.icon || '📄'}
</div>
<div>
<h3 className="font-semibold text-gray-900">{report.title}</h3>
<div className="flex items-center gap-4 mt-1 text-xs text-gray-500">
<span className="flex items-center gap-1">
<Clock className="h-3 w-3" />
{report.generatedAt}
</span>
<span className="flex items-center gap-1">
<Users className="h-3 w-3" />
{formatNumber(report.metrics.totalUsers)}
</span>
<span>RFM均值: {report.metrics.rfmAvg}</span>
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={() => openPreview(report)}>
<Eye className="h-4 w-4" />
</Button>
<Button variant="outline" size="sm">
<Download className="h-4 w-4" />
</Button>
<Button variant="outline" size="sm">
<Send className="h-4 w-4" />
</Button>
</div>
</div>
)
})}
</div>
</CardContent>
</Card>
))}
</div>
</div>
</TabsContent>
</Tabs>
{/* 最近报告 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
{recentReports.map((report) => (
<div
key={report.id}
className="flex items-center justify-between p-4 border rounded-lg hover:bg-muted/50 transition-colors"
>
<div className="flex items-center gap-4">
<div className="p-2 rounded-lg bg-primary/10">
<FileText className="h-5 w-5 text-primary" />
{/* 生成报告弹窗 */}
<Dialog open={showGenerateDialog} onOpenChange={setShowGenerateDialog}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>AI将自动生成分析报告</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label></Label>
<Select onValueChange={(v) => setSelectedTemplate(REPORT_TEMPLATES.find(t => t.id === v) || null)}>
<SelectTrigger>
<SelectValue placeholder="选择报告模板" />
</SelectTrigger>
<SelectContent>
{REPORT_TEMPLATES.map(template => (
<SelectItem key={template.id} value={template.id}>
{template.icon} {template.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedTemplate && (
<div className="p-3 rounded-lg bg-purple-50">
<p className="text-sm text-gray-600 mb-2">{selectedTemplate.description}</p>
<div className="flex flex-wrap gap-1">
{selectedTemplate.sections.map((section, i) => (
<Badge key={i} variant="secondary" className="text-xs">{section}</Badge>
))}
</div>
<div>
<h4 className="font-medium">{report.name}</h4>
<div className="flex items-center gap-4 text-sm text-muted-foreground">
<span>{report.template}</span>
<span className="flex items-center gap-1">
<Clock className="h-3 w-3" />
{report.createdAt}
</span>
{report.status === "completed" && (
<span>{report.pages}</span>
</div>
)}
<div className="space-y-2">
<Label></Label>
<Select defaultValue="all">
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="today"></SelectItem>
<SelectItem value="week"></SelectItem>
<SelectItem value="month"></SelectItem>
</SelectContent>
</Select>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowGenerateDialog(false)}></Button>
<Button
onClick={() => selectedTemplate && generateReport(selectedTemplate)}
disabled={!selectedTemplate}
>
<Sparkles className="h-4 w-4 mr-2" />
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 报告预览弹窗 */}
<Dialog open={showPreviewDialog} onOpenChange={setShowPreviewDialog}>
<DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{previewReport?.title}</DialogTitle>
<DialogDescription>: {previewReport?.generatedAt}</DialogDescription>
</DialogHeader>
{previewReport && (
<div className="space-y-4 py-4">
{/* 核心指标 */}
<div className="grid grid-cols-4 gap-4">
<Card className="border bg-blue-50">
<CardContent className="p-3 text-center">
<div className="text-2xl font-bold text-blue-600">{formatNumber(previewReport.metrics.totalUsers)}</div>
<div className="text-xs text-gray-500"></div>
</CardContent>
</Card>
<Card className="border bg-green-50">
<CardContent className="p-3 text-center">
<div className="text-2xl font-bold text-green-600">{formatNumber(previewReport.metrics.activeUsers)}</div>
<div className="text-xs text-gray-500"></div>
</CardContent>
</Card>
<Card className="border bg-orange-50">
<CardContent className="p-3 text-center">
<div className="text-2xl font-bold text-orange-600">{formatNumber(previewReport.metrics.newUsers)}</div>
<div className="text-xs text-gray-500"></div>
</CardContent>
</Card>
<Card className="border bg-purple-50">
<CardContent className="p-3 text-center">
<div className="text-2xl font-bold text-purple-600">{previewReport.metrics.rfmAvg}</div>
<div className="text-xs text-gray-500">RFM均值</div>
</CardContent>
</Card>
</div>
{/* 报告内容 */}
<Card className="border">
<CardContent className="p-4">
<h4 className="font-medium text-gray-900 mb-3"></h4>
<div className="prose prose-sm text-gray-600">
{previewReport.content || (
<div className="space-y-2">
<p></p>
<p><strong>:</strong> {formatNumber(previewReport.metrics.totalUsers)}{((previewReport.metrics.activeUsers / previewReport.metrics.totalUsers) * 100).toFixed(1)}%</p>
<p><strong>:</strong> RFM评分{previewReport.metrics.rfmAvg}0.5</p>
<p><strong>:</strong> {formatNumber(previewReport.metrics.newUsers)}8.2%</p>
</div>
)}
</div>
</CardContent>
</Card>
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setShowPreviewDialog(false)}></Button>
<Button variant="outline">
<Download className="h-4 w-4 mr-2" />
PDF
</Button>
<Button>
<Send className="h-4 w-4 mr-2" />
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 规则编辑弹窗 */}
<Dialog open={showRuleDialog} onOpenChange={setShowRuleDialog}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>{selectedRule?.name}</DialogDescription>
</DialogHeader>
{selectedRule && (
<div className="space-y-4 py-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label></Label>
<Input value={selectedRule.schedule} readOnly className="bg-gray-50" />
</div>
<div className="space-y-2">
<Label></Label>
<Select defaultValue={selectedRule.config.format}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="pdf">PDF</SelectItem>
<SelectItem value="html">HTML</SelectItem>
<SelectItem value="markdown">Markdown</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="flex items-center gap-2">
{report.status === "generating" ? (
<Badge className="bg-blue-100 text-blue-700">
<Sparkles className="h-3 w-3 mr-1 animate-pulse" />
</Badge>
) : (
<>
<Button variant="outline" size="sm">
<Eye className="h-4 w-4 mr-1" />
</Button>
<Button variant="outline" size="sm">
<Download className="h-4 w-4 mr-1" />
</Button>
<Button variant="outline" size="sm">
<Share2 className="h-4 w-4" />
</Button>
</>
)}
<div className="space-y-2">
<Label></Label>
<Input defaultValue={selectedRule.config.sendTo.join(', ')} placeholder="多个邮箱用逗号分隔" />
</div>
<div className="space-y-2">
<Label> <span className="text-gray-400 text-xs">(AI根据此提示词生成报告内容)</span></Label>
<Textarea
value={editingPrompt}
onChange={(e) => setEditingPrompt(e.target.value)}
rows={12}
className="font-mono text-sm"
/>
</div>
</div>
))}
</div>
</CardContent>
</Card>
{/* 创建报告弹窗 */}
<Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>AI将自动生成分析报告</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label></Label>
<Input
placeholder="输入报告名称"
value={reportConfig.name}
onChange={(e) => setReportConfig({...reportConfig, name: e.target.value})}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label></Label>
<Select
value={reportConfig.dateRange}
onValueChange={(v) => setReportConfig({...reportConfig, dateRange: v})}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="last_7_days">7</SelectItem>
<SelectItem value="last_30_days">30</SelectItem>
<SelectItem value="last_90_days">90</SelectItem>
<SelectItem value="custom"></SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label></Label>
<Select
value={reportConfig.userSegment}
onValueChange={(v) => setReportConfig({...reportConfig, userSegment: v})}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="high_value"></SelectItem>
<SelectItem value="new_users"></SelectItem>
<SelectItem value="active"></SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label></Label>
<Textarea
placeholder="输入额外的分析要求,例如:重点分析转化漏斗、对比上月数据等"
value={reportConfig.customPrompt}
onChange={(e) => setReportConfig({...reportConfig, customPrompt: e.target.value})}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowCreateDialog(false)}></Button>
<Button>
<Sparkles className="mr-2 h-4 w-4" />
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setShowRuleDialog(false)}></Button>
<Button onClick={() => {
if (selectedRule) {
setRules(rules.map(r => r.id === selectedRule.id ? { ...r, promptTemplate: editingPrompt } : r))
}
setShowRuleDialog(false)
}}>
<CheckCircle2 className="h-4 w-4 mr-2" />
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</div>
)
}

View File

@@ -1,14 +1,12 @@
"use client"
import { useState } from "react"
import { useState, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Progress } from "@/components/ui/progress"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Checkbox } from "@/components/ui/checkbox"
import {
Dialog,
DialogContent,
@@ -24,523 +22,537 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import {
Tags,
Plus,
Search,
Sparkles,
Play,
Pause,
CheckCircle2,
Clock,
AlertCircle,
Settings,
FileText,
Plus,
CheckCircle2,
Loader2,
RefreshCw,
Sparkles,
ThumbsUp,
ThumbsDown,
Tags,
Database,
Brain,
Edit,
Trash2,
Copy,
Eye,
MoreVertical,
Bot,
Clock,
Target,
Zap,
} from "lucide-react"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
// 第四部分AI Agent - AI打标
export default function AISmartTagPage() {
// 打标任务接口
interface TaggingTask {
id: string
name: string
description: string
promptTemplate: string
sourceDb: string
sourceCollection: string
targetTags: string[]
status: 'idle' | 'running' | 'paused' | 'completed'
progress: number
stats: {
totalRecords: number
processedRecords: number
taggedRecords: number
accuracy: number
}
createdAt: string
lastRunAt?: string
}
// 默认提示词模板
const DEFAULT_PROMPTS = {
value: {
name: '价值类打标',
prompt: `你是用户资产数字化专家。请分析以下用户数据,生成价值类标签:
用户数据: {user_data}
打标规则:
- RFM评分≥90: 输出"高价值用户"
- RFM评分≥70: 输出"优质用户"
- RFM评分≥50: 输出"普通用户"
- RFM评分<50: 输出"待激活用户"
- 近30天无活跃且历史RFM≥60: 输出"流失风险"
输出格式: ["标签1", "标签2", ...]
只输出标签数组,不要其他内容。`,
},
behavior: {
name: '行为类打标',
prompt: `分析用户行为数据,生成行为类标签:
用户数据: {user_data}
打标规则:
- 日活跃(每日登录): 输出"高频用户"
- 周活跃(每周≥3天): 输出"活跃用户"
- 月活跃(每月≥5天): 输出"普通用户"
- 30天+未活跃: 输出"沉默用户"
- 注册≤7天: 输出"新用户"
输出格式: ["标签1", "标签2", ...]`,
},
preference: {
name: '偏好类打标',
prompt: `分析用户消费和行为数据,生成偏好类标签:
用户数据: {user_data}
打标规则:
- 电商消费≥5次/月: 输出"电商活跃"
- 社交互动≥10次/天: 输出"社交达人"
- 浏览金融产品: 输出"金融偏好"
- 游戏时长≥2h/天: 输出"游戏玩家"
输出格式: ["标签1", "标签2", ...]`,
},
region: {
name: '地域类打标',
prompt: `分析用户地理位置数据,生成地域类标签:
用户数据: {user_data}
打标规则:
- 省份为北京/上海/广州/深圳: 输出"一线城市"
- 省份为福建且城市为厦门: 输出"厦门本地"
- 根据省份输出对应地域标签
输出格式: ["标签1", "标签2", ...]`,
},
}
// 预定义任务
const DEFAULT_TASKS: TaggingTask[] = [
{
id: 'task_1',
name: '腾讯QQ用户价值打标',
description: '基于RFM评分为QQ用户打价值类标签',
promptTemplate: DEFAULT_PROMPTS.value.prompt,
sourceDb: 'KR_腾讯',
sourceCollection: 'qq_phone',
targetTags: ['高价值用户', '优质用户', '普通用户', '待激活用户', '流失风险'],
status: 'completed',
progress: 100,
stats: {
totalRecords: 705000000,
processedRecords: 705000000,
taggedRecords: 680000000,
accuracy: 96.4,
},
createdAt: '2024-01-15',
lastRunAt: '2024-01-30 14:30',
},
{
id: 'task_2',
name: '京东用户行为打标',
description: '基于消费行为为京东用户打行为类标签',
promptTemplate: DEFAULT_PROMPTS.behavior.prompt,
sourceDb: 'KR_京东',
sourceCollection: 'users',
targetTags: ['高频用户', '活跃用户', '普通用户', '沉默用户', '新用户'],
status: 'running',
progress: 65,
stats: {
totalRecords: 89000000,
processedRecords: 57850000,
taggedRecords: 55000000,
accuracy: 94.2,
},
createdAt: '2024-01-20',
lastRunAt: '2024-01-30 15:00',
},
{
id: 'task_3',
name: '存客宝用户偏好打标',
description: '基于CRM数据为存客宝用户打偏好标签',
promptTemplate: DEFAULT_PROMPTS.preference.prompt,
sourceDb: 'cunkebao_v3',
sourceCollection: 'users',
targetTags: ['电商活跃', '社交达人', '金融偏好', '游戏玩家'],
status: 'idle',
progress: 0,
stats: {
totalRecords: 216000,
processedRecords: 0,
taggedRecords: 0,
accuracy: 0,
},
createdAt: '2024-01-25',
},
]
export default function SmartTagPage() {
const [tasks, setTasks] = useState<TaggingTask[]>(DEFAULT_TASKS)
const [activeTab, setActiveTab] = useState("tasks")
const [searchQuery, setSearchQuery] = useState("")
const [selectedTask, setSelectedTask] = useState<TaggingTask | null>(null)
const [showCreateDialog, setShowCreateDialog] = useState(false)
const [showReviewDialog, setShowReviewDialog] = useState(false)
const [selectedTask, setSelectedTask] = useState<any>(null)
const [selectedItems, setSelectedItems] = useState<string[]>([])
const [showPromptDialog, setShowPromptDialog] = useState(false)
const [editingPrompt, setEditingPrompt] = useState('')
const [selectedPromptType, setSelectedPromptType] = useState<keyof typeof DEFAULT_PROMPTS>('value')
// AI打标任务列表
const tagTasks = [
{
id: "1",
name: "高价值用户识别",
prompt: "根据用户的消费金额、频次、最近活跃时间,识别高价值用户",
status: "completed",
targetTag: "高价值用户",
dataSource: "用户表+交易表",
affectedCount: 45678,
confidence: 0.92,
createdAt: "2026-01-30 10:00",
completedAt: "2026-01-30 10:15",
needReview: false,
},
{
id: "2",
name: "流失风险预警",
prompt: "识别最近30天未登录且之前活跃的用户标记为流失风险",
status: "pending_review",
targetTag: "流失风险",
dataSource: "用户行为表",
affectedCount: 12456,
confidence: 0.87,
createdAt: "2026-01-31 09:00",
completedAt: "2026-01-31 09:12",
needReview: true,
reviewStats: { approved: 0, rejected: 0, pending: 12456 },
},
{
id: "3",
name: "兴趣标签推断",
prompt: "根据用户浏览和购买记录,推断用户兴趣偏好",
status: "running",
targetTag: "兴趣标签",
dataSource: "行为日志表",
affectedCount: 0,
confidence: 0,
createdAt: "2026-01-31 14:00",
progress: 67,
},
{
id: "4",
name: "地域特征识别",
prompt: "根据IP地址和收货地址识别用户地域特征",
status: "failed",
targetTag: "地域标签",
dataSource: "用户表+订单表",
affectedCount: 0,
confidence: 0,
createdAt: "2026-01-29 15:00",
error: "数据源连接超时",
},
]
// 待审核的标签结果
const pendingReviews = [
{ id: "r1", userId: "U10001", userName: "张三", currentTags: ["活跃用户"], newTag: "流失风险", confidence: 0.92, reason: "30天未登录" },
{ id: "r2", userId: "U10002", userName: "李四", currentTags: ["普通用户"], newTag: "流失风险", confidence: 0.88, reason: "25天未登录" },
{ id: "r3", userId: "U10003", userName: "王五", currentTags: ["新用户"], newTag: "流失风险", confidence: 0.75, reason: "注册后未活跃" },
{ id: "r4", userId: "U10004", userName: "赵六", currentTags: ["VIP用户"], newTag: "流失风险", confidence: 0.65, reason: "消费频次下降" },
{ id: "r5", userId: "U10005", userName: "钱七", currentTags: ["活跃用户"], newTag: "流失风险", confidence: 0.58, reason: "互动减少" },
]
const formatNumber = (num: number): string => {
if (num >= 1000000000) return `${(num / 1000000000).toFixed(2)}B`
if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`
if (num >= 1000) return `${(num / 1000).toFixed(0)}K`
return num.toLocaleString()
}
const getStatusBadge = (status: string) => {
switch (status) {
case "completed":
return <Badge className="bg-green-100 text-green-700"></Badge>
case "running":
return <Badge className="bg-blue-100 text-blue-700"></Badge>
case "pending_review":
return <Badge className="bg-yellow-100 text-yellow-700"></Badge>
case "failed":
return <Badge className="bg-red-100 text-red-700"></Badge>
case 'completed':
return <Badge className="bg-green-100 text-green-700"><CheckCircle2 className="h-3 w-3 mr-1" /></Badge>
case 'running':
return <Badge className="bg-blue-100 text-blue-700"><Loader2 className="h-3 w-3 mr-1 animate-spin" /></Badge>
case 'paused':
return <Badge className="bg-yellow-100 text-yellow-700"><Pause className="h-3 w-3 mr-1" /></Badge>
default:
return <Badge variant="secondary"></Badge>
return <Badge className="bg-gray-100 text-gray-700"></Badge>
}
}
const getConfidenceColor = (confidence: number) => {
if (confidence >= 0.8) return "text-green-600"
if (confidence >= 0.6) return "text-yellow-600"
return "text-red-600"
// 模拟进度更新
useEffect(() => {
const interval = setInterval(() => {
setTasks(prev => prev.map(t => {
if (t.status === 'running' && t.progress < 100) {
const newProgress = Math.min(t.progress + Math.random() * 2, 100)
return {
...t,
progress: newProgress,
status: newProgress >= 100 ? 'completed' as const : t.status,
stats: {
...t.stats,
processedRecords: Math.floor(t.stats.totalRecords * newProgress / 100),
taggedRecords: Math.floor(t.stats.totalRecords * newProgress / 100 * 0.95),
}
}
}
return t
}))
}, 3000)
return () => clearInterval(interval)
}, [])
const runTask = (taskId: string) => {
setTasks(tasks.map(t => t.id === taskId ? { ...t, status: 'running' as const } : t))
}
const handleOpenReview = (task: any) => {
const pauseTask = (taskId: string) => {
setTasks(tasks.map(t => t.id === taskId ? { ...t, status: 'paused' as const } : t))
}
const openPromptEditor = (task: TaggingTask) => {
setSelectedTask(task)
setShowReviewDialog(true)
setEditingPrompt(task.promptTemplate)
setShowPromptDialog(true)
}
const handleBatchApprove = () => {
console.log("批量通过", selectedItems)
setSelectedItems([])
}
const handleBatchReject = () => {
console.log("批量拒绝", selectedItems)
setSelectedItems([])
const savePrompt = () => {
if (selectedTask) {
setTasks(tasks.map(t => t.id === selectedTask.id ? { ...t, promptTemplate: editingPrompt } : t))
setShowPromptDialog(false)
}
}
return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/20">
<div className="p-6 space-y-6">
{/* 顶部标题 */}
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">AI智能打标</h1>
<p className="text-sm text-gray-500 mt-1">使AI自动识别用户特征并打标签</p>
<p className="text-sm text-gray-500 mt-1">AI自动为用户打标签</p>
</div>
<div className="flex items-center gap-3">
<Button variant="outline">
<RefreshCw className="h-4 w-4 mr-2" />
</Button>
<Button onClick={() => setShowCreateDialog(true)}>
<Plus className="h-4 w-4 mr-2" />
</Button>
</div>
</div>
{/* 统计卡片 */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<Card className="bg-white/80 backdrop-blur border-0 shadow-sm">
<div className="grid grid-cols-4 gap-4">
<Card className="border-0 shadow-sm bg-white/80 backdrop-blur">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold text-gray-900">{tagTasks.length}</p>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold">{tasks.length}</p>
</div>
<div className="p-3 rounded-xl bg-purple-100">
<Sparkles className="h-6 w-6 text-purple-600" />
</div>
<Bot className="h-8 w-8 text-purple-500" />
</div>
</CardContent>
</Card>
<Card className="bg-white/80 backdrop-blur border-0 shadow-sm">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold text-yellow-600">
{tagTasks.filter((t) => t.status === "pending_review").length}
</p>
</div>
<Clock className="h-8 w-8 text-yellow-500" />
</div>
</CardContent>
</Card>
<Card className="bg-white/80 backdrop-blur border-0 shadow-sm">
<Card className="border-0 shadow-sm bg-white/80 backdrop-blur">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold text-green-600">58,134</p>
<p className="text-2xl font-bold text-green-600">{formatNumber(tasks.reduce((sum, t) => sum + t.stats.taggedRecords, 0))}</p>
</div>
<div className="p-3 rounded-xl bg-green-100">
<Tags className="h-6 w-6 text-green-600" />
</div>
<Tags className="h-8 w-8 text-green-500" />
</div>
</CardContent>
</Card>
<Card className="bg-white/80 backdrop-blur border-0 shadow-sm">
<Card className="border-0 shadow-sm bg-white/80 backdrop-blur">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold text-blue-600">87.5%</p>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold text-blue-600">
{(tasks.filter(t => t.stats.accuracy > 0).reduce((sum, t) => sum + t.stats.accuracy, 0) / tasks.filter(t => t.stats.accuracy > 0).length || 0).toFixed(1)}%
</p>
</div>
<div className="p-3 rounded-xl bg-blue-100">
<Target className="h-6 w-6 text-blue-600" />
</div>
</div>
</CardContent>
</Card>
<Card className="border-0 shadow-sm bg-white/80 backdrop-blur">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500"></p>
<p className="text-2xl font-bold text-orange-600">{tasks.filter(t => t.status === 'running').length}</p>
</div>
<div className="p-3 rounded-xl bg-orange-100">
<Zap className="h-6 w-6 text-orange-600" />
</div>
<Sparkles className="h-8 w-8 text-blue-500" />
</div>
</CardContent>
</Card>
</div>
{/* Tabs */}
{/* 标签页 */}
<Tabs value={activeTab} onValueChange={setActiveTab}>
<div className="flex items-center justify-between">
<TabsList className="bg-white">
<TabsTrigger value="tasks"></TabsTrigger>
<TabsTrigger value="review"></TabsTrigger>
<TabsTrigger value="history"></TabsTrigger>
</TabsList>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
<Input
placeholder="搜索任务..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9 w-64 bg-white"
/>
</div>
</div>
<TabsList className="bg-white/80 backdrop-blur">
<TabsTrigger value="tasks"></TabsTrigger>
<TabsTrigger value="prompts"></TabsTrigger>
</TabsList>
<TabsContent value="tasks" className="mt-4">
<div className="space-y-4">
{tagTasks.map((task) => (
<Card key={task.id} className="bg-white/80 backdrop-blur border-0 shadow-sm">
<CardContent className="p-5">
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-3 mb-2">
{/* 打标任务列表 */}
<TabsContent value="tasks" className="mt-4 space-y-3">
{tasks.map(task => (
<Card key={task.id} className="border-0 shadow-sm bg-white/80 backdrop-blur hover:shadow-lg transition-all">
<CardContent className="p-4">
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-3">
<div className="p-2.5 rounded-xl bg-gradient-to-r from-purple-500 to-blue-500">
<Sparkles className="h-5 w-5 text-white" />
</div>
<div>
<div className="flex items-center gap-2">
<h3 className="font-semibold text-gray-900">{task.name}</h3>
{getStatusBadge(task.status)}
<Badge variant="outline">{task.targetTag}</Badge>
</div>
<p className="text-sm text-gray-500 mb-3">{task.prompt}</p>
<div className="flex items-center gap-6 text-sm text-gray-500">
<span>{task.dataSource}</span>
{task.affectedCount > 0 && (
<span>{task.affectedCount.toLocaleString()}</span>
)}
{task.confidence > 0 && (
<span className={getConfidenceColor(task.confidence)}>
{(task.confidence * 100).toFixed(0)}%
</span>
)}
<span>{task.createdAt}</span>
<p className="text-sm text-gray-500">{task.description}</p>
<div className="text-xs text-gray-400 mt-1 font-mono">
{task.sourceDb}.{task.sourceCollection}
</div>
{task.status === "running" && (
<div className="mt-3">
<div className="flex items-center justify-between text-sm mb-1">
<span className="text-gray-500"></span>
<span className="text-blue-600">{task.progress}%</span>
</div>
<div className="w-full h-2 bg-gray-100 rounded-full overflow-hidden">
<div
className="h-full bg-blue-500 rounded-full transition-all"
style={{ width: `${task.progress}%` }}
/>
</div>
</div>
)}
{task.status === "failed" && (
<div className="mt-3 p-3 bg-red-50 rounded-lg text-sm text-red-600">
{task.error}
</div>
)}
</div>
<div className="flex items-center gap-2">
{task.status === "pending_review" && (
<Button size="sm" onClick={() => handleOpenReview(task)}>
<Eye className="h-4 w-4 mr-1" />
</Button>
)}
{task.status === "failed" && (
<Button size="sm" variant="outline">
<RefreshCw className="h-4 w-4 mr-1" />
</Button>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem>
<FileText className="h-4 w-4 mr-2" />
</DropdownMenuItem>
<DropdownMenuItem>
<Settings className="h-4 w-4 mr-2" />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => openPromptEditor(task)}
>
<Edit className="h-4 w-4 mr-1" />
</Button>
{task.status === 'idle' && (
<Button size="sm" onClick={() => runTask(task.id)}>
<Play className="h-4 w-4 mr-1" />
</Button>
)}
{task.status === 'running' && (
<Button size="sm" variant="outline" onClick={() => pauseTask(task.id)}>
<Pause className="h-4 w-4 mr-1" />
</Button>
)}
{task.status === 'paused' && (
<Button size="sm" onClick={() => runTask(task.id)}>
<Play className="h-4 w-4 mr-1" />
</Button>
)}
</div>
</div>
{/* 进度条 */}
<div className="mb-3">
<div className="flex items-center justify-between text-sm mb-1">
<span className="text-gray-500"></span>
<span className="font-medium">{task.progress.toFixed(0)}%</span>
</div>
<Progress value={task.progress} className="h-2" />
</div>
{/* 目标标签 */}
<div className="flex flex-wrap gap-1 mb-3">
{task.targetTags.map((tag, i) => (
<Badge key={i} variant="secondary" className="text-xs">{tag}</Badge>
))}
</div>
{/* 统计信息 */}
<div className="grid grid-cols-4 gap-4 text-sm pt-3 border-t">
<div>
<span className="text-gray-500">:</span>
<span className="ml-2 font-medium">{formatNumber(task.stats.totalRecords)}</span>
</div>
<div>
<span className="text-gray-500">:</span>
<span className="ml-2 font-medium text-blue-600">{formatNumber(task.stats.processedRecords)}</span>
</div>
<div>
<span className="text-gray-500">:</span>
<span className="ml-2 font-medium text-green-600">{formatNumber(task.stats.taggedRecords)}</span>
</div>
<div>
<span className="text-gray-500">:</span>
<span className="ml-2 font-medium text-purple-600">{task.stats.accuracy}%</span>
</div>
</div>
</CardContent>
</Card>
))}
</TabsContent>
{/* 提示词模板 */}
<TabsContent value="prompts" className="mt-4">
<div className="grid grid-cols-2 gap-4">
{Object.entries(DEFAULT_PROMPTS).map(([key, config]) => (
<Card key={key} className="border-0 shadow-sm bg-white/80 backdrop-blur">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium flex items-center justify-between">
<span className="flex items-center gap-2">
<Brain className="h-4 w-4 text-purple-500" />
{config.name}
</span>
<Button variant="ghost" size="sm">
<Copy className="h-3 w-3" />
</Button>
</CardTitle>
</CardHeader>
<CardContent>
<pre className="text-xs text-gray-600 bg-gray-50 p-3 rounded-lg overflow-x-auto whitespace-pre-wrap max-h-[200px] overflow-y-auto">
{config.prompt}
</pre>
</CardContent>
</Card>
))}
</div>
</TabsContent>
<TabsContent value="review" className="mt-4">
<Card className="bg-white/80 backdrop-blur border-0 shadow-sm">
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<CardTitle className="text-base font-semibold"> {pendingReviews.length} </CardTitle>
<div className="flex items-center gap-2">
{selectedItems.length > 0 && (
<>
<span className="text-sm text-gray-500"> {selectedItems.length} </span>
<Button size="sm" onClick={handleBatchApprove}>
<ThumbsUp className="h-4 w-4 mr-1" />
</Button>
<Button size="sm" variant="outline" onClick={handleBatchReject}>
<ThumbsDown className="h-4 w-4 mr-1" />
</Button>
</>
)}
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-3">
{pendingReviews.map((item) => (
<div
key={item.id}
className={`flex items-center justify-between p-4 rounded-lg border transition-colors ${
selectedItems.includes(item.id) ? "bg-blue-50 border-blue-200" : "bg-gray-50 border-transparent"
}`}
>
<div className="flex items-center gap-4">
<Checkbox
checked={selectedItems.includes(item.id)}
onCheckedChange={(checked) => {
if (checked) {
setSelectedItems([...selectedItems, item.id])
} else {
setSelectedItems(selectedItems.filter((id) => id !== item.id))
}
}}
/>
<div>
<div className="flex items-center gap-2">
<span className="font-medium text-gray-900">{item.userName}</span>
<span className="text-sm text-gray-500">({item.userId})</span>
</div>
<div className="flex items-center gap-2 mt-1">
<span className="text-sm text-gray-500"></span>
{item.currentTags.map((tag, index) => (
<Badge key={index} variant="secondary" className="text-xs">
{tag}
</Badge>
))}
<span className="text-gray-400"></span>
<Badge className="bg-yellow-100 text-yellow-700 text-xs">
+ {item.newTag}
</Badge>
</div>
<p className="text-xs text-gray-400 mt-1">{item.reason}</p>
</div>
</div>
<div className="flex items-center gap-4">
<div className="text-right">
<p className="text-sm text-gray-500"></p>
<p className={`font-semibold ${getConfidenceColor(item.confidence)}`}>
{(item.confidence * 100).toFixed(0)}%
</p>
</div>
<div className="flex items-center gap-2">
<Button size="sm" variant="outline" className="text-green-600 border-green-200 hover:bg-green-50 bg-transparent">
<ThumbsUp className="h-4 w-4" />
</Button>
<Button size="sm" variant="outline" className="text-red-600 border-red-200 hover:bg-red-50 bg-transparent">
<ThumbsDown className="h-4 w-4" />
</Button>
</div>
</div>
</div>
))}
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="history" className="mt-4">
<Card className="bg-white/80 backdrop-blur border-0 shadow-sm">
<CardContent className="p-6 text-center text-gray-500">
</CardContent>
</Card>
</TabsContent>
</Tabs>
{/* 建任务弹窗 */}
{/* 建任务弹窗 */}
<Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>AI打标任务</DialogTitle>
<DialogDescription>AI打标规则AI将自动识别符合条件的用户并打标签</DialogDescription>
<DialogTitle>AI打标任务</DialogTitle>
<DialogDescription></DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label></Label>
<Input placeholder="例如:高价值用户识别" />
</div>
<div className="space-y-2">
<Label>AI提示词</Label>
<Textarea
placeholder="描述你希望AI如何识别用户例如根据用户的消费金额、频次、最近活跃时间识别高价值用户"
rows={4}
/>
<p className="text-xs text-gray-400">
AI将自动分析数据并打标签
</p>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label></Label>
<Select>
<SelectTrigger>
<SelectValue placeholder="选择或创建标签" />
</SelectTrigger>
<SelectContent>
<SelectItem value="high-value"></SelectItem>
<SelectItem value="churn-risk"></SelectItem>
<SelectItem value="new-user"></SelectItem>
<SelectItem value="vip">VIP用户</SelectItem>
<SelectItem value="custom">...</SelectItem>
</SelectContent>
</Select>
<Label></Label>
<Input placeholder="例如:高价值用户打标" />
</div>
<div className="space-y-2">
<Label></Label>
<Select>
<SelectTrigger>
<SelectValue placeholder="选择数据" />
<SelectValue placeholder="选择数据" />
</SelectTrigger>
<SelectContent>
<SelectItem value="users"></SelectItem>
<SelectItem value="transactions"></SelectItem>
<SelectItem value="behaviors"></SelectItem>
<SelectItem value="all"></SelectItem>
<SelectItem value="kr_tencent">KR_腾讯.qq_phone</SelectItem>
<SelectItem value="kr_weibo">KR_微博.users</SelectItem>
<SelectItem value="kr_jd">KR_京东.users</SelectItem>
<SelectItem value="ckb">cunkebao_v3.users</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label></Label>
<div className="flex items-center gap-4">
<Input type="number" defaultValue="0.7" min="0" max="1" step="0.1" className="w-24" />
<span className="text-sm text-gray-500"></span>
</div>
<Label></Label>
<Select value={selectedPromptType} onValueChange={(v) => setSelectedPromptType(v as keyof typeof DEFAULT_PROMPTS)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{Object.entries(DEFAULT_PROMPTS).map(([key, config]) => (
<SelectItem key={key} value={key}>{config.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex items-center gap-2">
<Checkbox id="auto-approve" />
<Label htmlFor="auto-approve" className="text-sm font-normal">
90%
</Label>
<div className="space-y-2">
<Label> <span className="text-gray-400 text-xs">()</span></Label>
<Textarea
value={DEFAULT_PROMPTS[selectedPromptType].prompt}
rows={10}
className="font-mono text-sm"
/>
</div>
<div className="space-y-2">
<Label> <span className="text-gray-400 text-xs">()</span></Label>
<Input placeholder="高价值用户, 优质用户, 普通用户" />
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowCreateDialog(false)}>
</Button>
<Button variant="outline" onClick={() => setShowCreateDialog(false)}></Button>
<Button onClick={() => setShowCreateDialog(false)}>
<Zap className="h-4 w-4 mr-2" />
<Sparkles className="h-4 w-4 mr-2" />
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 审核弹窗 */}
<Dialog open={showReviewDialog} onOpenChange={setShowReviewDialog}>
<DialogContent className="max-w-4xl max-h-[80vh]">
{/* 编辑提示词弹窗 */}
<Dialog open={showPromptDialog} onOpenChange={setShowPromptDialog}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle> - {selectedTask?.name}</DialogTitle>
<DialogDescription>
{selectedTask?.affectedCount.toLocaleString()} AI打标结果
</DialogDescription>
<DialogTitle></DialogTitle>
<DialogDescription>{selectedTask?.name}</DialogDescription>
</DialogHeader>
<div className="py-4 max-h-96 overflow-y-auto">
<div className="space-y-3">
{pendingReviews.map((item) => (
<div key={item.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
<div>
<span className="font-medium">{item.userName}</span>
<span className="text-gray-500 ml-2">({item.userId})</span>
<p className="text-sm text-gray-500 mt-1">{item.reason}</p>
</div>
<div className="flex items-center gap-3">
<span className={getConfidenceColor(item.confidence)}>
{(item.confidence * 100).toFixed(0)}%
</span>
<Button size="sm" variant="outline" className="text-green-600 bg-transparent">
<ThumbsUp className="h-4 w-4" />
</Button>
<Button size="sm" variant="outline" className="text-red-600 bg-transparent">
<ThumbsDown className="h-4 w-4" />
</Button>
</div>
</div>
))}
<div className="space-y-4 py-4">
<div className="p-3 rounded-lg bg-blue-50 text-sm text-blue-700">
💡 使 <code className="bg-blue-100 px-1 rounded">{'{user_data}'}</code>
</div>
<Textarea
value={editingPrompt}
onChange={(e) => setEditingPrompt(e.target.value)}
rows={15}
className="font-mono text-sm"
/>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowReviewDialog(false)}>
<Button variant="outline" onClick={() => setShowPromptDialog(false)}></Button>
<Button onClick={savePrompt}>
<CheckCircle2 className="h-4 w-4 mr-2" />
</Button>
<Button variant="outline"></Button>
<Button></Button>
</DialogFooter>
</DialogContent>
</Dialog>