feat: 完成后端-管理后台集成及部署配置

🚀 主要功能:
- 完善后端API服务层,实现完整的CRUD操作
- 开发管理后台所有核心页面 (仪表板、照片、分类、标签、用户、设置)
- 完成前后端完全集成,所有API接口正常对接
- 配置完整的CI/CD流水线,支持自动化部署

🎯 后端完善:
- 实现PhotoService, CategoryService, TagService, UserService
- 添加完整的API处理器和路由配置
- 支持Docker容器化部署
- 添加数据库迁移和健康检查

🎨 管理后台完成:
- 仪表板: 实时统计数据展示
- 照片管理: 完整的CRUD操作,支持批量处理
- 分类管理: 树形结构展示和管理
- 标签管理: 颜色标签和统计信息
- 用户管理: 角色权限控制
- 系统设置: 多标签配置界面
- 添加pre-commit代码质量检查

🔧 部署配置:
- Docker Compose完整配置
- 后端CI/CD流水线 (Docker部署)
- 管理后台CI/CD流水线 (静态文件部署)
- 前端CI/CD流水线优化
- 自动化脚本: 部署、备份、监控
- 完整的部署文档和运维指南

 集成完成:
- 所有API接口正常连接
- 认证系统完整集成
- 数据获取和状态管理
- 错误处理和用户反馈
- 响应式设计优化
This commit is contained in:
xujiang
2025-07-09 16:23:18 +08:00
parent c57ec3aa82
commit 72414d0979
62 changed files with 12416 additions and 262 deletions

View File

@ -0,0 +1,217 @@
import React, { useState } from 'react'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { Button } from '@/components/ui/button'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet'
import {
LayoutDashboard,
Camera,
FolderOpen,
Tags,
Users,
Settings,
LogOut,
Menu,
User,
Bell,
Search
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { useAuthStore } from '@/stores/authStore'
import { authService } from '@/services/authService'
import { toast } from 'sonner'
interface DashboardLayoutProps {
children: React.ReactNode
}
const navigation = [
{ name: '仪表板', href: '/dashboard', icon: LayoutDashboard },
{ name: '照片管理', href: '/photos', icon: Camera },
{ name: '分类管理', href: '/categories', icon: FolderOpen },
{ name: '标签管理', href: '/tags', icon: Tags },
{ name: '用户管理', href: '/users', icon: Users },
{ name: '系统设置', href: '/settings', icon: Settings },
]
export default function DashboardLayout({ children }: DashboardLayoutProps) {
const location = useLocation()
const navigate = useNavigate()
const { user, logout } = useAuthStore()
const [sidebarOpen, setSidebarOpen] = useState(false)
// 获取当前用户信息
const { data: currentUser } = useQuery({
queryKey: ['current-user'],
queryFn: authService.getCurrentUser,
initialData: user,
staleTime: 5 * 60 * 1000, // 5分钟
})
const handleLogout = async () => {
try {
await authService.logout()
logout()
toast.success('退出登录成功')
navigate('/login')
} catch (error) {
toast.error('退出登录失败')
}
}
const isCurrentPath = (path: string) => {
return location.pathname === path || location.pathname.startsWith(path + '/')
}
const SidebarContent = () => (
<div className="flex h-full flex-col">
{/* Logo */}
<div className="flex h-16 items-center border-b px-4">
<Link to="/dashboard" className="flex items-center space-x-2">
<div className="bg-primary p-2 rounded-md">
<Camera className="h-5 w-5 text-white" />
</div>
<span className="text-xl font-semibold"></span>
</Link>
</div>
{/* Navigation */}
<nav className="flex-1 space-y-1 px-2 py-4">
{navigation.map((item) => {
const Icon = item.icon
const isActive = isCurrentPath(item.href)
return (
<Link
key={item.name}
to={item.href}
className={cn(
'group flex items-center px-2 py-2 text-sm font-medium rounded-md transition-colors',
isActive
? 'bg-primary text-white'
: 'text-gray-700 hover:bg-gray-100 hover:text-gray-900'
)}
onClick={() => setSidebarOpen(false)}
>
<Icon className="mr-3 h-5 w-5" />
{item.name}
</Link>
)
})}
</nav>
{/* User info */}
<div className="border-t p-4">
<div className="flex items-center space-x-3">
<Avatar className="h-8 w-8">
<AvatarImage src={undefined} />
<AvatarFallback>
{currentUser?.username?.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-gray-900 truncate">
{currentUser?.username}
</p>
<Badge variant="secondary" className="text-xs">
{currentUser?.role === 'admin' ? '管理员' :
currentUser?.role === 'editor' ? '编辑者' : '用户'}
</Badge>
</div>
</div>
</div>
</div>
)
return (
<div className="flex h-screen bg-gray-100">
{/* Desktop sidebar */}
<div className="hidden lg:flex lg:flex-col lg:w-64 lg:fixed lg:inset-y-0 lg:bg-white lg:border-r">
<SidebarContent />
</div>
{/* Mobile sidebar */}
<Sheet open={sidebarOpen} onOpenChange={setSidebarOpen}>
<SheetContent side="left" className="p-0 w-64">
<SidebarContent />
</SheetContent>
</Sheet>
{/* Main content */}
<div className="flex-1 lg:ml-64">
{/* Top bar */}
<header className="bg-white border-b h-16 flex items-center justify-between px-4">
<div className="flex items-center space-x-4">
<Sheet>
<SheetTrigger asChild>
<Button variant="ghost" size="sm" className="lg:hidden">
<Menu className="h-5 w-5" />
</Button>
</SheetTrigger>
</Sheet>
<div className="flex items-center space-x-2">
<Search className="h-5 w-5 text-gray-400" />
<input
type="text"
placeholder="搜索..."
className="bg-gray-50 border-0 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
/>
</div>
</div>
<div className="flex items-center space-x-4">
<Button variant="ghost" size="sm">
<Bell className="h-5 w-5" />
</Button>
<Separator orientation="vertical" className="h-6" />
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="flex items-center space-x-2">
<Avatar className="h-8 w-8">
<AvatarImage src={undefined} />
<AvatarFallback>
{currentUser?.username?.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="hidden md:block text-left">
<p className="text-sm font-medium">{currentUser?.username}</p>
<p className="text-xs text-gray-500">{currentUser?.email}</p>
</div>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuLabel></DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => navigate('/profile')}>
<User className="mr-2 h-4 w-4" />
</DropdownMenuItem>
<DropdownMenuItem onClick={() => navigate('/settings')}>
<Settings className="mr-2 h-4 w-4" />
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={handleLogout}>
<LogOut className="mr-2 h-4 w-4" />
退
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</header>
{/* Page content */}
<main className="flex-1 overflow-auto">
{children}
</main>
</div>
</div>
)
}

View File

@ -0,0 +1,59 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription }

View File

@ -0,0 +1,48 @@
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn(
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
))
Avatar.displayName = AvatarPrimitive.Root.displayName
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn(
"flex h-full w-full items-center justify-center rounded-full bg-muted",
className
)}
{...props}
/>
))
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
export { Avatar, AvatarImage, AvatarFallback }

View File

@ -0,0 +1,28 @@
import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { Check } from "lucide-react"
import { cn } from "@/lib/utils"
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center text-current")}
>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
))
Checkbox.displayName = CheckboxPrimitive.Root.displayName
export { Checkbox }

View File

@ -0,0 +1,198 @@
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const DropdownMenu = DropdownMenuPrimitive.Root
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
const DropdownMenuGroup = DropdownMenuPrimitive.Group
const DropdownMenuPortal = DropdownMenuPrimitive.Portal
const DropdownMenuSub = DropdownMenuPrimitive.Sub
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger>
))
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
))
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
))
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
)
}
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
}

View File

@ -0,0 +1,24 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }

View File

@ -0,0 +1,158 @@
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { Check, ChevronDown, ChevronUp } from "lucide-react"
import { cn } from "@/lib/utils"
const Select = SelectPrimitive.Root
const SelectGroup = SelectPrimitive.Group
const SelectValue = SelectPrimitive.Value
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
))
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
))
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
{...props}
/>
))
SelectLabel.displayName = SelectPrimitive.Label.displayName
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
}

View File

@ -0,0 +1,29 @@
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(
(
{ className, orientation = "horizontal", decorative = true, ...props },
ref
) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border",
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
className
)}
{...props}
/>
)
)
Separator.displayName = SeparatorPrimitive.Root.displayName
export { Separator }

View File

@ -0,0 +1,138 @@
import * as React from "react"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { cva, type VariantProps } from "class-variance-authority"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Sheet = SheetPrimitive.Root
const SheetTrigger = SheetPrimitive.Trigger
const SheetClose = SheetPrimitive.Close
const SheetPortal = SheetPrimitive.Portal
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
))
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName
const sheetVariants = cva(
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
{
variants: {
side: {
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
bottom:
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
right:
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
},
},
defaultVariants: {
side: "right",
},
}
)
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Content>,
SheetContentProps
>(({ side = "right", className, children, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
ref={ref}
className={cn(sheetVariants({ side }), className)}
{...props}
>
{children}
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
))
SheetContent.displayName = SheetPrimitive.Content.displayName
const SheetHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className
)}
{...props}
/>
)
SheetHeader.displayName = "SheetHeader"
const SheetFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
SheetFooter.displayName = "SheetFooter"
const SheetTitle = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold text-foreground", className)}
{...props}
/>
))
SheetTitle.displayName = SheetPrimitive.Title.displayName
const SheetDescription = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
SheetDescription.displayName = SheetPrimitive.Description.displayName
export {
Sheet,
SheetPortal,
SheetOverlay,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
}

View File

@ -0,0 +1,15 @@
import { cn } from "@/lib/utils"
function Skeleton({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn("animate-pulse rounded-md bg-muted", className)}
{...props}
/>
)
}
export { Skeleton }

View File

@ -0,0 +1,27 @@
import * as React from "react"
import * as SwitchPrimitives from "@radix-ui/react-switch"
import { cn } from "@/lib/utils"
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
className
)}
{...props}
ref={ref}
>
<SwitchPrimitives.Thumb
className={cn(
"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0"
)}
/>
</SwitchPrimitives.Root>
))
Switch.displayName = SwitchPrimitives.Root.displayName
export { Switch }

View File

@ -0,0 +1,24 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export interface TextareaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Textarea.displayName = "Textarea"
export { Textarea }

86
admin/src/lib/utils.ts Normal file
View File

@ -0,0 +1,86 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function formatFileSize(bytes: number): string {
if (bytes === 0) return '0 Bytes'
const k = 1024
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
export function formatDate(date: string | Date): string {
const d = typeof date === 'string' ? new Date(date) : date
return d.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
})
}
export function formatDateTime(date: string | Date): string {
const d = typeof date === 'string' ? new Date(date) : date
return d.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
}
export function generateSlug(text: string): string {
return text
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '') // 移除特殊字符
.replace(/[\s_-]+/g, '-') // 替换空格和下划线为连字符
.replace(/^-+|-+$/g, '') // 移除开头和结尾的连字符
}
export function truncate(text: string, length: number): string {
if (text.length <= length) return text
return text.substring(0, length) + '...'
}
export function debounce<T extends (...args: any[]) => any>(
func: T,
wait: number
): (...args: Parameters<T>) => void {
let timeout: NodeJS.Timeout | null = null
return (...args: Parameters<T>) => {
if (timeout) clearTimeout(timeout)
timeout = setTimeout(() => func(...args), wait)
}
}
export function isImageFile(file: File): boolean {
const imageTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/bmp']
return imageTypes.includes(file.type)
}
export function getImageDimensions(file: File): Promise<{ width: number; height: number }> {
return new Promise((resolve, reject) => {
const img = new Image()
const url = URL.createObjectURL(file)
img.onload = () => {
URL.revokeObjectURL(url)
resolve({ width: img.naturalWidth, height: img.naturalHeight })
}
img.onerror = () => {
URL.revokeObjectURL(url)
reject(new Error('Failed to load image'))
}
img.src = url
})
}

