0.0.1.2
This commit is contained in:
@@ -28,9 +28,18 @@ export function FamilyTreesList() {
|
||||
|
||||
useEffect(() => {
|
||||
if (session?.user?.id) {
|
||||
console.log('📋 开始获取家族树列表...')
|
||||
fetch('/api/trees')
|
||||
.then(res => res.json())
|
||||
.then(res => {
|
||||
console.log('📋 家族树列表响应状态:', res.status)
|
||||
return res.json()
|
||||
})
|
||||
.then(data => {
|
||||
console.log('📋 家族树列表数据:', {
|
||||
data,
|
||||
treesCount: data.trees?.length,
|
||||
trees: data.trees
|
||||
})
|
||||
if (data.trees) {
|
||||
setTrees(data.trees)
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ export function MemberForm({ initialData, existingMembers = [], onSubmit, onCanc
|
||||
surname: initialData?.surname || "李",
|
||||
givenName: initialData?.givenName || "",
|
||||
fullName: initialData?.fullName || "",
|
||||
gender: initialData?.gender || "male",
|
||||
gender: (initialData?.gender || "MALE").toUpperCase() as "MALE" | "FEMALE",
|
||||
generation: initialData?.generation || maxGeneration,
|
||||
spouseIds: initialData?.spouseIds || [],
|
||||
childrenIds: initialData?.childrenIds || [],
|
||||
@@ -247,8 +247,8 @@ export function MemberForm({ initialData, existingMembers = [], onSubmit, onCanc
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="male">男 (Male)</SelectItem>
|
||||
<SelectItem value="female">女 (Female)</SelectItem>
|
||||
<SelectItem value="MALE">男 (Male)</SelectItem>
|
||||
<SelectItem value="FEMALE">女 (Female)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
@@ -287,7 +287,7 @@ export function MemberForm({ initialData, existingMembers = [], onSubmit, onCanc
|
||||
<SelectContent>
|
||||
<SelectItem value="none">无 (None)</SelectItem>
|
||||
{potentialRelatives
|
||||
.filter((m) => m.gender === "male" && m.generation === (formData.generation || 1) - 1)
|
||||
.filter((m) => m.gender === "MALE" && m.generation === (formData.generation || 1) - 1)
|
||||
.map((m) => (
|
||||
<SelectItem key={m.id} value={m.id}>
|
||||
{m.fullName} ({m.generation}世)
|
||||
@@ -319,7 +319,7 @@ export function MemberForm({ initialData, existingMembers = [], onSubmit, onCanc
|
||||
<SelectContent>
|
||||
<SelectItem value="none">无 (None)</SelectItem>
|
||||
{potentialRelatives
|
||||
.filter((m) => m.gender === "female" && m.generation === (formData.generation || 1) - 1)
|
||||
.filter((m) => m.gender === "FEMALE" && m.generation === (formData.generation || 1) - 1)
|
||||
.map((m) => (
|
||||
<SelectItem key={m.id} value={m.id}>
|
||||
{m.fullName} ({m.generation}世)
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
import { useState, useEffect } from "react"
|
||||
import { db } from "@/lib/db"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { X, Plus, ZoomIn } from "lucide-react"
|
||||
import { Card } from "@/components/ui/card"
|
||||
import { X, Upload, Image as ImageIcon } from "lucide-react"
|
||||
import { uploadImage } from "@/lib/image-upload"
|
||||
import { useDialog } from "@/components/ui/alert-dialog-custom"
|
||||
import { v4 as uuidv4 } from "uuid"
|
||||
import imageCompression from "browser-image-compression"
|
||||
|
||||
@@ -15,6 +17,7 @@ interface PhotoGalleryProps {
|
||||
}
|
||||
|
||||
export function PhotoGallery({ photoIds = [], onChange, readonly = false }: PhotoGalleryProps) {
|
||||
const { showAlert, showConfirm } = useDialog()
|
||||
const [photos, setPhotos] = useState<{ id: string; url: string }[]>([])
|
||||
const [selectedPhoto, setSelectedPhoto] = useState<string | null>(null)
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
@@ -85,15 +88,16 @@ export function PhotoGallery({ photoIds = [], onChange, readonly = false }: Phot
|
||||
onChange([...photoIds, ...newPhotoIds])
|
||||
} catch (error) {
|
||||
console.error('上传照片失败:', error)
|
||||
alert('上传照片失败')
|
||||
await showAlert('上传照片失败', '错误')
|
||||
} finally {
|
||||
setIsUploading(false)
|
||||
e.target.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = (photoId: string) => {
|
||||
if (confirm('确定要删除这张照片吗?')) {
|
||||
const handleDelete = async (photoId: string) => {
|
||||
const confirmed = await showConfirm('确定要删除这张照片吗?', '删除照片')
|
||||
if (confirmed) {
|
||||
onChange(photoIds.filter(id => id !== photoId))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,10 +6,10 @@ import { Input } from "@/components/ui/input"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
|
||||
import { Plus, Edit, Trash, BookOpen, Calendar } from "lucide-react"
|
||||
import type { FamilyStory } from "@/types/family"
|
||||
import { v4 as uuidv4 } from "uuid"
|
||||
import { useDialog } from "@/components/ui/alert-dialog-custom"
|
||||
|
||||
interface StoryManagerProps {
|
||||
stories?: FamilyStory[]
|
||||
@@ -18,7 +18,8 @@ interface StoryManagerProps {
|
||||
}
|
||||
|
||||
export function StoryManager({ stories = [], onChange, readonly = false }: StoryManagerProps) {
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false)
|
||||
const { showAlert, showConfirm } = useDialog()
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
const [editingStory, setEditingStory] = useState<FamilyStory | null>(null)
|
||||
const [formData, setFormData] = useState<Partial<FamilyStory>>({
|
||||
title: "",
|
||||
@@ -38,15 +39,16 @@ export function StoryManager({ stories = [], onChange, readonly = false }: Story
|
||||
setIsDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleDelete = (storyId: string) => {
|
||||
if (confirm("确定要删除这个故事吗?")) {
|
||||
const handleDelete = async (storyId: string) => {
|
||||
const confirmed = await showConfirm("确定要删除这个故事吗?", "删除故事")
|
||||
if (confirmed) {
|
||||
onChange(stories.filter(s => s.id !== storyId))
|
||||
}
|
||||
}
|
||||
|
||||
const handleSave = () => {
|
||||
const handleSave = async () => {
|
||||
if (!formData.title || !formData.content) {
|
||||
alert("请填写标题和内容")
|
||||
await showAlert("请填写标题和内容", "提示")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -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 (
|
||||
|
||||
+87
-41
@@ -17,17 +17,20 @@ import { useFamily } from "@/context/family-context"
|
||||
import { useState, useRef, useEffect, useCallback } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useSession, signOut } from "next-auth/react"
|
||||
import { useDialog } from "@/components/ui/alert-dialog-custom"
|
||||
|
||||
interface FamilyTree {
|
||||
id: string
|
||||
name: string
|
||||
description: string | null
|
||||
ownerId: string
|
||||
currentUserRole?: "OWNER" | "EDITOR" | "VIEWER"
|
||||
}
|
||||
|
||||
export function SiteHeader() {
|
||||
const { searchMembers, searchResults } = useFamily()
|
||||
const { data: session, status } = useSession()
|
||||
const { showAlert, showConfirm, showPrompt } = useDialog()
|
||||
const [searchQuery, setSearchQuery] = useState("")
|
||||
const [showResults, setShowResults] = useState(false)
|
||||
const [familyTrees, setFamilyTrees] = useState<FamilyTree[]>([])
|
||||
@@ -36,6 +39,27 @@ export function SiteHeader() {
|
||||
const searchRef = useRef<HTMLDivElement>(null)
|
||||
const router = useRouter()
|
||||
|
||||
// 生成带有 treeId 的 URL
|
||||
const getUrlWithTreeId = (path: string) => {
|
||||
if (currentTree?.id) {
|
||||
return `${path}?treeId=${currentTree.id}`
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
const getRoleBadge = (role?: string) => {
|
||||
switch (role) {
|
||||
case "OWNER":
|
||||
return <span className="text-[10px] px-1.5 py-0.5 rounded bg-purple-100 text-purple-700 border border-purple-200 ml-2">所有者</span>
|
||||
case "EDITOR":
|
||||
return <span className="text-[10px] px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 ml-2">编辑</span>
|
||||
case "VIEWER":
|
||||
return <span className="text-[10px] px-1.5 py-0.5 rounded bg-gray-100 text-gray-700 border border-gray-200 ml-2">查看</span>
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const handleSignOut = async () => {
|
||||
await signOut({ callbackUrl: "/auth/signin" })
|
||||
}
|
||||
@@ -57,19 +81,24 @@ export function SiteHeader() {
|
||||
|
||||
// 检查权限
|
||||
if (tree.ownerId !== session?.user?.id) {
|
||||
alert('只有家族树的创建者才能删除')
|
||||
await showAlert('只有家族树的创建者才能删除', '权限不足')
|
||||
return
|
||||
}
|
||||
|
||||
const confirmText = `确定要删除家族树"${tree.name}"吗?\n\n此操作将永久删除所有成员、活动日志和协作者数据,且不可撤销!`
|
||||
if (!confirm(confirmText)) {
|
||||
const confirmed = await showConfirm(confirmText, '删除家族树', 'destructive')
|
||||
if (!confirmed) {
|
||||
return
|
||||
}
|
||||
|
||||
// 二次确认
|
||||
const finalConfirm = prompt(`请输入家族树名称"${tree.name}"以确认删除:`)
|
||||
const finalConfirm = await showPrompt(
|
||||
`请输入家族树名称"${tree.name}"以确认删除:`,
|
||||
'',
|
||||
'确认删除'
|
||||
)
|
||||
if (finalConfirm !== tree.name) {
|
||||
alert('名称不匹配,删除已取消')
|
||||
await showAlert('名称不匹配,删除已取消', '操作已取消')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -93,7 +122,7 @@ export function SiteHeader() {
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('删除家族树失败:', error)
|
||||
alert('删除失败:' + (error as Error).message)
|
||||
await showAlert('删除失败:' + (error as Error).message, '错误')
|
||||
} finally {
|
||||
setDeletingTreeId(null)
|
||||
}
|
||||
@@ -101,37 +130,49 @@ export function SiteHeader() {
|
||||
|
||||
// 获取家族树列表
|
||||
const loadFamilyTrees = useCallback(() => {
|
||||
if (session?.user?.id) {
|
||||
fetch('/api/trees')
|
||||
.then(res => {
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}`)
|
||||
}
|
||||
return res.json()
|
||||
})
|
||||
.then(data => {
|
||||
if (data.trees) {
|
||||
setFamilyTrees(data.trees)
|
||||
// 如果 URL 中有 treeId,使用该树,否则使用第一个
|
||||
const urlParams = new URLSearchParams(window.location.search)
|
||||
const treeId = urlParams.get('treeId')
|
||||
if (treeId) {
|
||||
const tree = data.trees.find((t: FamilyTree) => t.id === treeId)
|
||||
if (tree) {
|
||||
setCurrentTree(tree)
|
||||
} else if (data.trees.length > 0) {
|
||||
setCurrentTree(data.trees[0])
|
||||
}
|
||||
// 只在 session 加载完成且用户已登录时才获取
|
||||
if (status === 'loading') {
|
||||
return
|
||||
}
|
||||
|
||||
if (!session?.user?.id) {
|
||||
setFamilyTrees([])
|
||||
setCurrentTree(null)
|
||||
return
|
||||
}
|
||||
|
||||
fetch('/api/trees')
|
||||
.then(res => {
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}`)
|
||||
}
|
||||
return res.json()
|
||||
})
|
||||
.then(data => {
|
||||
if (data.trees) {
|
||||
setFamilyTrees(data.trees)
|
||||
// 如果 URL 中有 treeId,使用该树,否则使用第一个
|
||||
const urlParams = new URLSearchParams(window.location.search)
|
||||
const treeId = urlParams.get('treeId')
|
||||
if (treeId) {
|
||||
const tree = data.trees.find((t: FamilyTree) => t.id === treeId)
|
||||
if (tree) {
|
||||
setCurrentTree(tree)
|
||||
} else if (data.trees.length > 0) {
|
||||
setCurrentTree(data.trees[0])
|
||||
}
|
||||
} else if (data.trees.length > 0) {
|
||||
setCurrentTree(data.trees[0])
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
// 只在非 abort 错误时才记录
|
||||
if (err.name !== 'AbortError') {
|
||||
console.error('获取家族树列表失败:', err)
|
||||
})
|
||||
}
|
||||
}, [session?.user?.id])
|
||||
}
|
||||
})
|
||||
}, [session?.user?.id, status])
|
||||
|
||||
useEffect(() => {
|
||||
loadFamilyTrees()
|
||||
@@ -198,11 +239,16 @@ export function SiteHeader() {
|
||||
key={tree.id}
|
||||
onClick={() => {
|
||||
setCurrentTree(tree)
|
||||
router.push(`/?treeId=${tree.id}`)
|
||||
// 保持当前路径,只更新 treeId 参数
|
||||
const currentPath = window.location.pathname
|
||||
router.push(`${currentPath}?treeId=${tree.id}`)
|
||||
}}
|
||||
className="cursor-pointer flex items-center justify-between group"
|
||||
>
|
||||
<span className="flex-1 truncate">{tree.name}</span>
|
||||
<div className="flex items-center overflow-hidden">
|
||||
<span className="truncate">{tree.name}</span>
|
||||
{getRoleBadge(tree.currentUserRole)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{currentTree?.id === tree.id && (
|
||||
<span className="text-primary">✓</span>
|
||||
@@ -236,18 +282,18 @@ export function SiteHeader() {
|
||||
|
||||
<nav className="hidden md:flex items-center gap-6 text-sm font-medium text-muted-foreground">
|
||||
<Link
|
||||
href="/"
|
||||
href={getUrlWithTreeId("/")}
|
||||
className="transition-colors hover:text-foreground data-[active=true]:text-foreground data-[active=true]:font-semibold"
|
||||
>
|
||||
总览 (Overview)
|
||||
</Link>
|
||||
<Link href="/tree" className="transition-colors hover:text-foreground">
|
||||
<Link href={getUrlWithTreeId("/tree")} className="transition-colors hover:text-foreground">
|
||||
族谱 (Tree)
|
||||
</Link>
|
||||
<Link href="/members" className="transition-colors hover:text-foreground">
|
||||
<Link href={getUrlWithTreeId("/members")} className="transition-colors hover:text-foreground">
|
||||
成员 (Members)
|
||||
</Link>
|
||||
<Link href="/timeline" className="transition-colors hover:text-foreground">
|
||||
<Link href={getUrlWithTreeId("/timeline")} className="transition-colors hover:text-foreground">
|
||||
大事记 (Timeline)
|
||||
</Link>
|
||||
</nav>
|
||||
@@ -276,8 +322,8 @@ export function SiteHeader() {
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">{member.fullName}</span>
|
||||
<span className={`text-xs px-1.5 py-0.5 rounded ${member.gender === "male" ? "bg-blue-100 text-blue-700" : "bg-pink-100 text-pink-700"}`}>
|
||||
{member.gender === "male" ? "男" : "女"}
|
||||
<span className={`text-xs px-1.5 py-0.5 rounded ${member.gender === "MALE" ? "bg-blue-100 text-blue-700" : "bg-pink-100 text-pink-700"}`}>
|
||||
{member.gender === "MALE" ? "男" : "女"}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">第{member.generation}世</span>
|
||||
</div>
|
||||
@@ -338,8 +384,8 @@ export function SiteHeader() {
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/settings" className="cursor-pointer">
|
||||
<User className="mr-2 h-4 w-4" />
|
||||
<span>个人设置</span>
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
<span>系统设置</span>
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { useSession } from "next-auth/react"
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
|
||||
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 CollaboratorDialog() {
|
||||
const { data: session } = useSession()
|
||||
const { currentTree } = useFamily()
|
||||
const { showConfirm, showAlert } = useDialog()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [collaborators, setCollaborators] = useState<Collaborator[]>([])
|
||||
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 (open && currentTree?.id) {
|
||||
loadCollaborators()
|
||||
}
|
||||
}, [open, 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 (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" className="gap-2">
|
||||
<Users className="h-4 w-4" />
|
||||
协作管理
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[600px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>协作管理 - {currentTree.name}</DialogTitle>
|
||||
<DialogDescription>
|
||||
邀请其他用户协作编辑或查看您的家族树。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6 py-4">
|
||||
{/* 邀请表单 */}
|
||||
<form onSubmit={handleInvite} className="space-y-4 border-b pb-6">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<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 sm:col-span-2">
|
||||
<Label htmlFor="password">初始密码 (仅新用户)</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="password"
|
||||
type="text"
|
||||
placeholder="为新用户设置密码(可选)"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
minLength={6}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button type="submit" disabled={isInviting}>
|
||||
{isInviting ? "处理中..." : "发送邀请"}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">如果是现有用户,此密码将被忽略。</p>
|
||||
</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>
|
||||
)}
|
||||
</form>
|
||||
|
||||
{/* 协作者列表 */}
|
||||
<div className="space-y-4">
|
||||
<h3 className="font-medium text-sm text-muted-foreground">现有协作者</h3>
|
||||
{collaborators.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground border border-dashed rounded-lg">
|
||||
暂无协作者
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 max-h-[300px] overflow-y-auto pr-2">
|
||||
{collaborators.map((collab) => (
|
||||
<div
|
||||
key={collab.id}
|
||||
className="flex items-center justify-between p-3 rounded-lg border bg-muted/30"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="h-9 w-9 border border-border">
|
||||
<AvatarFallback>
|
||||
{collab.user.name?.charAt(0).toUpperCase() || collab.user.email.charAt(0).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<div className="font-medium text-sm">{collab.user.name || "用户"}</div>
|
||||
<div className="text-xs text-muted-foreground">{collab.user.email}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className={`text-[10px] px-2 py-0.5 rounded-full border ${
|
||||
collab.role === 'EDITOR'
|
||||
? 'bg-blue-50 text-blue-700 border-blue-200'
|
||||
: 'bg-gray-50 text-gray-700 border-gray-200'
|
||||
}`}>
|
||||
{collab.role === 'EDITOR' ? '编辑者' : '查看者'}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => handleRemove(collab.userId)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
"use client"
|
||||
|
||||
import { useState, createContext, useContext, ReactNode } from "react"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
type DialogType = "alert" | "confirm" | "prompt"
|
||||
|
||||
interface DialogConfig {
|
||||
type: DialogType
|
||||
title?: string
|
||||
message: string
|
||||
defaultValue?: string
|
||||
confirmText?: string
|
||||
cancelText?: string
|
||||
variant?: "default" | "destructive"
|
||||
onConfirm?: (value?: string) => void
|
||||
onCancel?: () => void
|
||||
}
|
||||
|
||||
interface DialogContextType {
|
||||
showAlert: (message: string, title?: string) => Promise<void>
|
||||
showConfirm: (message: string, title?: string, variant?: "default" | "destructive") => Promise<boolean>
|
||||
showPrompt: (message: string, defaultValue?: string, title?: string) => Promise<string | null>
|
||||
}
|
||||
|
||||
const DialogContext = createContext<DialogContextType | undefined>(undefined)
|
||||
|
||||
export function DialogProvider({ children }: { children: ReactNode }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [config, setConfig] = useState<DialogConfig | null>(null)
|
||||
const [inputValue, setInputValue] = useState("")
|
||||
|
||||
const showAlert = (message: string, title?: string): Promise<void> => {
|
||||
return new Promise((resolve) => {
|
||||
setConfig({
|
||||
type: "alert",
|
||||
title: title || "提示",
|
||||
message,
|
||||
confirmText: "确定",
|
||||
onConfirm: () => {
|
||||
setOpen(false)
|
||||
resolve()
|
||||
},
|
||||
})
|
||||
setOpen(true)
|
||||
})
|
||||
}
|
||||
|
||||
const showConfirm = (
|
||||
message: string,
|
||||
title?: string,
|
||||
variant: "default" | "destructive" = "default"
|
||||
): Promise<boolean> => {
|
||||
return new Promise((resolve) => {
|
||||
setConfig({
|
||||
type: "confirm",
|
||||
title: title || "确认",
|
||||
message,
|
||||
confirmText: "确定",
|
||||
cancelText: "取消",
|
||||
variant,
|
||||
onConfirm: () => {
|
||||
setOpen(false)
|
||||
resolve(true)
|
||||
},
|
||||
onCancel: () => {
|
||||
setOpen(false)
|
||||
resolve(false)
|
||||
},
|
||||
})
|
||||
setOpen(true)
|
||||
})
|
||||
}
|
||||
|
||||
const showPrompt = (
|
||||
message: string,
|
||||
defaultValue: string = "",
|
||||
title?: string
|
||||
): Promise<string | null> => {
|
||||
return new Promise((resolve) => {
|
||||
setInputValue(defaultValue)
|
||||
setConfig({
|
||||
type: "prompt",
|
||||
title: title || "输入",
|
||||
message,
|
||||
defaultValue,
|
||||
confirmText: "确定",
|
||||
cancelText: "取消",
|
||||
onConfirm: (value) => {
|
||||
setOpen(false)
|
||||
resolve(value || null)
|
||||
},
|
||||
onCancel: () => {
|
||||
setOpen(false)
|
||||
resolve(null)
|
||||
},
|
||||
})
|
||||
setOpen(true)
|
||||
})
|
||||
}
|
||||
|
||||
const handleConfirm = () => {
|
||||
if (config?.type === "prompt") {
|
||||
config.onConfirm?.(inputValue)
|
||||
} else {
|
||||
config?.onConfirm?.()
|
||||
}
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
config?.onCancel?.()
|
||||
}
|
||||
|
||||
return (
|
||||
<DialogContext.Provider value={{ showAlert, showConfirm, showPrompt }}>
|
||||
{children}
|
||||
<AlertDialog open={open} onOpenChange={setOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{config?.title}</AlertDialogTitle>
|
||||
<AlertDialogDescription className="whitespace-pre-wrap">
|
||||
{config?.message}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
|
||||
{config?.type === "prompt" && (
|
||||
<div className="py-4">
|
||||
<Label htmlFor="prompt-input" className="sr-only">
|
||||
输入值
|
||||
</Label>
|
||||
<Input
|
||||
id="prompt-input"
|
||||
value={inputValue}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
handleConfirm()
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<AlertDialogFooter>
|
||||
{config?.type !== "alert" && (
|
||||
<AlertDialogCancel onClick={handleCancel}>
|
||||
{config?.cancelText || "取消"}
|
||||
</AlertDialogCancel>
|
||||
)}
|
||||
<AlertDialogAction
|
||||
onClick={handleConfirm}
|
||||
className={config?.variant === "destructive" ? "bg-destructive text-destructive-foreground hover:bg-destructive/90" : ""}
|
||||
>
|
||||
{config?.confirmText || "确定"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</DialogContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useDialog() {
|
||||
const context = useContext(DialogContext)
|
||||
if (!context) {
|
||||
throw new Error("useDialog must be used within a DialogProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
Reference in New Issue
Block a user