This commit is contained in:
freedakgmail
2025-11-23 09:13:25 +08:00
parent 81dbf709aa
commit bade25ff26
378 changed files with 769815 additions and 2334 deletions
+220 -91
View File
@@ -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>
)
}
@@ -0,0 +1,253 @@
"use client"
import { useState, useEffect } from "react"
import { useSession } from "next-auth/react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Users, Mail, Trash2, Plus, Shield, Eye, Edit } from "lucide-react"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { useFamily } from "@/context/family-context"
import { useDialog } from "@/components/ui/alert-dialog-custom"
interface Collaborator {
id: string
userId: string
role: "EDITOR" | "VIEWER"
invitedAt: string
user: {
id: string
name: string | null
email: string
avatar: string | null
}
}
export function CollaboratorManager() {
const { data: session } = useSession()
const { currentTree } = useFamily()
const { showConfirm, showAlert } = useDialog()
const [collaborators, setCollaborators] = useState<Collaborator[]>([])
const [isLoading, setIsLoading] = useState(false)
const [isInviting, setIsInviting] = useState(false)
const [email, setEmail] = useState("")
const [role, setRole] = useState<"EDITOR" | "VIEWER">("VIEWER")
const [password, setPassword] = useState("")
const [error, setError] = useState("")
const [success, setSuccess] = useState("")
// 加载协作者
useEffect(() => {
if (currentTree?.id) {
loadCollaborators()
}
}, [currentTree?.id])
const loadCollaborators = async () => {
if (!currentTree?.id) return
try {
const res = await fetch(`/api/trees/${currentTree.id}/collaborators`)
if (res.ok) {
const data = await res.json()
setCollaborators(data.collaborators)
}
} catch (err) {
console.error("加载协作者失败:", err)
}
}
const handleInvite = async (e: React.FormEvent) => {
e.preventDefault()
if (!currentTree?.id) return
setIsInviting(true)
setError("")
setSuccess("")
try {
const res = await fetch(`/api/trees/${currentTree.id}/invite`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email,
role,
password: password || undefined, // 只有填写了才发送
}),
})
const data = await res.json()
if (!res.ok) {
throw new Error(data.error || "邀请失败")
}
setSuccess(data.message)
setEmail("")
setPassword("")
loadCollaborators()
} catch (err: any) {
setError(err.message)
} finally {
setIsInviting(false)
}
}
const handleRemove = async (userId: string) => {
if (!currentTree?.id) return
const confirmed = await showConfirm("确定要移除此协作者吗?", "移除协作者")
if (!confirmed) return
try {
const res = await fetch(`/api/trees/${currentTree.id}/collaborators?userId=${userId}`, {
method: 'DELETE',
})
if (!res.ok) throw new Error('移除失败')
loadCollaborators()
} catch (err) {
console.error(err)
await showAlert("移除失败", "错误")
}
}
if (!currentTree) return null
// 只有所有者可以看到此组件
if (currentTree.ownerId !== session?.user?.id) return null
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Users className="h-5 w-5" />
</CardTitle>
<CardDescription>
"{currentTree.name}"
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{/* 邀请表单 */}
<form onSubmit={handleInvite} className="space-y-4 border-b pb-6">
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
<div className="space-y-2">
<Label htmlFor="email"></Label>
<Input
id="email"
type="email"
placeholder="输入对方邮箱"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="role"></Label>
<Select value={role} onValueChange={(v: any) => setRole(v)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="EDITOR">
<div className="flex items-center">
<Edit className="mr-2 h-4 w-4" />
()
</div>
</SelectItem>
<SelectItem value="VIEWER">
<div className="flex items-center">
<Eye className="mr-2 h-4 w-4" />
()
</div>
</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="password"> ()</Label>
<Input
id="password"
type="text"
placeholder="为新用户设置密码"
value={password}
onChange={(e) => setPassword(e.target.value)}
minLength={6}
/>
</div>
</div>
{error && (
<Alert variant="destructive">
<AlertTitle></AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{success && (
<Alert className="bg-green-50 text-green-700 border-green-200">
<AlertTitle></AlertTitle>
<AlertDescription>{success}</AlertDescription>
</Alert>
)}
<Button type="submit" disabled={isInviting}>
{isInviting ? "处理中..." : "发送邀请"}
</Button>
</form>
{/* 协作者列表 */}
<div className="space-y-4">
<h3 className="font-medium"></h3>
{collaborators.length === 0 ? (
<p className="text-sm text-muted-foreground"></p>
) : (
<div className="space-y-3">
{collaborators.map((collab) => (
<div
key={collab.id}
className="flex items-center justify-between p-3 rounded-lg border bg-muted/50"
>
<div className="flex items-center gap-3">
<Avatar className="h-10 w-10 border border-border">
<AvatarFallback>
{collab.user.name?.charAt(0).toUpperCase() || collab.user.email.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<div>
<div className="font-medium">{collab.user.name || "用户"}</div>
<div className="text-sm text-muted-foreground">{collab.user.email}</div>
</div>
</div>
<div className="flex items-center gap-4">
<span className={`text-xs px-2 py-1 rounded-full border ${
collab.role === 'EDITOR'
? 'bg-blue-100 text-blue-700 border-blue-200'
: 'bg-gray-100 text-gray-700 border-gray-200'
}`}>
{collab.role === 'EDITOR' ? '编辑者' : '查看者'}
</span>
<Button
variant="ghost"
size="icon"
className="text-muted-foreground hover:text-destructive"
onClick={() => handleRemove(collab.userId)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
))}
</div>
)}
</div>
</CardContent>
</Card>
)
}
@@ -1,16 +1,18 @@
"use client"
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"
import { Bell, BellOff, Check, X } from "lucide-react"
import { Bell, BellOff, X, Check } from "lucide-react"
import { useDialog } from "@/components/ui/alert-dialog-custom"
import { requestNotificationPermission, checkUpcomingAnniversaries } from "@/lib/notifications"
import { useFamily } from "@/context/family-context"
import { Alert, AlertDescription } from "@/components/ui/alert"
export function NotificationSettings() {
const { showAlert } = useDialog()
const { treeData } = useFamily()
const [notificationEnabled, setNotificationEnabled] = useState(false)
const [permission, setPermission] = useState<NotificationPermission>("default")
@@ -52,9 +54,9 @@ export function NotificationSettings() {
}
}
const handleDisableNotifications = () => {
const handleDisableNotifications = async () => {
setNotificationEnabled(false)
alert("请在浏览器设置中禁用此网站的通知权限")
await showAlert("请在浏览器设置中禁用此网站的通知权限", "提示")
}
return (