View File

@ -0,0 +1,252 @@
import React, { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import {
FolderOpen,
FolderPlus,
MoreVerticalIcon,
EditIcon,
TrashIcon,
PlusIcon,
SearchIcon,
TreePineIcon
} from 'lucide-react'
import { toast } from 'sonner'
import { categoryService } from '@/services/categoryService'
export default function Categories() {
const queryClient = useQueryClient()
const [search, setSearch] = useState('')
// 获取分类树
const { data: categories, isLoading: categoriesLoading } = useQuery({
queryKey: ['categories-tree'],
queryFn: categoryService.getCategoryTree
})
// 获取分类统计
const { data: stats, isLoading: statsLoading } = useQuery({
queryKey: ['category-stats'],
queryFn: categoryService.getStats
})
// 删除分类
const deleteCategoryMutation = useMutation({
mutationFn: categoryService.deleteCategory,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['categories-tree'] })
queryClient.invalidateQueries({ queryKey: ['category-stats'] })
toast.success('分类删除成功')
},
onError: (error: any) => {
toast.error(error?.message || '删除失败')
}
})
const handleDeleteCategory = (categoryId: number) => {
if (confirm('确定要删除这个分类吗?')) {
deleteCategoryMutation.mutate(categoryId)
}
}
const renderCategoryTree = (categories: any[], level = 0) => {
return categories?.map((category) => (
<div key={category.id} className="mb-2">
<div className={`flex items-center justify-between p-3 border rounded-lg ${level > 0 ? 'ml-6 border-l-4 border-l-primary/20' : ''}`}>
<div className="flex items-center space-x-3">
<FolderOpen className="h-5 w-5 text-blue-500" />
<div>
<div className="flex items-center space-x-2">
<span className="font-medium">{category.name}</span>
<Badge variant={category.isActive ? 'default' : 'secondary'}>
{category.isActive ? '启用' : '禁用'}
</Badge>
<Badge variant="outline">
{category.photoCount}
</Badge>
</div>
{category.description && (
<p className="text-sm text-muted-foreground mt-1">{category.description}</p>
)}
</div>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm">
<MoreVerticalIcon className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem>
<EditIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
<DropdownMenuItem>
<FolderPlus className="h-4 w-4 mr-2" />
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleDeleteCategory(category.id)}
disabled={category.photoCount > 0 || category.children?.length > 0}
>
<TrashIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{category.children && category.children.length > 0 && (
<div className="mt-2">
{renderCategoryTree(category.children, level + 1)}
</div>
)}
</div>
))
}
return (
<div className="container mx-auto px-4 py-8">
{/* 页面头部 */}
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-3xl font-bold"></h1>
<p className="text-muted-foreground mt-1">
</p>
</div>
<Button className="flex items-center gap-2">
<PlusIcon className="h-4 w-4" />
</Button>
</div>
{/* 统计卡片 */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<FolderOpen className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold">{stats?.total || 0}</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<TreePineIcon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold text-green-600">{stats?.active || 0}</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<FolderOpen className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold text-blue-600">{stats?.topLevel || 0}</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<FolderOpen className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold text-purple-600">
{stats?.total ? Math.round(Object.values(stats.photoCounts || {}).reduce((a, b) => a + b, 0) / stats.total) : 0}
</div>
)}
</CardContent>
</Card>
</div>
{/* 搜索栏 */}
<Card className="mb-6">
<CardContent className="pt-6">
<div className="flex items-center gap-4">
<div className="flex-1 relative">
<SearchIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
<Input
placeholder="搜索分类..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
<Button variant="outline">
<TreePineIcon className="h-4 w-4 mr-2" />
</Button>
</div>
</CardContent>
</Card>
{/* 分类列表 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
{categoriesLoading ? (
<div className="space-y-4">
{[...Array(5)].map((_, i) => (
<div key={i} className="flex items-center gap-4 p-4 border rounded-lg">
<Skeleton className="h-5 w-5" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-3 w-64" />
</div>
<Skeleton className="h-8 w-8" />
</div>
))}
</div>
) : categories?.length ? (
<div className="space-y-2">
{renderCategoryTree(categories)}
</div>
) : (
<div className="text-center py-12">
<FolderOpen className="h-16 w-16 mx-auto mb-4 text-gray-300" />
<h3 className="text-lg font-medium mb-2"></h3>
<p className="text-muted-foreground mb-4">
</p>
<Button>
<PlusIcon className="h-4 w-4 mr-2" />
</Button>
</div>
)}
</CardContent>
</Card>
</div>
)
}

View File

@ -0,0 +1,272 @@
import React from 'react'
import { useQuery } from '@tanstack/react-query'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { PhotoIcon, FolderIcon, TagIcon, PlusIcon, TrendingUpIcon } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { photoService } from '@/services/photoService'
import { categoryService } from '@/services/categoryService'
import { tagService } from '@/services/tagService'
export default function Dashboard() {
const navigate = useNavigate()
// 获取统计数据
const { data: photoStats, isLoading: photoStatsLoading } = useQuery({
queryKey: ['photo-stats'],
queryFn: photoService.getStats
})
const { data: categoryStats, isLoading: categoryStatsLoading } = useQuery({
queryKey: ['category-stats'],
queryFn: categoryService.getStats
})
const { data: tagStats, isLoading: tagStatsLoading } = useQuery({
queryKey: ['tag-stats'],
queryFn: tagService.getStats
})
// 获取最近照片
const { data: recentPhotos, isLoading: recentPhotosLoading } = useQuery({
queryKey: ['recent-photos'],
queryFn: () => photoService.getPhotos({ page: 1, limit: 5, sort_by: 'created_at', sort_order: 'desc' })
})
// 获取热门标签
const { data: popularTags, isLoading: popularTagsLoading } = useQuery({
queryKey: ['popular-tags'],
queryFn: () => tagService.getPopularTags(10)
})
const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 Bytes'
const k = 1024
const sizes = ['Bytes', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
const getStatusColor = (status: string) => {
switch (status) {
case 'published': return 'bg-green-100 text-green-800'
case 'draft': return 'bg-yellow-100 text-yellow-800'
case 'archived': return 'bg-gray-100 text-gray-800'
case 'processing': return 'bg-blue-100 text-blue-800'
default: return 'bg-gray-100 text-gray-800'
}
}
const getStatusText = (status: string) => {
switch (status) {
case 'published': return '已发布'
case 'draft': return '草稿'
case 'archived': return '已归档'
case 'processing': return '处理中'
default: return status
}
}
return (
<div className="container mx-auto px-4 py-8">
<div className="flex items-center justify-between mb-8">
<h1 className="text-3xl font-bold"></h1>
<Button onClick={() => navigate('/photos/upload')} className="flex items-center gap-2">
<PlusIcon className="h-4 w-4" />
</Button>
</div>
{/* 统计卡片 */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<PhotoIcon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{photoStatsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold">{photoStats?.total || 0}</div>
)}
<div className="text-xs text-muted-foreground mt-1">
: {formatFileSize(photoStats?.totalSize || 0)}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<TrendingUpIcon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{photoStatsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold text-green-600">{photoStats?.thisMonth || 0}</div>
)}
<div className="text-xs text-muted-foreground mt-1">
: {photoStats?.today || 0}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<FolderIcon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{categoryStatsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold text-blue-600">{categoryStats?.total || 0}</div>
)}
<div className="text-xs text-muted-foreground mt-1">
: {categoryStats?.active || 0}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<TagIcon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{tagStatsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold text-purple-600">{tagStats?.total || 0}</div>
)}
<div className="text-xs text-muted-foreground mt-1">
使: {tagStats?.used || 0}
</div>
</CardContent>
</Card>
</div>
{/* 照片状态统计 */}
{photoStats?.statusStats && (
<Card className="mb-8">
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-wrap gap-4">
{Object.entries(photoStats.statusStats).map(([status, count]) => (
<div key={status} className="flex items-center gap-2">
<Badge className={getStatusColor(status)}>
{getStatusText(status)}
</Badge>
<span className="text-sm text-muted-foreground">{count}</span>
</div>
))}
</div>
</CardContent>
</Card>
)}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* 最近上传 */}
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle></CardTitle>
<Button variant="outline" size="sm" onClick={() => navigate('/photos')}>
</Button>
</CardHeader>
<CardContent>
{recentPhotosLoading ? (
<div className="space-y-4">
{[...Array(3)].map((_, i) => (
<div key={i} className="flex items-center gap-4">
<Skeleton className="h-12 w-12 rounded" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-3 w-24" />
</div>
</div>
))}
</div>
) : recentPhotos?.photos?.length ? (
<div className="space-y-4">
{recentPhotos.photos.map((photo) => (
<div key={photo.id} className="flex items-center gap-4">
<div className="h-12 w-12 bg-gray-100 rounded flex items-center justify-center">
<PhotoIcon className="h-6 w-6 text-gray-400" />
</div>
<div className="flex-1 min-w-0">
<div className="text-sm font-medium truncate">{photo.title}</div>
<div className="text-xs text-muted-foreground">
{new Date(photo.createdAt).toLocaleDateString()}
</div>
</div>
<Badge className={getStatusColor(photo.status)}>
{getStatusText(photo.status)}
</Badge>
</div>
))}
</div>
) : (
<div className="text-center py-8 text-muted-foreground">
<PhotoIcon className="h-12 w-12 mx-auto mb-4 text-gray-300" />
<p></p>
<Button
variant="outline"
className="mt-4"
onClick={() => navigate('/photos/upload')}
>
</Button>
</div>
)}
</CardContent>
</Card>
{/* 热门标签 */}
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle></CardTitle>
<Button variant="outline" size="sm" onClick={() => navigate('/tags')}>
</Button>
</CardHeader>
<CardContent>
{popularTagsLoading ? (
<div className="flex flex-wrap gap-2">
{[...Array(6)].map((_, i) => (
<Skeleton key={i} className="h-6 w-16" />
))}
</div>
) : popularTags?.length ? (
<div className="flex flex-wrap gap-2">
{popularTags.map((tag) => (
<Badge key={tag.id} variant="secondary" className="cursor-pointer hover:bg-secondary/80">
{tag.name} ({tag.photoCount})
</Badge>
))}
</div>
) : (
<div className="text-center py-8 text-muted-foreground">
<TagIcon className="h-12 w-12 mx-auto mb-4 text-gray-300" />
<p></p>
<Button
variant="outline"
className="mt-4"
onClick={() => navigate('/tags')}
>
</Button>
</div>
)}
</CardContent>
</Card>
</div>
</div>
)
}

