0.0.1.2
This commit is contained in:
@@ -5,57 +5,116 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { History, Trash2, RefreshCw, User, FileText, Image, Settings } from "lucide-react"
|
||||
import { getActivityLogs, cleanOldLogs, getActivityStats } from "@/lib/activity-logger"
|
||||
import type { ActivityLog } from "@/lib/db"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { History, Trash2, RefreshCw, User, FileText, Image, Settings, Globe, Filter } from "lucide-react"
|
||||
import { format } from "date-fns"
|
||||
import { useFamily } from "@/context/family-context"
|
||||
import { useSession } from "next-auth/react"
|
||||
import { useDialog } from "@/components/ui/alert-dialog-custom"
|
||||
|
||||
const actionLabels = {
|
||||
create: "创建",
|
||||
update: "更新",
|
||||
delete: "删除",
|
||||
import: "导入",
|
||||
export: "导出",
|
||||
// 定义日志类型
|
||||
interface ActivityLog {
|
||||
id: string
|
||||
action: "CREATE" | "UPDATE" | "DELETE" | "IMPORT" | "EXPORT"
|
||||
entityType: "MEMBER" | "PHOTO" | "STORY" | "SETTINGS"
|
||||
entityId?: string | null
|
||||
entityName?: string | null
|
||||
changes?: any
|
||||
timestamp: string
|
||||
userId: string
|
||||
user?: {
|
||||
name?: string | null
|
||||
email?: string | null
|
||||
}
|
||||
tree?: {
|
||||
name: string
|
||||
}
|
||||
}
|
||||
|
||||
const actionColors = {
|
||||
create: "bg-green-500",
|
||||
update: "bg-blue-500",
|
||||
delete: "bg-red-500",
|
||||
import: "bg-purple-500",
|
||||
export: "bg-orange-500",
|
||||
const actionLabels: Record<string, string> = {
|
||||
CREATE: "创建",
|
||||
UPDATE: "更新",
|
||||
DELETE: "删除",
|
||||
IMPORT: "导入",
|
||||
EXPORT: "导出",
|
||||
}
|
||||
|
||||
const entityTypeLabels = {
|
||||
member: "成员",
|
||||
photo: "照片",
|
||||
story: "故事",
|
||||
settings: "设置",
|
||||
const actionColors: Record<string, string> = {
|
||||
CREATE: "bg-green-500",
|
||||
UPDATE: "bg-blue-500",
|
||||
DELETE: "bg-red-500",
|
||||
IMPORT: "bg-purple-500",
|
||||
EXPORT: "bg-orange-500",
|
||||
}
|
||||
|
||||
const entityTypeIcons = {
|
||||
member: User,
|
||||
photo: Image,
|
||||
story: FileText,
|
||||
settings: Settings,
|
||||
const entityTypeLabels: Record<string, string> = {
|
||||
MEMBER: "成员",
|
||||
PHOTO: "照片",
|
||||
STORY: "故事",
|
||||
SETTINGS: "设置",
|
||||
}
|
||||
|
||||
const entityTypeIcons: Record<string, any> = {
|
||||
MEMBER: User,
|
||||
PHOTO: Image,
|
||||
STORY: FileText,
|
||||
SETTINGS: Settings,
|
||||
}
|
||||
|
||||
interface FamilyTree {
|
||||
id: string
|
||||
name: string
|
||||
ownerId: string
|
||||
currentUserRole?: "OWNER" | "EDITOR" | "VIEWER"
|
||||
}
|
||||
|
||||
export function ActivityLogViewer() {
|
||||
const { currentTree } = useFamily()
|
||||
const { data: session } = useSession()
|
||||
const { showAlert, showConfirm, showPrompt } = useDialog()
|
||||
const [logs, setLogs] = useState<ActivityLog[]>([])
|
||||
const [stats, setStats] = useState<any>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [trees, setTrees] = useState<FamilyTree[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [filterTreeId, setFilterTreeId] = useState<string>("all")
|
||||
const [clearing, setClearing] = useState(false)
|
||||
|
||||
// 加载家族树列表
|
||||
useEffect(() => {
|
||||
fetch('/api/trees')
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data.trees) {
|
||||
setTrees(data.trees)
|
||||
}
|
||||
})
|
||||
.catch(err => console.error("加载家族树列表失败:", err))
|
||||
}, [])
|
||||
|
||||
// 当 currentTree 改变时,更新筛选
|
||||
useEffect(() => {
|
||||
if (currentTree?.id) {
|
||||
setFilterTreeId(currentTree.id)
|
||||
}
|
||||
}, [currentTree?.id])
|
||||
|
||||
const loadLogs = async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const [activityLogs, activityStats] = await Promise.all([
|
||||
getActivityLogs(100),
|
||||
getActivityStats()
|
||||
])
|
||||
setLogs(activityLogs)
|
||||
setStats(activityStats)
|
||||
let url = ""
|
||||
|
||||
if (filterTreeId === "all") {
|
||||
url = `/api/user/activity-logs?limit=100`
|
||||
} else {
|
||||
url = `/api/trees/${filterTreeId}/activity-logs?limit=100`
|
||||
}
|
||||
|
||||
const res = await fetch(url)
|
||||
if (!res.ok) throw new Error("获取日志失败")
|
||||
|
||||
const data = await res.json()
|
||||
setLogs(data.logs || [])
|
||||
} catch (err) {
|
||||
console.error("加载日志失败:", err)
|
||||
setError(err instanceof Error ? err.message : "加载失败")
|
||||
@@ -66,13 +125,70 @@ export function ActivityLogViewer() {
|
||||
|
||||
useEffect(() => {
|
||||
loadLogs()
|
||||
}, [])
|
||||
}, [filterTreeId])
|
||||
|
||||
const handleCleanOldLogs = async () => {
|
||||
if (confirm("确定要清除90天前的日志吗?")) {
|
||||
const count = await cleanOldLogs(90)
|
||||
alert(`已清除 ${count} 条旧日志`)
|
||||
loadLogs()
|
||||
// 检查当前用户是否是选中家族树的所有者
|
||||
const isOwner = () => {
|
||||
if (filterTreeId === "all") return false
|
||||
const selectedTree = trees.find(t => t.id === filterTreeId)
|
||||
if (!selectedTree) return false
|
||||
|
||||
// 检查是否是所有者
|
||||
return selectedTree.ownerId === session?.user?.id || selectedTree.currentUserRole === "OWNER"
|
||||
}
|
||||
|
||||
const handleClearLogs = async () => {
|
||||
if (filterTreeId === "all") {
|
||||
await showAlert("请先选择一个具体的家族树再清空日志", "提示")
|
||||
return
|
||||
}
|
||||
|
||||
const selectedTree = trees.find(t => t.id === filterTreeId)
|
||||
if (!selectedTree) {
|
||||
await showAlert("未找到选中的家族树", "错误")
|
||||
return
|
||||
}
|
||||
|
||||
// 第一次确认
|
||||
const confirmMessage = `⚠️ 警告:即将清空"${selectedTree.name}"的所有操作日志!\n\n此操作将永久删除该家族树的所有历史记录,且不可恢复。\n\n确定要继续吗?`
|
||||
const confirmed = await showConfirm(confirmMessage, "清空操作日志", "destructive")
|
||||
if (!confirmed) {
|
||||
return
|
||||
}
|
||||
|
||||
// 第二次确认
|
||||
const finalConfirm = await showPrompt(
|
||||
`请输入家族树名称"${selectedTree.name}"以确认清空操作:\n\n(此操作不可撤销)`,
|
||||
"",
|
||||
"确认清空"
|
||||
)
|
||||
|
||||
if (finalConfirm !== selectedTree.name) {
|
||||
await showAlert("名称不匹配,操作已取消", "操作已取消")
|
||||
return
|
||||
}
|
||||
|
||||
setClearing(true)
|
||||
try {
|
||||
const res = await fetch(`/api/trees/${filterTreeId}/activity-logs`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json()
|
||||
throw new Error(error.error || "清空失败")
|
||||
}
|
||||
|
||||
const data = await res.json()
|
||||
await showAlert(data.message || "操作日志已清空", "成功")
|
||||
|
||||
// 重新加载日志
|
||||
await loadLogs()
|
||||
} catch (err) {
|
||||
console.error("清空日志失败:", err)
|
||||
await showAlert("清空失败:" + (err instanceof Error ? err.message : "未知错误"), "错误")
|
||||
} finally {
|
||||
setClearing(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,61 +196,68 @@ export function ActivityLogViewer() {
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<History className="h-5 w-5" />
|
||||
操作日志
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
查看所有修谱操作记录
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{stats && (
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
|
||||
<div className="bg-muted p-4 rounded-lg">
|
||||
<p className="text-sm text-muted-foreground">总记录数</p>
|
||||
<p className="text-2xl font-bold">{stats.total}</p>
|
||||
</div>
|
||||
<div className="bg-muted p-4 rounded-lg">
|
||||
<p className="text-sm text-muted-foreground">24小时内</p>
|
||||
<p className="text-2xl font-bold">{stats.recentCount}</p>
|
||||
</div>
|
||||
<div className="bg-muted p-4 rounded-lg">
|
||||
<p className="text-sm text-muted-foreground">创建操作</p>
|
||||
<p className="text-2xl font-bold">{stats.byAction.create || 0}</p>
|
||||
</div>
|
||||
<div className="bg-muted p-4 rounded-lg">
|
||||
<p className="text-sm text-muted-foreground">更新操作</p>
|
||||
<p className="text-2xl font-bold">{stats.byAction.update || 0}</p>
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
|
||||
<div>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<History className="h-5 w-5" />
|
||||
操作日志
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
查看家族树的变更记录
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={loadLogs}
|
||||
disabled={loading || clearing}
|
||||
className="h-9 w-9"
|
||||
title="刷新日志"
|
||||
>
|
||||
<RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
</Button>
|
||||
{isOwner() && (
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={handleClearLogs}
|
||||
disabled={loading || clearing}
|
||||
className="gap-2"
|
||||
title="清空当前家族树的操作日志(仅所有者可用)"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
{clearing ? "清空中..." : "清空日志"}
|
||||
</Button>
|
||||
)}
|
||||
<div className="w-[200px]">
|
||||
<Select value={filterTreeId} onValueChange={setFilterTreeId}>
|
||||
<SelectTrigger>
|
||||
<div className="flex items-center gap-2">
|
||||
<Filter className="h-4 w-4 text-muted-foreground" />
|
||||
<SelectValue placeholder="筛选家族树" />
|
||||
</div>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">所有家族树</SelectItem>
|
||||
{trees.map(tree => (
|
||||
<SelectItem key={tree.id} value={tree.id}>
|
||||
{tree.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2 mb-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={loadLogs}
|
||||
>
|
||||
<RefreshCw className="mr-2 h-4 w-4" />
|
||||
刷新
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleCleanOldLogs}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
清除旧日志
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ScrollArea className="h-[400px] pr-4">
|
||||
{error ? (
|
||||
<div className="text-center py-8 text-destructive">
|
||||
加载失败: {error}
|
||||
</div>
|
||||
) : loading ? (
|
||||
) : loading && logs.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
加载中...
|
||||
</div>
|
||||
@@ -145,7 +268,7 @@ export function ActivityLogViewer() {
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{logs.map((log) => {
|
||||
const EntityIcon = entityTypeIcons[log.entityType]
|
||||
const EntityIcon = entityTypeIcons[log.entityType] || FileText
|
||||
return (
|
||||
<div
|
||||
key={log.id}
|
||||
@@ -155,13 +278,18 @@ export function ActivityLogViewer() {
|
||||
<EntityIcon className={`h-4 w-4 ${actionColors[log.action].replace('bg-', 'text-')}`} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<div className="flex items-center gap-2 mb-1 flex-wrap">
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{actionLabels[log.action]}
|
||||
{actionLabels[log.action] || log.action}
|
||||
</Badge>
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{entityTypeLabels[log.entityType]}
|
||||
{entityTypeLabels[log.entityType] || log.entityType}
|
||||
</Badge>
|
||||
{filterTreeId === "all" && log.tree && (
|
||||
<Badge variant="outline" className="text-xs bg-blue-50 text-blue-700 border-blue-200">
|
||||
{log.tree.name}
|
||||
</Badge>
|
||||
)}
|
||||
{log.entityName && (
|
||||
<span className="text-sm font-medium truncate">
|
||||
{log.entityName}
|
||||
@@ -170,7 +298,7 @@ export function ActivityLogViewer() {
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{log.userName || "系统"}
|
||||
{log.user?.name || log.user?.email || "未知用户"}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{format(new Date(log.timestamp), "yyyy-MM-dd HH:mm:ss")}
|
||||
@@ -198,3 +326,4 @@ export function ActivityLogViewer() {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user