View File

@ -0,0 +1,162 @@
import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useMutation } from '@tanstack/react-query'
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 { Alert, AlertDescription } from '@/components/ui/alert'
import { Loader2, Eye, EyeOff, Camera } from 'lucide-react'
import { useAuthStore } from '@/stores/authStore'
import { authService } from '@/services/authService'
import { toast } from 'sonner'
export default function LoginPage() {
const navigate = useNavigate()
const { login } = useAuthStore()
const [formData, setFormData] = useState({
username: '',
password: ''
})
const [showPassword, setShowPassword] = useState(false)
const [error, setError] = useState('')
const loginMutation = useMutation({
mutationFn: authService.login,
onSuccess: (data) => {
login(data.access_token, data.user)
toast.success('登录成功')
navigate('/')
},
onError: (error: any) => {
const message = error?.response?.data?.message || error.message || '登录失败'
setError(message)
toast.error(message)
}
})
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
setError('')
if (!formData.username || !formData.password) {
setError('请输入用户名和密码')
return
}
loginMutation.mutate(formData)
}
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target
setFormData(prev => ({ ...prev, [name]: value }))
if (error) setError('')
}
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100 p-4">
<div className="w-full max-w-md">
{/* Logo和标题 */}
<div className="text-center mb-8">
<div className="flex justify-center items-center mb-4">
<div className="bg-primary p-3 rounded-full">
<Camera className="h-8 w-8 text-white" />
</div>
</div>
<h1 className="text-3xl font-bold text-gray-900"></h1>
<p className="text-gray-600 mt-2"></p>
</div>
<Card className="shadow-lg">
<CardHeader className="space-y-1">
<CardTitle className="text-2xl font-bold text-center"></CardTitle>
<CardDescription className="text-center">
使
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="username"></Label>
<Input
id="username"
name="username"
type="text"
placeholder="请输入用户名或邮箱"
value={formData.username}
onChange={handleInputChange}
disabled={loginMutation.isPending}
className="h-11"
/>
</div>
<div className="space-y-2">
<Label htmlFor="password"></Label>
<div className="relative">
<Input
id="password"
name="password"
type={showPassword ? 'text' : 'password'}
placeholder="请输入密码"
value={formData.password}
onChange={handleInputChange}
disabled={loginMutation.isPending}
className="h-11 pr-10"
/>
<Button
type="button"
variant="ghost"
size="sm"
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
onClick={() => setShowPassword(!showPassword)}
disabled={loginMutation.isPending}
>
{showPassword ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</Button>
</div>
</div>
<Button
type="submit"
className="w-full h-11 text-base"
disabled={loginMutation.isPending}
>
{loginMutation.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
...
</>
) : (
'登录'
)}
</Button>
</form>
<div className="mt-6 text-center text-sm text-gray-600">
<p></p>
<p className="mt-1">
: <span className="font-medium">admin</span> |
: <span className="font-medium">admin123</span>
</p>
</div>
</CardContent>
</Card>
<div className="mt-8 text-center text-sm text-gray-500">
<p>© 2024 . .</p>
</div>
</div>
</div>
)
}

518
admin/src/pages/Photos.tsx Normal file
View File

@ -0,0 +1,518 @@
import React, { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Checkbox } from '@/components/ui/checkbox'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import {
PhotoIcon,
PlusIcon,
SearchIcon,
FilterIcon,
MoreVerticalIcon,
EditIcon,
TrashIcon,
EyeIcon,
DownloadIcon,
GridIcon,
ListIcon
} from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { toast } from 'sonner'
import { photoService } from '@/services/photoService'
import { categoryService } from '@/services/categoryService'
import { tagService } from '@/services/tagService'
type ViewMode = 'grid' | 'list'
interface PhotoFilters {
search: string
status: string
categoryId: string
tagId: string
dateRange: string
}
export default function Photos() {
const navigate = useNavigate()
const queryClient = useQueryClient()
// 状态管理
const [viewMode, setViewMode] = useState<ViewMode>('grid')
const [selectedPhotos, setSelectedPhotos] = useState<number[]>([])
const [page, setPage] = useState(1)
const [filters, setFilters] = useState<PhotoFilters>({
search: '',
status: '',
categoryId: '',
tagId: '',
dateRange: ''
})
// 获取照片列表
const { data: photosData, isLoading: photosLoading } = useQuery({
queryKey: ['photos', { page, ...filters }],
queryFn: () => photoService.getPhotos({
page,
limit: 20,
search: filters.search || undefined,
status: filters.status || undefined,
category_id: filters.categoryId ? parseInt(filters.categoryId) : undefined,
sort_by: 'created_at',
sort_order: 'desc'
})
})
// 获取分类列表
const { data: categories } = useQuery({
queryKey: ['categories-all'],
queryFn: () => categoryService.getCategories()
})
// 获取标签列表
const { data: tags } = useQuery({
queryKey: ['tags-all'],
queryFn: () => tagService.getAllTags()
})
// 删除照片
const deletePhotoMutation = useMutation({
mutationFn: photoService.deletePhoto,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['photos'] })
toast.success('照片删除成功')
},
onError: (error: any) => {
toast.error(error?.message || '删除失败')
}
})
// 批量删除照片
const batchDeleteMutation = useMutation({
mutationFn: photoService.batchDelete,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['photos'] })
setSelectedPhotos([])
toast.success('批量删除成功')
},
onError: (error: any) => {
toast.error(error?.message || '批量删除失败')
}
})
// 批量更新状态
const batchUpdateMutation = useMutation({
mutationFn: ({ ids, status }: { ids: number[], status: string }) =>
photoService.batchUpdate(ids, { status }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['photos'] })
setSelectedPhotos([])
toast.success('状态更新成功')
},
onError: (error: any) => {
toast.error(error?.message || '状态更新失败')
}
})
const handleSelectAll = (checked: boolean) => {
if (checked) {
setSelectedPhotos(photosData?.photos.map(photo => photo.id) || [])
} else {
setSelectedPhotos([])
}
}
const handleSelectPhoto = (photoId: number, checked: boolean) => {
if (checked) {
setSelectedPhotos([...selectedPhotos, photoId])
} else {
setSelectedPhotos(selectedPhotos.filter(id => id !== photoId))
}
}
const handleBatchAction = (action: string, value?: string) => {
if (selectedPhotos.length === 0) {
toast.error('请先选择照片')
return
}
if (action === 'delete') {
if (confirm('确定要删除选中的照片吗?')) {
batchDeleteMutation.mutate(selectedPhotos)
}
} else if (action === 'status' && value) {
batchUpdateMutation.mutate({ ids: selectedPhotos, status: value })
}
}
const handleDeletePhoto = (photoId: number) => {
if (confirm('确定要删除这张照片吗?')) {
deletePhotoMutation.mutate(photoId)
}
}
const getStatusColor = (status: string) => {
switch (status) {
case 'published': return 'bg-green-100 text-green-800'
case 'draft': return 'bg-yellow-100 text-yellow-800'
case 'archived': return 'bg-gray-100 text-gray-800'
case 'processing': return 'bg-blue-100 text-blue-800'
default: return 'bg-gray-100 text-gray-800'
}
}
const getStatusText = (status: string) => {
switch (status) {
case 'published': return '已发布'
case 'draft': return '草稿'
case 'archived': return '已归档'
case 'processing': return '处理中'
default: return status
}
}
const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 Bytes'
const k = 1024
const sizes = ['Bytes', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
return (
<div className="container mx-auto px-4 py-8">
{/* 页面头部 */}
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-3xl font-bold"></h1>
<p className="text-muted-foreground mt-1">
{photosData?.total || 0}
</p>
</div>
<Button onClick={() => navigate('/photos/upload')} className="flex items-center gap-2">
<PlusIcon className="h-4 w-4" />
</Button>
</div>
{/* 工具栏 */}
<Card className="mb-6">
<CardContent className="pt-6">
<div className="flex flex-col lg:flex-row gap-4">
{/* 搜索 */}
<div className="flex-1 relative">
<SearchIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
<Input
placeholder="搜索照片..."
value={filters.search}
onChange={(e) => setFilters({ ...filters, search: e.target.value })}
className="pl-10"
/>
</div>
{/* 过滤器 */}
<div className="flex gap-2">
<Select value={filters.status} onValueChange={(value) => setFilters({ ...filters, status: value })}>
<SelectTrigger className="w-32">
<SelectValue placeholder="状态" />
</SelectTrigger>
<SelectContent>
<SelectItem value=""></SelectItem>
<SelectItem value="published"></SelectItem>
<SelectItem value="draft">稿</SelectItem>
<SelectItem value="archived"></SelectItem>
<SelectItem value="processing"></SelectItem>
</SelectContent>
</Select>
<Select value={filters.categoryId} onValueChange={(value) => setFilters({ ...filters, categoryId: value })}>
<SelectTrigger className="w-32">
<SelectValue placeholder="分类" />
</SelectTrigger>
<SelectContent>
<SelectItem value=""></SelectItem>
{categories?.map((category) => (
<SelectItem key={category.id} value={category.id.toString()}>
{category.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 视图模式 */}
<div className="flex gap-1 border rounded-md">
<Button
variant={viewMode === 'grid' ? 'default' : 'ghost'}
size="sm"
onClick={() => setViewMode('grid')}
>
<GridIcon className="h-4 w-4" />
</Button>
<Button
variant={viewMode === 'list' ? 'default' : 'ghost'}
size="sm"
onClick={() => setViewMode('list')}
>
<ListIcon className="h-4 w-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
{/* 批量操作栏 */}
{selectedPhotos.length > 0 && (
<Card className="mb-6 border-primary">
<CardContent className="pt-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<span className="text-sm">
{selectedPhotos.length}
</span>
<Button variant="outline" size="sm" onClick={() => setSelectedPhotos([])}>
</Button>
</div>
<div className="flex gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem onClick={() => handleBatchAction('status', 'published')}>
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleBatchAction('status', 'draft')}>
稿
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleBatchAction('status', 'archived')}>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Button
variant="destructive"
size="sm"
onClick={() => handleBatchAction('delete')}
disabled={batchDeleteMutation.isPending}
>
</Button>
</div>
</div>
</CardContent>
</Card>
)}
{/* 照片列表 */}
{photosLoading ? (
<div className={viewMode === 'grid' ? 'grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6' : 'space-y-4'}>
{[...Array(8)].map((_, i) => (
<Card key={i}>
<CardContent className="p-4">
<Skeleton className={viewMode === 'grid' ? 'aspect-square mb-4' : 'h-20 w-20 mb-4'} />
<Skeleton className="h-4 w-3/4 mb-2" />
<Skeleton className="h-3 w-1/2" />
</CardContent>
</Card>
))}
</div>
) : photosData?.photos?.length ? (
<>
{/* 全选复选框 */}
<div className="flex items-center gap-2 mb-4">
<Checkbox
checked={selectedPhotos.length === photosData.photos.length && photosData.photos.length > 0}
onCheckedChange={handleSelectAll}
/>
<span className="text-sm text-muted-foreground"></span>
</div>
{viewMode === 'grid' ? (
<div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6">
{photosData.photos.map((photo) => (
<Card key={photo.id} className="group">
<CardContent className="p-4">
<div className="relative mb-4">
<div className="aspect-square bg-gray-100 rounded-lg flex items-center justify-center">
<PhotoIcon className="h-12 w-12 text-gray-400" />
</div>
{/* 复选框 */}
<div className="absolute top-2 left-2">
<Checkbox
checked={selectedPhotos.includes(photo.id)}
onCheckedChange={(checked) => handleSelectPhoto(photo.id, checked as boolean)}
className="bg-white"
/>
</div>
{/* 操作按钮 */}
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" className="h-8 w-8 p-0 bg-white">
<MoreVerticalIcon className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => navigate(`/photos/${photo.id}`)}>
<EyeIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
<DropdownMenuItem onClick={() => navigate(`/photos/${photo.id}/edit`)}>
<EditIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleDeletePhoto(photo.id)}>
<TrashIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
<div>
<h3 className="font-medium truncate mb-2">{photo.title}</h3>
<div className="flex items-center justify-between mb-2">
<Badge className={getStatusColor(photo.status)}>
{getStatusText(photo.status)}
</Badge>
<span className="text-xs text-muted-foreground">
{formatFileSize(photo.fileSize)}
</span>
</div>
<div className="text-xs text-muted-foreground">
{new Date(photo.createdAt).toLocaleDateString()}
</div>
</div>
</CardContent>
</Card>
))}
</div>
) : (
<div className="space-y-4">
{photosData.photos.map((photo) => (
<Card key={photo.id}>
<CardContent className="p-4">
<div className="flex items-center gap-4">
<Checkbox
checked={selectedPhotos.includes(photo.id)}
onCheckedChange={(checked) => handleSelectPhoto(photo.id, checked as boolean)}
/>
<div className="h-16 w-16 bg-gray-100 rounded flex items-center justify-center flex-shrink-0">
<PhotoIcon className="h-8 w-8 text-gray-400" />
</div>
<div className="flex-1 min-w-0">
<h3 className="font-medium truncate">{photo.title}</h3>
<p className="text-sm text-muted-foreground truncate">
{photo.description}
</p>
<div className="flex items-center gap-4 mt-2">
<Badge className={getStatusColor(photo.status)}>
{getStatusText(photo.status)}
</Badge>
<span className="text-xs text-muted-foreground">
{formatFileSize(photo.fileSize)}
</span>
<span className="text-xs text-muted-foreground">
{new Date(photo.createdAt).toLocaleDateString()}
</span>
</div>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
<MoreVerticalIcon className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => navigate(`/photos/${photo.id}`)}>
<EyeIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
<DropdownMenuItem onClick={() => navigate(`/photos/${photo.id}/edit`)}>
<EditIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleDeletePhoto(photo.id)}>
<TrashIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</CardContent>
</Card>
))}
</div>
)}
{/* 分页 */}
{photosData.pages > 1 && (
<div className="flex justify-center mt-8">
<div className="flex gap-2">
<Button
variant="outline"
disabled={page === 1}
onClick={() => setPage(page - 1)}
>
</Button>
<div className="flex items-center gap-2">
{[...Array(Math.min(5, photosData.pages))].map((_, i) => {
const pageNum = i + 1
return (
<Button
key={pageNum}
variant={page === pageNum ? 'default' : 'outline'}
size="sm"
onClick={() => setPage(pageNum)}
>
{pageNum}
</Button>
)
})}
</div>
<Button
variant="outline"
disabled={page === photosData.pages}
onClick={() => setPage(page + 1)}
>
</Button>
</div>
</div>
)}
</>
) : (
<Card>
<CardContent className="py-12">
<div className="text-center">
<PhotoIcon className="h-16 w-16 mx-auto mb-4 text-gray-300" />
<h3 className="text-lg font-medium mb-2"></h3>
<p className="text-muted-foreground mb-4">
</p>
<Button onClick={() => navigate('/photos/upload')}>
<PlusIcon className="h-4 w-4 mr-2" />
</Button>
</div>
</CardContent>
</Card>
)}
</div>
)
}

View File

@ -0,0 +1,640 @@
import React, { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Card, CardContent, 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 { Textarea } from '@/components/ui/textarea'
import { Switch } from '@/components/ui/switch'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import {
Settings as SettingsIcon,
Globe,
Database,
Shield,
Bell,
Palette,
Upload,
Server,
RefreshCw,
Save,
Download,
Trash2,
AlertTriangle,
CheckCircle,
XCircle,
HardDrive,
Cpu,
MemoryStick,
WifiIcon
} from 'lucide-react'
import { toast } from 'sonner'
import { settingsService } from '@/services/settingsService'
interface SystemSettings {
site: {
title: string
description: string
keywords: string
favicon?: string
logo?: string
copyright: string
contactEmail: string
}
upload: {
maxFileSize: number
allowedTypes: string[]
compressionQuality: number
watermarkEnabled: boolean
watermarkText: string
watermarkPosition: string
}
security: {
jwtSecret: string
jwtExpiration: number
enableTwoFactor: boolean
enableAuditLog: boolean
maxLoginAttempts: number
lockoutDuration: number
}
performance: {
cacheEnabled: boolean
cacheExpiration: number
imageCacheSize: number
enableCompression: boolean
maxConcurrentUploads: number
}
notifications: {
emailEnabled: boolean
emailHost: string
emailPort: number
emailUser: string
emailPassword: string
enableUserNotifications: boolean
enableSystemAlerts: boolean
}
backup: {
autoBackupEnabled: boolean
backupInterval: number
maxBackupFiles: number
backupLocation: string
}
}
interface SystemStatus {
server: {
status: 'online' | 'offline'
uptime: string
version: string
lastRestart: string
}
database: {
status: 'connected' | 'disconnected' | 'error'
version: string
size: string
lastBackup: string
}
storage: {
total: string
used: string
free: string
usage: number
}
performance: {
cpu: number
memory: number
activeConnections: number
responseTime: number
}
}
export default function Settings() {
const queryClient = useQueryClient()
const [activeTab, setActiveTab] = useState<'general' | 'upload' | 'security' | 'performance' | 'notifications' | 'backup' | 'system'>('general')
const [isDirty, setIsDirty] = useState(false)
// 获取系统设置
const { data: settings, isLoading: settingsLoading } = useQuery<SystemSettings>({
queryKey: ['settings'],
queryFn: settingsService.getSettings
})
// 获取系统状态
const { data: status, isLoading: statusLoading } = useQuery<SystemStatus>({
queryKey: ['system-status'],
queryFn: settingsService.getSystemStatus,
refetchInterval: 30000 // 30秒刷新一次
})
// 更新设置
const updateSettingsMutation = useMutation({
mutationFn: settingsService.updateSettings,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['settings'] })
setIsDirty(false)
toast.success('设置保存成功')
},
onError: (error: any) => {
toast.error(error?.message || '保存失败')
}
})
// 系统操作
const systemOperationMutation = useMutation({
mutationFn: settingsService.performSystemOperation,
onSuccess: (data, variables) => {
queryClient.invalidateQueries({ queryKey: ['system-status'] })
toast.success(`${variables.operation} 操作成功`)
},
onError: (error: any) => {
toast.error(error?.message || '操作失败')
}
})
const handleSaveSettings = () => {
if (settings) {
updateSettingsMutation.mutate(settings)
}
}
const handleSystemOperation = (operation: string) => {
if (confirm(`确定要执行 ${operation} 操作吗?`)) {
systemOperationMutation.mutate({ operation })
}
}
const updateSetting = (section: string, key: string, value: any) => {
// 这里应该更新本地状态
setIsDirty(true)
}
const tabs = [
{ id: 'general', label: '网站设置', icon: Globe },
{ id: 'upload', label: '上传设置', icon: Upload },
{ id: 'security', label: '安全设置', icon: Shield },
{ id: 'performance', label: '性能设置', icon: Cpu },
{ id: 'notifications', label: '通知设置', icon: Bell },
{ id: 'backup', label: '备份设置', icon: Database },
{ id: 'system', label: '系统状态', icon: Server }
]
const renderGeneralSettings = () => (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="site-title"></Label>
<Input
id="site-title"
value={settings?.site.title || ''}
onChange={(e) => updateSetting('site', 'title', e.target.value)}
placeholder="摄影作品集"
/>
</div>
<div>
<Label htmlFor="contact-email"></Label>
<Input
id="contact-email"
type="email"
value={settings?.site.contactEmail || ''}
onChange={(e) => updateSetting('site', 'contactEmail', e.target.value)}
placeholder="contact@example.com"
/>
</div>
</div>
<div>
<Label htmlFor="site-description"></Label>
<Textarea
id="site-description"
value={settings?.site.description || ''}
onChange={(e) => updateSetting('site', 'description', e.target.value)}
placeholder="分享摄影作品,记录美好时光"
rows={3}
/>
</div>
<div>
<Label htmlFor="site-keywords"></Label>
<Input
id="site-keywords"
value={settings?.site.keywords || ''}
onChange={(e) => updateSetting('site', 'keywords', e.target.value)}
placeholder="摄影, 作品集, 艺术, 照片"
/>
</div>
<div>
<Label htmlFor="copyright"></Label>
<Input
id="copyright"
value={settings?.site.copyright || ''}
onChange={(e) => updateSetting('site', 'copyright', e.target.value)}
placeholder="© 2024 摄影作品集. All rights reserved."
/>
</div>
</CardContent>
</Card>
</div>
)
const renderUploadSettings = () => (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="max-file-size"> (MB)</Label>
<Input
id="max-file-size"
type="number"
value={settings?.upload.maxFileSize || 10}
onChange={(e) => updateSetting('upload', 'maxFileSize', parseInt(e.target.value))}
min="1"
max="100"
/>
</div>
<div>
<Label htmlFor="compression-quality"> (%)</Label>
<Input
id="compression-quality"
type="number"
value={settings?.upload.compressionQuality || 85}
onChange={(e) => updateSetting('upload', 'compressionQuality', parseInt(e.target.value))}
min="1"
max="100"
/>
</div>
</div>
<div>
<Label></Label>
<div className="flex flex-wrap gap-2 mt-2">
{['jpg', 'jpeg', 'png', 'gif', 'webp', 'tiff', 'raw'].map(type => (
<Badge key={type} variant="outline" className="cursor-pointer">
{type.toUpperCase()}
</Badge>
))}
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center space-x-2">
<Switch
id="watermark-enabled"
checked={settings?.upload.watermarkEnabled || false}
onCheckedChange={(checked) => updateSetting('upload', 'watermarkEnabled', checked)}
/>
<Label htmlFor="watermark-enabled"></Label>
</div>
{settings?.upload.watermarkEnabled && (
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="watermark-text"></Label>
<Input
id="watermark-text"
value={settings?.upload.watermarkText || ''}
onChange={(e) => updateSetting('upload', 'watermarkText', e.target.value)}
placeholder="© 摄影师名字"
/>
</div>
<div>
<Label htmlFor="watermark-position"></Label>
<select
id="watermark-position"
value={settings?.upload.watermarkPosition || 'bottom-right'}
onChange={(e) => updateSetting('upload', 'watermarkPosition', e.target.value)}
className="w-full p-2 border rounded"
>
<option value="top-left"></option>
<option value="top-right"></option>
<option value="bottom-left"></option>
<option value="bottom-right"></option>
<option value="center"></option>
</select>
</div>
</div>
)}
</CardContent>
</Card>
</div>
)
const renderSecuritySettings = () => (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="jwt-expiration">JWT ()</Label>
<Input
id="jwt-expiration"
type="number"
value={settings?.security.jwtExpiration || 24}
onChange={(e) => updateSetting('security', 'jwtExpiration', parseInt(e.target.value))}
min="1"
max="168"
/>
</div>
<div>
<Label htmlFor="max-login-attempts"></Label>
<Input
id="max-login-attempts"
type="number"
value={settings?.security.maxLoginAttempts || 5}
onChange={(e) => updateSetting('security', 'maxLoginAttempts', parseInt(e.target.value))}
min="1"
max="10"
/>
</div>
</div>
<div className="space-y-3">
<div className="flex items-center space-x-2">
<Switch
id="enable-2fa"
checked={settings?.security.enableTwoFactor || false}
onCheckedChange={(checked) => updateSetting('security', 'enableTwoFactor', checked)}
/>
<Label htmlFor="enable-2fa"></Label>
</div>
<div className="flex items-center space-x-2">
<Switch
id="enable-audit-log"
checked={settings?.security.enableAuditLog || false}
onCheckedChange={(checked) => updateSetting('security', 'enableAuditLog', checked)}
/>
<Label htmlFor="enable-audit-log"></Label>
</div>
</div>
</CardContent>
</Card>
</div>
)
const renderSystemStatus = () => (
<div className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Server className="h-5 w-5" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
<div className="flex items-center justify-between">
<span></span>
<Badge variant={status?.server.status === 'online' ? 'default' : 'destructive'}>
{status?.server.status === 'online' ? '在线' : '离线'}
</Badge>
</div>
<div className="flex items-center justify-between">
<span></span>
<span className="text-sm text-muted-foreground">{status?.server.uptime}</span>
</div>
<div className="flex items-center justify-between">
<span></span>
<span className="text-sm text-muted-foreground">{status?.server.version}</span>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Database className="h-5 w-5" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
<div className="flex items-center justify-between">
<span></span>
<Badge variant={status?.database.status === 'connected' ? 'default' : 'destructive'}>
{status?.database.status === 'connected' ? '已连接' : '断开连接'}
</Badge>
</div>
<div className="flex items-center justify-between">
<span></span>
<span className="text-sm text-muted-foreground">{status?.database.size}</span>
</div>
<div className="flex items-center justify-between">
<span></span>
<span className="text-sm text-muted-foreground">{status?.database.lastBackup}</span>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<HardDrive className="h-5 w-5" />
使
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
<div className="flex items-center justify-between">
<span></span>
<span className="text-sm text-muted-foreground">{status?.storage.total}</span>
</div>
<div className="flex items-center justify-between">
<span>使</span>
<span className="text-sm text-muted-foreground">{status?.storage.used}</span>
</div>
<div className="flex items-center justify-between">
<span></span>
<span className="text-sm text-muted-foreground">{status?.storage.free}</span>
</div>
<div className="mt-2">
<div className="flex items-center justify-between text-sm mb-1">
<span>使</span>
<span>{status?.storage.usage}%</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-2">
<div
className="bg-blue-600 h-2 rounded-full transition-all duration-300"
style={{ width: `${status?.storage.usage}%` }}
/>
</div>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Cpu className="h-5 w-5" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
<div className="flex items-center justify-between">
<span>CPU 使</span>
<span className="text-sm text-muted-foreground">{status?.performance.cpu}%</span>
</div>
<div className="flex items-center justify-between">
<span>使</span>
<span className="text-sm text-muted-foreground">{status?.performance.memory}%</span>
</div>
<div className="flex items-center justify-between">
<span></span>
<span className="text-sm text-muted-foreground">{status?.performance.activeConnections}</span>
</div>
<div className="flex items-center justify-between">
<span></span>
<span className="text-sm text-muted-foreground">{status?.performance.responseTime}ms</span>
</div>
</div>
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<Button
variant="outline"
onClick={() => handleSystemOperation('restart')}
className="flex items-center gap-2"
>
<RefreshCw className="h-4 w-4" />
</Button>
<Button
variant="outline"
onClick={() => handleSystemOperation('backup')}
className="flex items-center gap-2"
>
<Database className="h-4 w-4" />
</Button>
<Button
variant="outline"
onClick={() => handleSystemOperation('clear-cache')}
className="flex items-center gap-2"
>
<Trash2 className="h-4 w-4" />
</Button>
<Button
variant="outline"
onClick={() => handleSystemOperation('optimize')}
className="flex items-center gap-2"
>
<Settings className="h-4 w-4" />
</Button>
</div>
</CardContent>
</Card>
</div>
)
const renderTabContent = () => {
switch (activeTab) {
case 'general':
return renderGeneralSettings()
case 'upload':
return renderUploadSettings()
case 'security':
return renderSecuritySettings()
case 'system':
return renderSystemStatus()
default:
return (
<Card>
<CardContent className="py-8">
<div className="text-center text-muted-foreground">
{activeTab} ...
</div>
</CardContent>
</Card>
)
}
}
return (
<div className="container mx-auto px-4 py-8">
{/* 页面头部 */}
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-3xl font-bold"></h1>
<p className="text-muted-foreground mt-1">
</p>
</div>
{isDirty && (
<Button
onClick={handleSaveSettings}
disabled={updateSettingsMutation.isPending}
className="flex items-center gap-2"
>
<Save className="h-4 w-4" />
</Button>
)}
</div>
<div className="flex gap-8">
{/* 左侧导航 */}
<div className="w-64 flex-shrink-0">
<Card>
<CardHeader>
<CardTitle className="text-lg"></CardTitle>
</CardHeader>
<CardContent className="p-0">
<nav className="space-y-1">
{tabs.map(tab => (
<button
key={tab.id}
onClick={() => setActiveTab(tab.id as any)}
className={`w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-accent transition-colors ${
activeTab === tab.id ? 'bg-accent text-accent-foreground' : 'text-muted-foreground'
}`}
>
<tab.icon className="h-4 w-4" />
{tab.label}
</button>
))}
</nav>
</CardContent>
</Card>
</div>
{/* 右侧内容 */}
<div className="flex-1">
{renderTabContent()}
</div>
</div>
</div>
)
}

411
admin/src/pages/Tags.tsx Normal file
View File

@ -0,0 +1,411 @@
import React, { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import {
Tag,
TagIcon,
MoreVerticalIcon,
EditIcon,
TrashIcon,
PlusIcon,
SearchIcon,
FilterIcon,
SortAscIcon,
SortDescIcon,
TrendingUpIcon,
HashIcon
} from 'lucide-react'
import { toast } from 'sonner'
import { tagService } from '@/services/tagService'
interface TagData {
id: number
name: string
color: string
description?: string
photoCount: number
isActive: boolean
createdAt: string
updatedAt: string
}
interface TagStats {
total: number
active: number
popular: number
avgPhotosPerTag: number
topTags: Array<{
name: string
photoCount: number
color: string
}>
}
export default function Tags() {
const queryClient = useQueryClient()
const [search, setSearch] = useState('')
const [sortBy, setSortBy] = useState<'name' | 'photoCount' | 'createdAt'>('name')
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc')
const [filterActive, setFilterActive] = useState<boolean | null>(null)
// 获取标签列表
const { data: tags, isLoading: tagsLoading } = useQuery<TagData[]>({
queryKey: ['tags', { search, sortBy, sortOrder, filterActive }],
queryFn: () => tagService.getTags({
search,
sortBy,
sortOrder,
isActive: filterActive
})
})
// 获取标签统计
const { data: stats, isLoading: statsLoading } = useQuery<TagStats>({
queryKey: ['tag-stats'],
queryFn: tagService.getStats
})
// 删除标签
const deleteTagMutation = useMutation({
mutationFn: tagService.deleteTag,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['tags'] })
queryClient.invalidateQueries({ queryKey: ['tag-stats'] })
toast.success('标签删除成功')
},
onError: (error: any) => {
toast.error(error?.message || '删除失败')
}
})
// 切换标签状态
const toggleTagStatusMutation = useMutation({
mutationFn: ({ id, isActive }: { id: number; isActive: boolean }) =>
tagService.updateTag(id, { isActive }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['tags'] })
queryClient.invalidateQueries({ queryKey: ['tag-stats'] })
toast.success('标签状态更新成功')
},
onError: (error: any) => {
toast.error(error?.message || '更新失败')
}
})
const handleDeleteTag = (tagId: number, photoCount: number) => {
if (photoCount > 0) {
toast.error('无法删除包含照片的标签')
return
}
if (confirm('确定要删除这个标签吗?')) {
deleteTagMutation.mutate(tagId)
}
}
const handleToggleStatus = (tagId: number, currentStatus: boolean) => {
toggleTagStatusMutation.mutate({ id: tagId, isActive: !currentStatus })
}
const toggleSort = (field: 'name' | 'photoCount' | 'createdAt') => {
if (sortBy === field) {
setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')
} else {
setSortBy(field)
setSortOrder('asc')
}
}
const filteredTags = tags?.filter(tag => {
const matchesSearch = tag.name.toLowerCase().includes(search.toLowerCase())
const matchesFilter = filterActive === null || tag.isActive === filterActive
return matchesSearch && matchesFilter
})
return (
<div className="container mx-auto px-4 py-8">
{/* 页面头部 */}
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-3xl font-bold"></h1>
<p className="text-muted-foreground mt-1">
</p>
</div>
<Button className="flex items-center gap-2">
<PlusIcon className="h-4 w-4" />
</Button>
</div>
{/* 统计卡片 */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<TagIcon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold">{stats?.total || 0}</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<TrendingUpIcon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold text-green-600">{stats?.active || 0}</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<HashIcon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold text-orange-600">{stats?.popular || 0}</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<Tag className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold text-purple-600">
{Math.round(stats?.avgPhotosPerTag || 0)}
</div>
)}
</CardContent>
</Card>
</div>
{/* 热门标签 */}
{stats?.topTags && stats.topTags.length > 0 && (
<Card className="mb-6">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<TrendingUpIcon className="h-5 w-5" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-wrap gap-2">
{stats.topTags.map((tag, index) => (
<Badge
key={index}
variant="secondary"
className="flex items-center gap-1 px-3 py-1 text-sm"
style={{ backgroundColor: tag.color + '20', color: tag.color }}
>
<TagIcon className="h-3 w-3" />
{tag.name}
<span className="text-xs opacity-70">({tag.photoCount})</span>
</Badge>
))}
</div>
</CardContent>
</Card>
)}
{/* 搜索和过滤 */}
<Card className="mb-6">
<CardContent className="pt-6">
<div className="flex flex-col sm:flex-row gap-4">
<div className="flex-1 relative">
<SearchIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
<Input
placeholder="搜索标签..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
<div className="flex gap-2">
<Button
variant={filterActive === null ? "default" : "outline"}
size="sm"
onClick={() => setFilterActive(null)}
>
<FilterIcon className="h-4 w-4 mr-1" />
</Button>
<Button
variant={filterActive === true ? "default" : "outline"}
size="sm"
onClick={() => setFilterActive(true)}
>
</Button>
<Button
variant={filterActive === false ? "default" : "outline"}
size="sm"
onClick={() => setFilterActive(false)}
>
</Button>
</div>
</div>
</CardContent>
</Card>
{/* 标签列表 */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle></CardTitle>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => toggleSort('name')}
className="flex items-center gap-1"
>
{sortBy === 'name' && (
sortOrder === 'asc' ? <SortAscIcon className="h-3 w-3" /> : <SortDescIcon className="h-3 w-3" />
)}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => toggleSort('photoCount')}
className="flex items-center gap-1"
>
{sortBy === 'photoCount' && (
sortOrder === 'asc' ? <SortAscIcon className="h-3 w-3" /> : <SortDescIcon className="h-3 w-3" />
)}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => toggleSort('createdAt')}
className="flex items-center gap-1"
>
{sortBy === 'createdAt' && (
sortOrder === 'asc' ? <SortAscIcon className="h-3 w-3" /> : <SortDescIcon className="h-3 w-3" />
)}
</Button>
</div>
</div>
</CardHeader>
<CardContent>
{tagsLoading ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{[...Array(9)].map((_, i) => (
<div key={i} className="flex items-center gap-4 p-4 border rounded-lg">
<Skeleton className="h-4 w-4 rounded-full" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
<Skeleton className="h-8 w-8" />
</div>
))}
</div>
) : filteredTags?.length ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{filteredTags.map((tag) => (
<div key={tag.id} className="flex items-center justify-between p-4 border rounded-lg hover:bg-accent/50 transition-colors">
<div className="flex items-center space-x-3">
<div
className="w-4 h-4 rounded-full border-2"
style={{ backgroundColor: tag.color }}
/>
<div>
<div className="flex items-center space-x-2">
<span className="font-medium">{tag.name}</span>
<Badge variant={tag.isActive ? 'default' : 'secondary'}>
{tag.isActive ? '启用' : '禁用'}
</Badge>
</div>
<div className="flex items-center gap-2 mt-1">
<Badge variant="outline" className="text-xs">
{tag.photoCount}
</Badge>
<span className="text-xs text-muted-foreground">
{new Date(tag.createdAt).toLocaleDateString()}
</span>
</div>
{tag.description && (
<p className="text-sm text-muted-foreground mt-1">{tag.description}</p>
)}
</div>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm">
<MoreVerticalIcon className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem>
<EditIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleToggleStatus(tag.id, tag.isActive)}
>
{tag.isActive ? '禁用' : '启用'}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleDeleteTag(tag.id, tag.photoCount)}
disabled={tag.photoCount > 0}
className="text-red-600"
>
<TrashIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
))}
</div>
) : (
<div className="text-center py-12">
<TagIcon className="h-16 w-16 mx-auto mb-4 text-gray-300" />
<h3 className="text-lg font-medium mb-2">
{search ? '没有找到匹配的标签' : '暂无标签'}
</h3>
<p className="text-muted-foreground mb-4">
{search ? '尝试调整搜索条件' : '创建您的第一个标签来标记照片'}
</p>
<Button>
<PlusIcon className="h-4 w-4 mr-2" />
</Button>
</div>
)}
</CardContent>
</Card>
</div>
)
}

499
admin/src/pages/Users.tsx Normal file
View File

@ -0,0 +1,499 @@
import React, { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import {
Users as UsersIcon,
User,
MoreVerticalIcon,
EditIcon,
TrashIcon,
PlusIcon,
SearchIcon,
FilterIcon,
ShieldIcon,
UserCheckIcon,
UserXIcon,
MailIcon,
CalendarIcon,
CrownIcon
} from 'lucide-react'
import { toast } from 'sonner'
import { userService } from '@/services/userService'
interface UserData {
id: number
username: string
email: string
role: 'admin' | 'editor' | 'viewer'
isActive: boolean
lastLoginAt?: string
createdAt: string
updatedAt: string
profile?: {
firstName?: string
lastName?: string
avatar?: string
}
}
interface UserStats {
total: number
active: number
admins: number
editors: number
viewers: number
recentLogins: number
}
export default function Users() {
const queryClient = useQueryClient()
const [search, setSearch] = useState('')
const [roleFilter, setRoleFilter] = useState<string | null>(null)
const [statusFilter, setStatusFilter] = useState<boolean | null>(null)
// 获取用户列表
const { data: users, isLoading: usersLoading } = useQuery<UserData[]>({
queryKey: ['users', { search, roleFilter, statusFilter }],
queryFn: () => userService.getUsers({
search,
role: roleFilter,
isActive: statusFilter
})
})
// 获取用户统计
const { data: stats, isLoading: statsLoading } = useQuery<UserStats>({
queryKey: ['user-stats'],
queryFn: userService.getStats
})
// 删除用户
const deleteUserMutation = useMutation({
mutationFn: userService.deleteUser,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['users'] })
queryClient.invalidateQueries({ queryKey: ['user-stats'] })
toast.success('用户删除成功')
},
onError: (error: any) => {
toast.error(error?.message || '删除失败')
}
})
// 切换用户状态
const toggleUserStatusMutation = useMutation({
mutationFn: ({ id, isActive }: { id: number; isActive: boolean }) =>
userService.updateUser(id, { isActive }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['users'] })
queryClient.invalidateQueries({ queryKey: ['user-stats'] })
toast.success('用户状态更新成功')
},
onError: (error: any) => {
toast.error(error?.message || '更新失败')
}
})
// 更新用户角色
const updateRoleMutation = useMutation({
mutationFn: ({ id, role }: { id: number; role: string }) =>
userService.updateUser(id, { role }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['users'] })
queryClient.invalidateQueries({ queryKey: ['user-stats'] })
toast.success('用户角色更新成功')
},
onError: (error: any) => {
toast.error(error?.message || '更新失败')
}
})
const handleDeleteUser = (userId: number, username: string) => {
if (confirm(`确定要删除用户 "${username}" 吗?`)) {
deleteUserMutation.mutate(userId)
}
}
const handleToggleStatus = (userId: number, currentStatus: boolean) => {
toggleUserStatusMutation.mutate({ id: userId, isActive: !currentStatus })
}
const handleUpdateRole = (userId: number, newRole: string) => {
updateRoleMutation.mutate({ id: userId, role: newRole })
}
const getRoleColor = (role: string) => {
switch (role) {
case 'admin':
return 'bg-red-100 text-red-800'
case 'editor':
return 'bg-blue-100 text-blue-800'
case 'viewer':
return 'bg-green-100 text-green-800'
default:
return 'bg-gray-100 text-gray-800'
}
}
const getRoleIcon = (role: string) => {
switch (role) {
case 'admin':
return <CrownIcon className="h-3 w-3" />
case 'editor':
return <EditIcon className="h-3 w-3" />
case 'viewer':
return <UserCheckIcon className="h-3 w-3" />
default:
return <User className="h-3 w-3" />
}
}
const filteredUsers = users?.filter(user => {
const matchesSearch = user.username.toLowerCase().includes(search.toLowerCase()) ||
user.email.toLowerCase().includes(search.toLowerCase())
const matchesRole = roleFilter === null || user.role === roleFilter
const matchesStatus = statusFilter === null || user.isActive === statusFilter
return matchesSearch && matchesRole && matchesStatus
})
return (
<div className="container mx-auto px-4 py-8">
{/* 页面头部 */}
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-3xl font-bold"></h1>
<p className="text-muted-foreground mt-1">
</p>
</div>
<Button className="flex items-center gap-2">
<PlusIcon className="h-4 w-4" />
</Button>
</div>
{/* 统计卡片 */}
<div className="grid grid-cols-1 md:grid-cols-6 gap-6 mb-8">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<UsersIcon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold">{stats?.total || 0}</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<UserCheckIcon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold text-green-600">{stats?.active || 0}</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<CrownIcon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold text-red-600">{stats?.admins || 0}</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<EditIcon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold text-blue-600">{stats?.editors || 0}</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">访</CardTitle>
<User className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold text-green-600">{stats?.viewers || 0}</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium"></CardTitle>
<CalendarIcon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-20" />
) : (
<div className="text-2xl font-bold text-purple-600">{stats?.recentLogins || 0}</div>
)}
</CardContent>
</Card>
</div>
{/* 搜索和过滤 */}
<Card className="mb-6">
<CardContent className="pt-6">
<div className="flex flex-col sm:flex-row gap-4">
<div className="flex-1 relative">
<SearchIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
<Input
placeholder="搜索用户名或邮箱..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
<div className="flex gap-2">
<Button
variant={roleFilter === null ? "default" : "outline"}
size="sm"
onClick={() => setRoleFilter(null)}
>
<FilterIcon className="h-4 w-4 mr-1" />
</Button>
<Button
variant={roleFilter === 'admin' ? "default" : "outline"}
size="sm"
onClick={() => setRoleFilter('admin')}
>
<CrownIcon className="h-4 w-4 mr-1" />
</Button>
<Button
variant={roleFilter === 'editor' ? "default" : "outline"}
size="sm"
onClick={() => setRoleFilter('editor')}
>
<EditIcon className="h-4 w-4 mr-1" />
</Button>
<Button
variant={roleFilter === 'viewer' ? "default" : "outline"}
size="sm"
onClick={() => setRoleFilter('viewer')}
>
<User className="h-4 w-4 mr-1" />
访
</Button>
</div>
<div className="flex gap-2">
<Button
variant={statusFilter === null ? "default" : "outline"}
size="sm"
onClick={() => setStatusFilter(null)}
>
</Button>
<Button
variant={statusFilter === true ? "default" : "outline"}
size="sm"
onClick={() => setStatusFilter(true)}
>
<UserCheckIcon className="h-4 w-4 mr-1" />
</Button>
<Button
variant={statusFilter === false ? "default" : "outline"}
size="sm"
onClick={() => setStatusFilter(false)}
>
<UserXIcon className="h-4 w-4 mr-1" />
</Button>
</div>
</div>
</CardContent>
</Card>
{/* 用户列表 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
{usersLoading ? (
<div className="space-y-4">
{[...Array(5)].map((_, i) => (
<div key={i} className="flex items-center gap-4 p-4 border rounded-lg">
<Skeleton className="h-12 w-12 rounded-full" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-3 w-48" />
<div className="flex gap-2">
<Skeleton className="h-6 w-16" />
<Skeleton className="h-6 w-16" />
</div>
</div>
<Skeleton className="h-8 w-8" />
</div>
))}
</div>
) : filteredUsers?.length ? (
<div className="space-y-4">
{filteredUsers.map((user) => (
<div key={user.id} className="flex items-center justify-between p-4 border rounded-lg hover:bg-accent/50 transition-colors">
<div className="flex items-center space-x-4">
<Avatar className="h-12 w-12">
<AvatarImage src={user.profile?.avatar} />
<AvatarFallback>
{user.profile?.firstName?.[0] || user.username[0].toUpperCase()}
</AvatarFallback>
</Avatar>
<div>
<div className="flex items-center space-x-2">
<span className="font-medium">{user.username}</span>
<Badge variant={user.isActive ? 'default' : 'secondary'}>
{user.isActive ? '启用' : '禁用'}
</Badge>
<Badge className={getRoleColor(user.role)}>
{getRoleIcon(user.role)}
<span className="ml-1">
{user.role === 'admin' ? '管理员' :
user.role === 'editor' ? '编辑员' : '访客'}
</span>
</Badge>
</div>
<div className="flex items-center gap-4 mt-1 text-sm text-muted-foreground">
<div className="flex items-center gap-1">
<MailIcon className="h-3 w-3" />
{user.email}
</div>
<div className="flex items-center gap-1">
<CalendarIcon className="h-3 w-3" />
{new Date(user.createdAt).toLocaleDateString()}
</div>
{user.lastLoginAt && (
<div className="flex items-center gap-1">
<UserCheckIcon className="h-3 w-3" />
{new Date(user.lastLoginAt).toLocaleDateString()}
</div>
)}
</div>
</div>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm">
<MoreVerticalIcon className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem>
<EditIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
<DropdownMenuItem>
<ShieldIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleToggleStatus(user.id, user.isActive)}
>
{user.isActive ? (
<>
<UserXIcon className="h-4 w-4 mr-2" />
</>
) : (
<>
<UserCheckIcon className="h-4 w-4 mr-2" />
</>
)}
</DropdownMenuItem>
{user.role !== 'admin' && (
<>
<DropdownMenuItem
onClick={() => handleUpdateRole(user.id, 'admin')}
>
<CrownIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleUpdateRole(user.id, 'editor')}
>
<EditIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleUpdateRole(user.id, 'viewer')}
>
<User className="h-4 w-4 mr-2" />
访
</DropdownMenuItem>
</>
)}
<DropdownMenuItem
onClick={() => handleDeleteUser(user.id, user.username)}
className="text-red-600"
disabled={user.role === 'admin'} // 防止删除管理员
>
<TrashIcon className="h-4 w-4 mr-2" />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
))}
</div>
) : (
<div className="text-center py-12">
<UsersIcon className="h-16 w-16 mx-auto mb-4 text-gray-300" />
<h3 className="text-lg font-medium mb-2">
{search ? '没有找到匹配的用户' : '暂无用户'}
</h3>
<p className="text-muted-foreground mb-4">
{search ? '尝试调整搜索条件' : '创建您的第一个用户'}
</p>
<Button>
<PlusIcon className="h-4 w-4 mr-2" />
</Button>
</div>
)}
</CardContent>
</Card>
</div>
)
}

52
admin/src/services/api.ts Normal file
View File

@ -0,0 +1,52 @@
import axios from 'axios'
import { useAuthStore } from '@/stores/authStore'
import { toast } from 'sonner'
const api = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api',
timeout: 30000,
headers: {
'Content-Type': 'application/json',
},
})
// 请求拦截器
api.interceptors.request.use(
(config) => {
const { token } = useAuthStore.getState()
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
(error) => {
return Promise.reject(error)
}
)
// 响应拦截器
api.interceptors.response.use(
(response) => {
return response
},
(error) => {
const message = error.response?.data?.message || error.message || '请求失败'
// 显示错误提示
if (error.response?.status !== 401) {
toast.error(message)
}
// 401 错误自动跳转登录
if (error.response?.status === 401) {
const { logout } = useAuthStore.getState()
logout()
window.location.href = '/login'
toast.error('登录已过期,请重新登录')
}
return Promise.reject(error)
}
)
export default api

View File

@ -0,0 +1,85 @@
import api from './api'
export interface LoginRequest {
username: string
password: string
}
export interface LoginResponse {
user: User
access_token: string
refresh_token: string
expires_in: number
}
export interface User {
id: number
username: string
email: string
role: string
is_active: boolean
created_at: string
updated_at: string
}
export interface RefreshTokenRequest {
refresh_token: string
}
export interface RefreshTokenResponse {
access_token: string
refresh_token: string
expires_in: number
}
export interface ChangePasswordRequest {
old_password: string
new_password: string
}
export interface UpdateProfileRequest {
username?: string
email?: string
}
class AuthService {
async login(credentials: LoginRequest): Promise<LoginResponse> {
const response = await api.post('/auth/login', credentials)
return response.data
}
async logout(): Promise<void> {
await api.post('/auth/logout')
}
async refreshToken(refreshToken: string): Promise<RefreshTokenResponse> {
const response = await api.post('/auth/refresh', { refresh_token: refreshToken })
return response.data
}
async getCurrentUser(): Promise<User> {
const response = await api.get('/me')
return response.data
}
async updateProfile(data: UpdateProfileRequest): Promise<User> {
const response = await api.put('/me', data)
return response.data
}
async changePassword(data: ChangePasswordRequest): Promise<void> {
await api.put('/auth/password', data)
}
async checkUsernameAvailability(username: string): Promise<boolean> {
const response = await api.get(`/auth/check-username/${username}`)
return response.data.available
}
async checkEmailAvailability(email: string): Promise<boolean> {
const response = await api.get(`/auth/check-email/${email}`)
return response.data.available
}
}
export const authService = new AuthService()

View File

@ -0,0 +1,94 @@
import api from './api'
export interface Category {
id: number
name: string
slug: string
description: string
parentId?: number
sortOrder: number
isActive: boolean
photoCount: number
createdAt: string
updatedAt: string
}
export interface CategoryTree extends Category {
children: CategoryTree[]
}
export interface CreateCategoryRequest {
name: string
slug: string
description?: string
parentId?: number
}
export interface UpdateCategoryRequest {
name?: string
slug?: string
description?: string
parentId?: number
sortOrder?: number
isActive?: boolean
}
export interface CategoryStats {
total: number
active: number
topLevel: number
photoCounts: Record<string, number>
}
class CategoryService {
async getCategories(parentId?: number): Promise<Category[]> {
const params = parentId ? { parent_id: parentId } : {}
const response = await api.get('/categories', { params })
return response.data
}
async getCategoryTree(): Promise<CategoryTree[]> {
const response = await api.get('/categories/tree')
return response.data
}
async getCategory(id: number): Promise<Category> {
const response = await api.get(`/categories/${id}`)
return response.data
}
async getCategoryBySlug(slug: string): Promise<Category> {
const response = await api.get(`/categories/slug/${slug}`)
return response.data
}
async createCategory(data: CreateCategoryRequest): Promise<Category> {
const response = await api.post('/categories', data)
return response.data
}
async updateCategory(id: number, data: UpdateCategoryRequest): Promise<Category> {
const response = await api.put(`/categories/${id}`, data)
return response.data
}
async deleteCategory(id: number): Promise<void> {
await api.delete(`/categories/${id}`)
}
async reorderCategories(parentId: number | null, categoryIds: number[]): Promise<void> {
await api.post('/categories/reorder', { parentId, categoryIds })
}
async getStats(): Promise<CategoryStats> {
const response = await api.get('/categories/stats')
return response.data
}
async generateSlug(name: string): Promise<string> {
const response = await api.post('/categories/generate-slug', { name })
return response.data.slug
}
}
export const categoryService = new CategoryService()

View File

@ -0,0 +1,184 @@
import api from './api'
export interface Photo {
id: number
title: string
description: string
originalFilename: string
uniqueFilename: string
fileSize: number
status: 'draft' | 'published' | 'archived' | 'processing'
camera?: string
lens?: string
iso?: number
aperture?: string
shutterSpeed?: string
focalLength?: string
takenAt?: string
createdAt: string
updatedAt: string
categories: Category[]
tags: Tag[]
formats: PhotoFormat[]
}
export interface PhotoFormat {
id: number
photoId: number
format: string
width: number
height: number
quality: number
fileSize: number
url: string
createdAt: string
}
export interface Category {
id: number
name: string
slug: string
description: string
photoCount: number
}
export interface Tag {
id: number
name: string
slug: string
description: string
color?: string
photoCount: number
}
export interface PhotoListParams {
page?: number
limit?: number
search?: string
status?: string
category_id?: number
tags?: string[]
start_date?: string
end_date?: string
sort_by?: string
sort_order?: string
}
export interface PhotoListResponse {
photos: Photo[]
total: number
page: number
limit: number
pages: number
}
export interface CreatePhotoRequest {
title: string
description?: string
status?: string
categoryIds?: number[]
tagIds?: number[]
camera?: string
lens?: string
iso?: number
aperture?: string
shutterSpeed?: string
focalLength?: string
takenAt?: string
}
export interface UpdatePhotoRequest {
title?: string
description?: string
status?: string
categoryIds?: number[]
tagIds?: number[]
camera?: string
lens?: string
iso?: number
aperture?: string
shutterSpeed?: string
focalLength?: string
takenAt?: string
}
export interface BatchUpdateRequest {
status?: string
categoryIds?: number[]
tagIds?: number[]
}
export interface PhotoStats {
total: number
thisMonth: number
today: number
totalSize: number
statusStats: Record<string, number>
}
class PhotoService {
async getPhotos(params: PhotoListParams = {}): Promise<PhotoListResponse> {
const response = await api.get('/photos', { params })
return response.data
}
async getPhoto(id: number): Promise<Photo> {
const response = await api.get(`/photos/${id}`)
return response.data
}
async createPhoto(data: CreatePhotoRequest): Promise<Photo> {
const response = await api.post('/photos', data)
return response.data
}
async updatePhoto(id: number, data: UpdatePhotoRequest): Promise<Photo> {
const response = await api.put(`/photos/${id}`, data)
return response.data
}
async deletePhoto(id: number): Promise<void> {
await api.delete(`/photos/${id}`)
}
async uploadPhoto(file: File, data: CreatePhotoRequest): Promise<Photo> {
const formData = new FormData()
formData.append('file', file)
// 添加其他字段
if (data.title) formData.append('title', data.title)
if (data.description) formData.append('description', data.description)
if (data.status) formData.append('status', data.status)
if (data.categoryIds) formData.append('category_ids', data.categoryIds.join(','))
if (data.tagIds) formData.append('tag_ids', data.tagIds.join(','))
if (data.camera) formData.append('camera', data.camera)
if (data.lens) formData.append('lens', data.lens)
if (data.iso) formData.append('iso', data.iso.toString())
if (data.aperture) formData.append('aperture', data.aperture)
if (data.shutterSpeed) formData.append('shutter_speed', data.shutterSpeed)
if (data.focalLength) formData.append('focal_length', data.focalLength)
if (data.takenAt) formData.append('taken_at', data.takenAt)
const response = await api.post('/photos/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
return response.data
}
async batchUpdate(ids: number[], data: BatchUpdateRequest): Promise<void> {
await api.post('/photos/batch/update', { ids, ...data })
}
async batchDelete(ids: number[]): Promise<void> {
await api.post('/photos/batch/delete', { ids })
}
async getStats(): Promise<PhotoStats> {
const response = await api.get('/photos/stats')
return response.data
}
}
export const photoService = new PhotoService()

View File

@ -0,0 +1,240 @@
import api from './api'
interface SystemSettings {
site: {
title: string
description: string
keywords: string
favicon?: string
logo?: string
copyright: string
contactEmail: string
}
upload: {
maxFileSize: number
allowedTypes: string[]
compressionQuality: number
watermarkEnabled: boolean
watermarkText: string
watermarkPosition: string
}
security: {
jwtSecret: string
jwtExpiration: number
enableTwoFactor: boolean
enableAuditLog: boolean
maxLoginAttempts: number
lockoutDuration: number
}
performance: {
cacheEnabled: boolean
cacheExpiration: number
imageCacheSize: number
enableCompression: boolean
maxConcurrentUploads: number
}
notifications: {
emailEnabled: boolean
emailHost: string
emailPort: number
emailUser: string
emailPassword: string
enableUserNotifications: boolean
enableSystemAlerts: boolean
}
backup: {
autoBackupEnabled: boolean
backupInterval: number
maxBackupFiles: number
backupLocation: string
}
}
interface SystemStatus {
server: {
status: 'online' | 'offline'
uptime: string
version: string
lastRestart: string
}
database: {
status: 'connected' | 'disconnected' | 'error'
version: string
size: string
lastBackup: string
}
storage: {
total: string
used: string
free: string
usage: number
}
performance: {
cpu: number
memory: number
activeConnections: number
responseTime: number
}
}
interface SystemOperation {
operation: string
}
export const settingsService = {
// 获取系统设置
getSettings: async (): Promise<SystemSettings> => {
const response = await api.get('/settings')
return response.data
},
// 更新系统设置
updateSettings: async (settings: Partial<SystemSettings>): Promise<SystemSettings> => {
const response = await api.put('/settings', settings)
return response.data
},
// 获取系统状态
getSystemStatus: async (): Promise<SystemStatus> => {
const response = await api.get('/system/status')
return response.data
},
// 执行系统操作
performSystemOperation: async (operation: SystemOperation): Promise<any> => {
const response = await api.post('/system/operation', operation)
return response.data
},
// 获取配置项
getConfig: async (key: string): Promise<any> => {
const response = await api.get(`/settings/config/${key}`)
return response.data
},
// 更新配置项
updateConfig: async (key: string, value: any): Promise<void> => {
await api.put(`/settings/config/${key}`, { value })
},
// 重置配置
resetConfig: async (section?: string): Promise<void> => {
await api.post('/settings/reset', { section })
},
// 导出配置
exportConfig: async (): Promise<Blob> => {
const response = await api.get('/settings/export', { responseType: 'blob' })
return response.data
},
// 导入配置
importConfig: async (file: File): Promise<void> => {
const formData = new FormData()
formData.append('config', file)
await api.post('/settings/import', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
})
},
// 获取系统日志
getSystemLogs: async (params: { level?: string; limit?: number; offset?: number }): Promise<any[]> => {
const response = await api.get('/system/logs', { params })
return response.data
},
// 清理系统日志
clearSystemLogs: async (): Promise<void> => {
await api.delete('/system/logs')
},
// 获取系统健康检查
getHealthCheck: async (): Promise<any> => {
const response = await api.get('/system/health')
return response.data
},
// 获取系统信息
getSystemInfo: async (): Promise<any> => {
const response = await api.get('/system/info')
return response.data
},
// 获取备份列表
getBackups: async (): Promise<any[]> => {
const response = await api.get('/system/backups')
return response.data
},
// 创建备份
createBackup: async (): Promise<any> => {
const response = await api.post('/system/backups')
return response.data
},
// 删除备份
deleteBackup: async (id: string): Promise<void> => {
await api.delete(`/system/backups/${id}`)
},
// 恢复备份
restoreBackup: async (id: string): Promise<void> => {
await api.post(`/system/backups/${id}/restore`)
},
// 下载备份
downloadBackup: async (id: string): Promise<Blob> => {
const response = await api.get(`/system/backups/${id}/download`, { responseType: 'blob' })
return response.data
},
// 获取缓存统计
getCacheStats: async (): Promise<any> => {
const response = await api.get('/system/cache/stats')
return response.data
},
// 清理缓存
clearCache: async (type?: string): Promise<void> => {
await api.delete('/system/cache', { params: { type } })
},
// 获取存储统计
getStorageStats: async (): Promise<any> => {
const response = await api.get('/system/storage/stats')
return response.data
},
// 清理存储
cleanStorage: async (type?: string): Promise<void> => {
await api.delete('/system/storage/cleanup', { params: { type } })
},
// 获取任务列表
getTasks: async (): Promise<any[]> => {
const response = await api.get('/system/tasks')
return response.data
},
// 创建任务
createTask: async (task: any): Promise<any> => {
const response = await api.post('/system/tasks', task)
return response.data
},
// 删除任务
deleteTask: async (id: string): Promise<void> => {
await api.delete(`/system/tasks/${id}`)
},
// 执行任务
executeTask: async (id: string): Promise<void> => {
await api.post(`/system/tasks/${id}/execute`)
},
// 获取任务日志
getTaskLogs: async (id: string): Promise<any[]> => {
const response = await api.get(`/system/tasks/${id}/logs`)
return response.data
}
}

View File

@ -0,0 +1,131 @@
import api from './api'
export interface Tag {
id: number
name: string
slug: string
description: string
color?: string
isActive: boolean
photoCount: number
createdAt: string
updatedAt: string
}
export interface TagWithCount extends Tag {
photoCount: number
}
export interface TagCloudItem {
name: string
slug: string
color?: string
count: number
}
export interface TagListParams {
page?: number
limit?: number
search?: string
isActive?: boolean
sortBy?: string
sortOrder?: string
}
export interface TagListResponse {
tags: Tag[]
total: number
page: number
limit: number
pages: number
}
export interface CreateTagRequest {
name: string
slug: string
description?: string
color?: string
}
export interface UpdateTagRequest {
name?: string
slug?: string
description?: string
color?: string
isActive?: boolean
}
export interface TagStats {
total: number
active: number
used: number
unused: number
avgPhotosPerTag: number
}
class TagService {
async getTags(params: TagListParams = {}): Promise<TagListResponse> {
const response = await api.get('/tags', { params })
return response.data
}
async getAllTags(): Promise<Tag[]> {
const response = await api.get('/tags/all')
return response.data
}
async getTag(id: number): Promise<Tag> {
const response = await api.get(`/tags/${id}`)
return response.data
}
async getTagBySlug(slug: string): Promise<Tag> {
const response = await api.get(`/tags/slug/${slug}`)
return response.data
}
async createTag(data: CreateTagRequest): Promise<Tag> {
const response = await api.post('/tags', data)
return response.data
}
async updateTag(id: number, data: UpdateTagRequest): Promise<Tag> {
const response = await api.put(`/tags/${id}`, data)
return response.data
}
async deleteTag(id: number): Promise<void> {
await api.delete(`/tags/${id}`)
}
async batchDelete(ids: number[]): Promise<void> {
await api.post('/tags/batch/delete', { ids })
}
async getPopularTags(limit: number = 10): Promise<TagWithCount[]> {
const response = await api.get('/tags/popular', { params: { limit } })
return response.data
}
async getTagCloud(): Promise<TagCloudItem[]> {
const response = await api.get('/tags/cloud')
return response.data
}
async getStats(): Promise<TagStats> {
const response = await api.get('/tags/stats')
return response.data
}
async searchTags(query: string, limit: number = 10): Promise<Tag[]> {
const response = await api.get('/tags/search', { params: { q: query, limit } })
return response.data
}
async generateSlug(name: string): Promise<string> {
const response = await api.post('/tags/generate-slug', { name })
return response.data.slug
}
}
export const tagService = new TagService()

View File

@ -0,0 +1,157 @@
import api from './api'
interface User {
id: number
username: string
email: string
role: 'admin' | 'editor' | 'viewer'
isActive: boolean
lastLoginAt?: string
createdAt: string
updatedAt: string
profile?: {
firstName?: string
lastName?: string
avatar?: string
}
}
interface UserListParams {
search?: string
role?: string | null
isActive?: boolean | null
page?: number
limit?: number
}
interface UserCreateData {
username: string
email: string
password: string
role?: string
isActive?: boolean
profile?: {
firstName?: string
lastName?: string
}
}
interface UserUpdateData {
username?: string
email?: string
password?: string
role?: string
isActive?: boolean
profile?: {
firstName?: string
lastName?: string
avatar?: string
}
}
interface UserStats {
total: number
active: number
admins: number
editors: number
viewers: number
recentLogins: number
}
export const userService = {
// 获取用户列表
getUsers: async (params: UserListParams = {}): Promise<User[]> => {
const response = await api.get('/users', { params })
return response.data
},
// 获取用户统计
getStats: async (): Promise<UserStats> => {
const response = await api.get('/users/stats')
return response.data
},
// 创建用户
createUser: async (data: UserCreateData): Promise<User> => {
const response = await api.post('/users', data)
return response.data
},
// 更新用户
updateUser: async (id: number, data: UserUpdateData): Promise<User> => {
const response = await api.put(`/users/${id}`, data)
return response.data
},
// 删除用户
deleteUser: async (id: number): Promise<void> => {
await api.delete(`/users/${id}`)
},
// 获取用户详情
getUser: async (id: number): Promise<User> => {
const response = await api.get(`/users/${id}`)
return response.data
},
// 批量删除用户
deleteUsers: async (ids: number[]): Promise<void> => {
await api.delete('/users/batch', { data: { ids } })
},
// 批量更新用户状态
updateUsersStatus: async (ids: number[], isActive: boolean): Promise<void> => {
await api.put('/users/batch/status', { ids, isActive })
},
// 重置用户密码
resetPassword: async (id: number): Promise<string> => {
const response = await api.post(`/users/${id}/reset-password`)
return response.data.newPassword
},
// 更改用户角色
updateUserRole: async (id: number, role: string): Promise<User> => {
const response = await api.put(`/users/${id}/role`, { role })
return response.data
},
// 获取用户活动日志
getUserActivity: async (id: number): Promise<any[]> => {
const response = await api.get(`/users/${id}/activity`)
return response.data
},
// 获取最近登录用户
getRecentLogins: async (limit: number = 10): Promise<User[]> => {
const response = await api.get('/users/recent-logins', { params: { limit } })
return response.data
},
// 检查用户名是否可用
checkUsername: async (username: string): Promise<boolean> => {
const response = await api.get('/users/check-username', { params: { username } })
return response.data.available
},
// 检查邮箱是否可用
checkEmail: async (email: string): Promise<boolean> => {
const response = await api.get('/users/check-email', { params: { email } })
return response.data.available
},
// 发送验证邮件
sendVerificationEmail: async (id: number): Promise<void> => {
await api.post(`/users/${id}/send-verification`)
},
// 激活用户账号
activateUser: async (id: number): Promise<void> => {
await api.post(`/users/${id}/activate`)
},
// 停用用户账号
deactivateUser: async (id: number): Promise<void> => {
await api.post(`/users/${id}/deactivate`)
}
}

View File

@ -0,0 +1,59 @@
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
export interface User {
id: number
username: string
email: string
role: string
isActive: boolean
createdAt: string
updatedAt: string
}
interface AuthState {
user: User | null
token: string | null
isAuthenticated: boolean
login: (token: string, user: User) => void
logout: () => void
updateUser: (user: User) => void
}
export const useAuthStore = create<AuthState>()(
persist(
(set, get) => ({
user: null,
token: null,
isAuthenticated: false,
login: (token: string, user: User) => {
set({
token,
user,
isAuthenticated: true,
})
},
logout: () => {
set({
token: null,
user: null,
isAuthenticated: false,
})
},
updateUser: (user: User) => {
set({ user })
},
}),
{
name: 'auth-storage',
partialize: (state) => ({
token: state.token,
user: state.user,
isAuthenticated: state.isAuthenticated,
}),
}
)
)