更新系统功能:新增部门管理、平台管理API,优化上传功能和网络检测,更新数据库架构

This commit is contained in:
chenpei 2025-11-07 19:05:34 +08:00
parent 383772d39f
commit 134abfc0a3
14 changed files with 1355 additions and 337 deletions

View File

@ -15,6 +15,7 @@ interface User {
role: string
isActive: boolean
canDownload: boolean
managedDepartment?: string
createdAt: string
_count: {
materials: number
@ -48,6 +49,12 @@ interface Scene {
count: number
}
interface Platform {
id: string
name: string
count: number
}
export default function AdminPage() {
const { data: session, status } = useSession()
const router = useRouter()
@ -56,14 +63,18 @@ export default function AdminPage() {
const [users, setUsers] = useState<User[]>([])
const [categories, setCategories] = useState<Category[]>([])
const [scenes, setScenes] = useState<Scene[]>([])
const [platforms, setPlatforms] = useState<Platform[]>([])
const [loading, setLoading] = useState(true)
const [editingMaterial, setEditingMaterial] = useState<Material | null>(null)
const [editingCategory, setEditingCategory] = useState<Category | null>(null)
const [editingScene, setEditingScene] = useState<Scene | null>(null)
const [editingPlatform, setEditingPlatform] = useState<Platform | null>(null)
const [showAddCategoryModal, setShowAddCategoryModal] = useState(false)
const [showAddSceneModal, setShowAddSceneModal] = useState(false)
const [showAddPlatformModal, setShowAddPlatformModal] = useState(false)
const [newCategoryName, setNewCategoryName] = useState('')
const [newSceneName, setNewSceneName] = useState('')
const [newPlatformName, setNewPlatformName] = useState('')
const [toast, setToast] = useState<{message: string, type: 'success' | 'error'} | null>(null)
// 编辑用户部门
@ -75,6 +86,16 @@ export default function AdminPage() {
const [newDepartmentName, setNewDepartmentName] = useState('')
const [addingDepartment, setAddingDepartment] = useState(false)
// 用户搜索
const [userSearchTerm, setUserSearchTerm] = useState('')
// 素材搜索
const [materialSearchTerm, setMaterialSearchTerm] = useState('')
// 部门折叠状态
const [collapsedDepartments, setCollapsedDepartments] = useState<Set<string>>(new Set())
const [collapsedAdmins, setCollapsedAdmins] = useState<Set<string>>(new Set())
// Toast自动隐藏
useEffect(() => {
if (toast) {
@ -125,9 +146,10 @@ export default function AdminPage() {
// 加载部门列表
fetchDepartments()
} else if (activeTab === 'categories') {
const [categoriesRes, scenesRes] = await Promise.all([
const [categoriesRes, scenesRes, platformsRes] = await Promise.all([
fetch('/api/categories'),
fetch('/api/scenes')
fetch('/api/scenes'),
fetch('/api/platforms')
])
if (categoriesRes.ok) {
const data = await categoriesRes.json()
@ -137,6 +159,10 @@ export default function AdminPage() {
const data = await scenesRes.json()
setScenes(data)
}
if (platformsRes.ok) {
const data = await platformsRes.json()
setPlatforms(data)
}
} else if (activeTab === 'departments') {
fetchDepartments()
}
@ -580,6 +606,169 @@ export default function AdminPage() {
}
}
// 平台分类管理函数
const handleAddPlatform = async () => {
if (!newPlatformName.trim()) {
showToast('平台名称不能为空', 'error')
return
}
try {
const response = await fetch('/api/platforms', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: newPlatformName.trim() }),
})
if (response.ok) {
const data = await response.json()
setPlatforms(prevPlatforms => [...prevPlatforms, { id: data.id, name: newPlatformName.trim(), count: 0 }])
setShowAddPlatformModal(false)
setNewPlatformName('')
showToast('添加成功')
} else {
const data = await response.json()
showToast(data.error || '添加失败', 'error')
}
} catch (error) {
console.error('Error adding platform:', error)
showToast('添加失败', 'error')
}
}
const handleUpdatePlatform = async (id: string, newName: string) => {
if (!newName.trim()) {
showToast('平台名称不能为空', 'error')
return
}
try {
const response = await fetch('/api/platforms', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ id, name: newName.trim() }),
})
if (response.ok) {
setPlatforms(prevPlatforms =>
prevPlatforms.map(platform =>
platform.id === id ? { ...platform, name: newName.trim() } : platform
)
)
setEditingPlatform(null)
showToast('修改成功')
} else {
const data = await response.json()
showToast(data.error || '修改失败', 'error')
}
} catch (error) {
console.error('Error updating platform:', error)
showToast('修改失败', 'error')
}
}
const handleDeletePlatform = async (id: string) => {
if (!confirm('确定要删除这个平台分类吗?')) return
try {
const response = await fetch(`/api/platforms?id=${id}`, {
method: 'DELETE',
})
if (response.ok) {
setPlatforms(prevPlatforms => prevPlatforms.filter(platform => platform.id !== id))
showToast('删除成功')
} else {
const data = await response.json()
showToast(data.error || '删除失败', 'error')
}
} catch (error) {
console.error('Error deleting platform:', error)
showToast('删除失败', 'error')
}
}
// 设置部门管理员
const handleSetDepartmentManager = async (userId: string, departmentName: string) => {
try {
const response = await fetch('/api/admin/users/set-department-manager', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ userId, departmentName }),
})
if (response.ok) {
await fetchData() // 重新加载用户数据
showToast('部门管理员设置成功')
} else {
const data = await response.json()
showToast(data.error || '设置失败', 'error')
}
} catch (error) {
console.error('Set department manager error:', error)
showToast('设置失败', 'error')
}
}
// 切换部门折叠状态
const toggleDepartmentCollapse = (departmentName: string) => {
setCollapsedDepartments(prev => {
const newSet = new Set(prev)
if (newSet.has(departmentName)) {
newSet.delete(departmentName)
} else {
newSet.add(departmentName)
}
return newSet
})
}
// 切换管理员折叠状态
const toggleAdminCollapse = (adminId: string) => {
setCollapsedAdmins(prev => {
const newSet = new Set(prev)
if (newSet.has(adminId)) {
newSet.delete(adminId)
} else {
newSet.add(adminId)
}
return newSet
})
}
// 组织用户树形结构数据
const getUserTreeData = () => {
// 系统管理员(包括总管理员和部门管理员)
const admins = users.filter(u => u.role === 'ADMIN')
// 所有部门名称
const allDepartmentNames = Array.from(new Set(users.map(u => u.department).filter(d => d)))
return {
admins,
departments: allDepartmentNames,
getUsersByDepartment: (deptName: string) =>
users.filter(u => u.department === deptName && u.role !== 'ADMIN'),
getDepartmentsByAdmin: (adminId: string) => {
const admin = users.find(u => u.id === adminId)
if (!admin || !admin.managedDepartment) return []
// 一个管理员只负责一个部门
return [admin.managedDepartment]
},
getUnmanagedDepartments: () => {
const managedDepts = new Set(
admins.map(a => a.managedDepartment).filter(Boolean)
)
return allDepartmentNames.filter(d => !managedDepts.has(d))
}
}
}
if (status === 'loading' || loading) {
return (
<div className="min-h-screen flex items-center justify-center">
@ -672,6 +861,36 @@ export default function AdminPage() {
{/* Materials Table */}
{activeTab === 'materials' && (
<div className="card-apple overflow-hidden">
{/* 素材搜索框 */}
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="relative">
<input
type="text"
placeholder="搜索素材:SPU型号、店铺、场景、作者..."
value={materialSearchTerm}
onChange={(e) => setMaterialSearchTerm(e.target.value)}
className="w-full pl-10 pr-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:border-blue-500 dark:focus:border-blue-400 focus:ring-2 focus:ring-blue-200 dark:focus:ring-blue-600 outline-none transition-all"
/>
<svg
className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
{materialSearchTerm && (
<button
onClick={() => setMaterialSearchTerm('')}
className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
</div>
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
@ -697,7 +916,19 @@ export default function AdminPage() {
</tr>
</thead>
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
{materials.map((material) => (
{materials
.filter(material => {
if (!materialSearchTerm) return true
const searchLower = materialSearchTerm.toLowerCase()
return (
material.productModel.toLowerCase().includes(searchLower) ||
material.categoryName.toLowerCase().includes(searchLower) ||
material.sceneName.toLowerCase().includes(searchLower) ||
material.authorName.toLowerCase().includes(searchLower) ||
material.materialType.toLowerCase().includes(searchLower)
)
})
.map((material) => (
<tr key={material.id}>
<td className="px-6 py-4 whitespace-nowrap">
<img
@ -756,161 +987,334 @@ export default function AdminPage() {
</div>
)}
{/* Users Table */}
{/* Users Tree View */}
{activeTab === 'users' && (
<div className="card-apple overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
用户名
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
邮箱
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
部门
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
角色
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
状态
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
下载权限
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
素材数量
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
注册时间
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
操作
</th>
</tr>
</thead>
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
{users.map((user) => (
<tr key={user.id}>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm font-medium text-gray-900 dark:text-white">
{user.username}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm text-gray-900 dark:text-white">{user.email}</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm text-gray-500 dark:text-gray-400">
{user.department || '-'}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span
className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
user.role === 'ADMIN'
? 'bg-purple-100 text-purple-800'
: 'bg-green-100 text-green-800'
}`}
>
{user.role === 'ADMIN' ? '管理员' : '用户'}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span
className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
user.isActive
? 'bg-green-100 text-green-800'
: 'bg-red-100 text-red-800'
}`}
>
{user.isActive ? '已激活' : '未激活'}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span
className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
user.canDownload
? 'bg-blue-100 text-blue-800'
: 'bg-gray-100 text-gray-800'
}`}
>
{user.canDownload ? '允许下载' : '禁止下载'}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
{user._count.materials}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
{format(new Date(user.createdAt), 'yyyy-MM-dd')}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<div className="flex items-center space-x-3">
{user.email !== session?.user?.email && (
<>
<button
onClick={() => handleEditUserDepartment(user)}
className="text-blue-600 hover:text-blue-800 dark:text-blue-400 font-medium"
title="编辑部门"
>
编辑部门
</button>
<button
onClick={() => handleSetRole(user.id, user.role)}
className={`font-medium ${
user.role === 'ADMIN'
? 'text-orange-600 hover:text-orange-800 dark:text-orange-400'
: 'text-purple-600 hover:text-purple-800 dark:text-purple-400'
}`}
>
{user.role === 'ADMIN' ? '取消管理员' : '设为管理员'}
</button>
<button
onClick={() => handleToggleActive(user.id, user.isActive)}
className="text-gray-700 hover:text-gray-900 dark:text-gray-300 dark:hover:text-gray-100 font-medium"
>
{user.isActive ? '禁用' : '激活'}
</button>
{user.role !== 'ADMIN' && (
{/* 用户搜索框 */}
<div className="p-4 border-b border-gray-200 dark:border-gray-700">
<div className="relative">
<input
type="text"
placeholder="搜索用户名或部门..."
value={userSearchTerm}
onChange={(e) => setUserSearchTerm(e.target.value)}
className="w-full px-4 py-2 pl-10 rounded-apple border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:border-gray-900 dark:focus:border-gray-400 focus:ring-2 focus:ring-gray-200 dark:focus:ring-gray-600 outline-none"
/>
<svg className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
</div>
</div>
{/* 树形结构显示 */}
<div className="p-6">{(() => {
const treeData = getUserTreeData()
const filteredUsers = users.filter(user => {
if (!userSearchTerm) return true
const searchLower = userSearchTerm.toLowerCase()
return user.username.toLowerCase().includes(searchLower) ||
(user.department && user.department.toLowerCase().includes(searchLower))
})
return (
<div className="space-y-2">
{/* 第一层:管理员列表 */}
{treeData.admins
.filter(admin => !userSearchTerm || filteredUsers.some(u => u.id === admin.id))
.map((admin) => {
const managedDepts = treeData.getDepartmentsByAdmin(admin.id)
const isCollapsed = collapsedAdmins.has(admin.id)
return (
<div key={admin.id} className="border border-gray-200 dark:border-gray-600 rounded-lg overflow-hidden">
{/* 管理员行 */}
<div className="bg-purple-50 dark:bg-purple-900/20 p-4">
<div className="flex items-center gap-3">
{/* 折叠按钮 */}
{managedDepts.length > 0 && (
<button
onClick={() => handleToggleDownload(user.id, user.canDownload)}
className={`font-medium ${
user.canDownload
? 'text-yellow-600 hover:text-yellow-800 dark:text-yellow-400'
: 'text-blue-600 hover:text-blue-800 dark:text-blue-400'
}`}
onClick={() => toggleAdminCollapse(admin.id)}
className="flex-shrink-0 w-6 h-6 flex items-center justify-center hover:bg-purple-200 dark:hover:bg-purple-800 rounded transition-colors"
>
{user.canDownload ? '关闭下载' : '开启下载'}
<svg className={`w-4 h-4 transform transition-transform ${isCollapsed ? '' : 'rotate-90'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</button>
)}
<button
onClick={() => handleDeleteUser(user.id)}
className="text-red-600 hover:text-red-800 dark:text-red-400 font-medium"
>
删除
</button>
</>
)}
{user.email === session?.user?.email && (
<span className="text-xs text-gray-500 dark:text-gray-400 italic">
当前账号
</span>
)}
<div className="flex-1">
<div className="flex items-center gap-2">
<span className="font-semibold text-gray-900 dark:text-white">{admin.username}</span>
<span className="px-2 py-0.5 bg-purple-600 text-white text-xs rounded-full">管理员</span>
{admin.managedDepartment && (
<span className="px-2 py-0.5 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 text-xs rounded-full">
负责: {admin.managedDepartment}
</span>
)}
</div>
<div className="text-sm text-gray-600 dark:text-gray-400 mt-1">
部门: {admin.department || '未分配'} | 素材: {admin._count.materials} |
注册: {format(new Date(admin.createdAt), 'yyyy-MM-dd')}
</div>
</div>
{/* 管理员操作按钮 */}
{admin.email !== session?.user?.email && (
<div className="flex items-center gap-2">
<button
onClick={() => handleEditUserDepartment(admin)}
className="px-3 py-1 text-xs bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 rounded hover:bg-blue-200 dark:hover:bg-blue-800 transition-colors"
>
编辑部门
</button>
<button
onClick={() => handleSetRole(admin.id, admin.role)}
className="px-3 py-1 text-xs bg-orange-100 dark:bg-orange-900 text-orange-700 dark:text-orange-300 rounded hover:bg-orange-200 dark:hover:bg-orange-800 transition-colors"
>
取消管理员
</button>
<button
onClick={() => handleToggleActive(admin.id, admin.isActive)}
className="px-3 py-1 text-xs bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
>
{admin.isActive ? '禁用' : '激活'}
</button>
</div>
)}
</div>
</div>
{/* 第二层:管理员负责的部门 */}
{!isCollapsed && managedDepts.map((deptName) => {
const deptUsers = treeData.getUsersByDepartment(deptName)
.filter(u => !userSearchTerm || filteredUsers.some(fu => fu.id === u.id))
const isDeptCollapsed = collapsedDepartments.has(deptName)
return (
<div key={deptName} className="border-t border-gray-200 dark:border-gray-700">
{/* 部门行 */}
<div className="bg-blue-50 dark:bg-blue-900/20 p-4 pl-12">
<div className="flex items-center gap-3">
{/* 折叠按钮 */}
{deptUsers.length > 0 && (
<button
onClick={() => toggleDepartmentCollapse(deptName)}
className="flex-shrink-0 w-5 h-5 flex items-center justify-center hover:bg-blue-200 dark:hover:bg-blue-800 rounded transition-colors"
>
<svg className={`w-3 h-3 transform transition-transform ${isDeptCollapsed ? '' : 'rotate-90'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</button>
)}
<div className="flex-1">
<div className="flex items-center gap-2">
<svg className="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
</svg>
<span className="font-medium text-gray-900 dark:text-white">{deptName}</span>
<span className="text-xs text-gray-500 dark:text-gray-400">({deptUsers.length} 人)</span>
</div>
</div>
</div>
</div>
{/* 第三层:部门下的用户 */}
{!isDeptCollapsed && deptUsers.map((user) => (
<div key={user.id} className="bg-white dark:bg-gray-800 p-4 pl-20 border-t border-gray-100 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors">
<div className="flex items-center gap-3">
<svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
<div className="flex-1">
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-gray-900 dark:text-white">{user.username}</span>
<span className={`px-2 py-0.5 text-xs rounded-full ${
user.isActive
? 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200'
: 'bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200'
}`}>
{user.isActive ? '已激活' : '未激活'}
</span>
<span className={`px-2 py-0.5 text-xs rounded-full ${
user.canDownload
? 'bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200'
: 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-300'
}`}>
{user.canDownload ? '可下载' : '禁止下载'}
</span>
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
素材: {user._count.materials} | 注册: {format(new Date(user.createdAt), 'yyyy-MM-dd')}
</div>
</div>
{/* 用户操作按钮 */}
<div className="flex items-center gap-2">
<button
onClick={() => handleEditUserDepartment(user)}
className="px-2 py-1 text-xs text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded transition-colors"
>
编辑
</button>
<button
onClick={() => handleSetRole(user.id, user.role)}
className="px-2 py-1 text-xs text-purple-600 dark:text-purple-400 hover:bg-purple-50 dark:hover:bg-purple-900/30 rounded transition-colors"
>
设为管理员
</button>
<button
onClick={() => handleToggleActive(user.id, user.isActive)}
className="px-2 py-1 text-xs text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
>
{user.isActive ? '禁用' : '激活'}
</button>
<button
onClick={() => handleToggleDownload(user.id, user.canDownload)}
className="px-2 py-1 text-xs text-yellow-600 dark:text-yellow-400 hover:bg-yellow-50 dark:hover:bg-yellow-900/30 rounded transition-colors"
>
{user.canDownload ? '禁止下载' : '允许下载'}
</button>
<button
onClick={() => handleDeleteUser(user.id)}
className="px-2 py-1 text-xs text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/30 rounded transition-colors"
>
删除
</button>
</div>
</div>
</div>
))}
</div>
)
})}
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
{users.length === 0 && (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
暂无用户
</div>
)}
)
})}
{/* 未分配管理员的部门 */}
{treeData.getUnmanagedDepartments()
.filter(deptName => {
if (!userSearchTerm) return true
const deptUsers = treeData.getUsersByDepartment(deptName)
return deptUsers.some(u => filteredUsers.some(fu => fu.id === u.id))
})
.map((deptName) => {
const deptUsers = treeData.getUsersByDepartment(deptName)
.filter(u => !userSearchTerm || filteredUsers.some(fu => fu.id === u.id))
const isDeptCollapsed = collapsedDepartments.has(deptName)
return (
<div key={deptName} className="border border-gray-200 dark:border-gray-600 rounded-lg overflow-hidden">
{/* 部门行(未分配管理员) */}
<div className="bg-yellow-50 dark:bg-yellow-900/20 p-4">
<div className="flex items-center gap-3">
{/* 折叠按钮 */}
{deptUsers.length > 0 && (
<button
onClick={() => toggleDepartmentCollapse(deptName)}
className="flex-shrink-0 w-6 h-6 flex items-center justify-center hover:bg-yellow-200 dark:hover:bg-yellow-800 rounded transition-colors"
>
<svg className={`w-4 h-4 transform transition-transform ${isDeptCollapsed ? '' : 'rotate-90'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</button>
)}
<div className="flex-1">
<div className="flex items-center gap-2">
<svg className="w-5 h-5 text-yellow-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
</svg>
<span className="font-medium text-gray-900 dark:text-white">{deptName}</span>
<span className="px-2 py-0.5 bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200 text-xs rounded-full">未分配管理员</span>
<span className="text-xs text-gray-500 dark:text-gray-400">({deptUsers.length} 人)</span>
</div>
</div>
</div>
</div>
{/* 部门下的用户 */}
{!isDeptCollapsed && deptUsers.map((user) => (
<div key={user.id} className="bg-white dark:bg-gray-800 p-4 pl-12 border-t border-gray-100 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors">
<div className="flex items-center gap-3">
<svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
<div className="flex-1">
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-gray-900 dark:text-white">{user.username}</span>
<span className={`px-2 py-0.5 text-xs rounded-full ${
user.isActive
? 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200'
: 'bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200'
}`}>
{user.isActive ? '已激活' : '未激活'}
</span>
<span className={`px-2 py-0.5 text-xs rounded-full ${
user.canDownload
? 'bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200'
: 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-300'
}`}>
{user.canDownload ? '可下载' : '禁止下载'}
</span>
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
素材: {user._count.materials} | 注册: {format(new Date(user.createdAt), 'yyyy-MM-dd')}
</div>
</div>
{/* 用户操作按钮 */}
<div className="flex items-center gap-2">
<button
onClick={() => handleEditUserDepartment(user)}
className="px-2 py-1 text-xs text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded transition-colors"
>
编辑
</button>
<button
onClick={() => handleSetRole(user.id, user.role)}
className="px-2 py-1 text-xs text-purple-600 dark:text-purple-400 hover:bg-purple-50 dark:hover:bg-purple-900/30 rounded transition-colors"
>
设为管理员
</button>
<button
onClick={() => handleToggleActive(user.id, user.isActive)}
className="px-2 py-1 text-xs text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
>
{user.isActive ? '禁用' : '激活'}
</button>
<button
onClick={() => handleToggleDownload(user.id, user.canDownload)}
className="px-2 py-1 text-xs text-yellow-600 dark:text-yellow-400 hover:bg-yellow-50 dark:hover:bg-yellow-900/30 rounded transition-colors"
>
{user.canDownload ? '禁止下载' : '允许下载'}
</button>
<button
onClick={() => handleDeleteUser(user.id)}
className="px-2 py-1 text-xs text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/30 rounded transition-colors"
>
删除
</button>
</div>
</div>
</div>
))}
</div>
)
})}
{/* 空状态提示 */}
{users.length === 0 && (
<div className="text-center py-12 text-gray-500 dark:text-gray-400">
暂无用户
</div>
)}
</div>
)
})()}</div>
</div>
)}
@ -1104,6 +1508,100 @@ export default function AdminPage() {
)}
</div>
</div>
{/* 平台分类 */}
<div className="card-apple">
<div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
<div>
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">平台分类(可选)</h2>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">管理所有平台分类名称,用于素材分类</p>
</div>
<button
onClick={() => setShowAddPlatformModal(true)}
className="px-4 py-2 bg-gray-900 dark:bg-gray-700 text-white text-sm rounded-lg hover:bg-gray-800 dark:hover:bg-gray-600 transition-colors flex items-center gap-2"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
</svg>
新增平台
</button>
</div>
<div className="p-6">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{platforms.map((platform) => (
<div
key={platform.id}
className="border border-gray-200 dark:border-gray-600 rounded-lg p-4 hover:shadow-md transition-shadow"
>
{editingPlatform?.id === platform.id ? (
<div className="space-y-3">
<input
type="text"
defaultValue={platform.name}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-gray-400 outline-none"
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleUpdatePlatform(platform.id, e.currentTarget.value)
} else if (e.key === 'Escape') {
setEditingPlatform(null)
}
}}
autoFocus
/>
<div className="flex gap-2">
<button
onClick={(e) => {
const input = e.currentTarget.parentElement?.previousElementSibling as HTMLInputElement
handleUpdatePlatform(platform.id, input.value)
}}
className="flex-1 px-3 py-1.5 bg-gray-900 text-white text-sm rounded-lg hover:bg-gray-800 transition-colors"
>
保存
</button>
<button
onClick={() => setEditingPlatform(null)}
className="flex-1 px-3 py-1.5 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 text-sm rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
>
取消
</button>
</div>
</div>
) : (
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="font-medium text-gray-900 dark:text-white">
{platform.name}
</h3>
<span className="text-xs text-gray-500 bg-gray-100 dark:bg-gray-700 px-2 py-1 rounded-full">
{platform.count} 个素材
</span>
</div>
<div className="flex gap-2">
<button
onClick={() => setEditingPlatform(platform)}
className="flex-1 px-3 py-1.5 text-gray-700 dark:text-gray-300 text-sm border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
>
编辑
</button>
<button
onClick={() => handleDeletePlatform(platform.id)}
className="flex-1 px-3 py-1.5 text-red-600 dark:text-red-400 text-sm border border-red-300 dark:border-red-600 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
>
删除
</button>
</div>
</div>
)}
</div>
))}
</div>
{platforms.length === 0 && (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
暂无平台分类
</div>
)}
</div>
</div>
</div>
)}
@ -1306,6 +1804,57 @@ export default function AdminPage() {
</div>
)}
{/* 新增平台分类模态框 */}
{showAddPlatformModal && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md p-6">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
新增平台分类
</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
平台名称
</label>
<input
type="text"
value={newPlatformName}
onChange={(e) => setNewPlatformName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleAddPlatform()
} else if (e.key === 'Escape') {
setShowAddPlatformModal(false)
setNewPlatformName('')
}
}}
placeholder="请输入平台名称"
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:ring-2 focus:ring-gray-400 outline-none"
autoFocus
/>
</div>
<div className="flex gap-3 justify-end">
<button
onClick={() => {
setShowAddPlatformModal(false)
setNewPlatformName('')
}}
className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
>
取消
</button>
<button
onClick={handleAddPlatform}
className="px-4 py-2 bg-gray-900 dark:bg-gray-700 text-white rounded-lg hover:bg-gray-800 dark:hover:bg-gray-600 transition-colors"
>
确定添加
</button>
</div>
</div>
</div>
</div>
)}
{/* 编辑用户部门模态框 */}
{editingUser && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">

View File

@ -0,0 +1,86 @@
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
export async function POST(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session || session.user.role !== 'ADMIN') {
return NextResponse.json({ error: '需要管理员权限' }, { status: 403 })
}
const { userId, departmentName } = await req.json()
if (!userId || !departmentName) {
return NextResponse.json({ error: '用户ID和部门名称不能为空' }, { status: 400 })
}
// 检查该部门是否已经有管理员
const existingManager = await prisma.user.findFirst({
where: {
managedDepartment: departmentName,
NOT: { id: userId }
}
})
if (existingManager) {
return NextResponse.json({
error: `部门"${departmentName}"已有管理员:${existingManager.username}`
}, { status: 400 })
}
// 更新用户为部门管理员
const user = await prisma.user.update({
where: { id: userId },
data: {
managedDepartment: departmentName,
role: 'ADMIN' // 设置为管理员角色
}
})
return NextResponse.json({
message: '部门管理员设置成功',
user
})
} catch (error) {
console.error('Set department manager error:', error)
return NextResponse.json({ error: '设置失败' }, { status: 500 })
}
}
// 取消部门管理员
export async function DELETE(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session || session.user.role !== 'ADMIN') {
return NextResponse.json({ error: '需要管理员权限' }, { status: 403 })
}
const { searchParams } = new URL(req.url)
const userId = searchParams.get('userId')
if (!userId) {
return NextResponse.json({ error: '用户ID不能为空' }, { status: 400 })
}
// 取消部门管理员
const user = await prisma.user.update({
where: { id: userId },
data: {
managedDepartment: null
}
})
return NextResponse.json({
message: '已取消部门管理员',
user
})
} catch (error) {
console.error('Remove department manager error:', error)
return NextResponse.json({ error: '取消失败' }, { status: 500 })
}
}

View File

@ -185,7 +185,9 @@ export async function POST(request: NextRequest) {
)
}
const company = state || 'default'
// state 用于传递前端数据(如origin),不是公司标识
// 始终使用 default 配置
const company = 'default'
console.log('开始钉钉登录流程:', { code, company })

View File

@ -12,6 +12,7 @@ export async function GET(req: NextRequest) {
const categoryName = searchParams.get('category') || ''
const sceneName = searchParams.get('scene') || ''
const materialType = searchParams.get('materialType') || ''
const platformName = searchParams.get('platform') || ''
const month = searchParams.get('month') || ''
const sortBy = searchParams.get('sortBy') || 'createdAt' // createdAt | downloadCount
const page = parseInt(searchParams.get('page') || '1')
@ -45,6 +46,11 @@ export async function GET(req: NextRequest) {
where.materialType = materialType
}
// Add platform filter (平台分类)
if (platformName) {
where.platformName = platformName
}
// Add month filter (上传月份)
if (month) {
const [year, monthNum] = month.split('-')

View File

@ -263,19 +263,19 @@ export async function POST(req: NextRequest) {
if (!zipFile) {
console.log('[Upload] No zip file provided (Model type with images only), skipping file save...')
} else {
console.log('[Upload] Saving file locally...')
const uploadDir = process.env.UPLOAD_DIR || './uploads'
await mkdir(uploadDir, { recursive: true })
console.log('[Upload] Saving file locally...')
const uploadDir = process.env.UPLOAD_DIR || './uploads'
await mkdir(uploadDir, { recursive: true })
const zipFileExt = path.extname(zipFile.name)
const zipFileExt = path.extname(zipFile.name)
zipFileName = generateUniqueFileName('material', zipFileExt)
zipFilePath = path.join(uploadDir, zipFileName)
// 读取并保存素材文件
const zipBuffer = Buffer.from(await zipFile.arrayBuffer())
await writeFile(zipFilePath, zipBuffer)
await writeFile(zipFilePath, zipBuffer)
zipFileSize = BigInt(zipBuffer.length) // 记录文件大小(字节)
console.log('[Upload] File saved:', zipFilePath, `(${(Number(zipFileSize) / 1024 / 1024).toFixed(2)} MB)`)
console.log('[Upload] File saved:', zipFilePath, `(${(Number(zipFileSize) / 1024 / 1024).toFixed(2)} MB)`)
}
// Create material record

162
app/api/platforms/route.ts Normal file
View File

@ -0,0 +1,162 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
// GET - 获取所有平台分类(包含数量统计)
export async function GET(request: NextRequest) {
try {
const platforms = await prisma.platform.findMany({
orderBy: { createdAt: 'asc' }
})
// 获取每个平台的素材数量
const platformsWithCount = await Promise.all(
platforms.map(async (platform) => {
const count = await prisma.material.count({
where: { platformName: platform.name }
})
return {
id: platform.id,
name: platform.name,
count
}
})
)
return NextResponse.json(platformsWithCount)
} catch (error) {
console.error('Error fetching platforms:', error)
return NextResponse.json({ error: '获取平台分类失败' }, { status: 500 })
}
}
// POST - 创建新平台分类
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session || session.user.role !== 'ADMIN') {
return NextResponse.json({ error: '需要管理员权限' }, { status: 403 })
}
const { name } = await request.json()
if (!name || !name.trim()) {
return NextResponse.json({ error: '平台分类名称不能为空' }, { status: 400 })
}
// 检查是否已存在
const existing = await prisma.platform.findUnique({
where: { name: name.trim() }
})
if (existing) {
return NextResponse.json({ error: '该平台分类已存在' }, { status: 400 })
}
const platform = await prisma.platform.create({
data: { name: name.trim() }
})
return NextResponse.json(platform, { status: 201 })
} catch (error) {
console.error('Error creating platform:', error)
return NextResponse.json({ error: '创建平台分类失败' }, { status: 500 })
}
}
// PUT - 更新平台分类
export async function PUT(request: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session || session.user.role !== 'ADMIN') {
return NextResponse.json({ error: '需要管理员权限' }, { status: 403 })
}
const { id, name } = await request.json()
if (!id || !name || !name.trim()) {
return NextResponse.json({ error: '平台分类ID和名称不能为空' }, { status: 400 })
}
// 检查是否存在其他同名平台
const existing = await prisma.platform.findFirst({
where: {
name: name.trim(),
NOT: { id }
}
})
if (existing) {
return NextResponse.json({ error: '该平台分类名称已被使用' }, { status: 400 })
}
// 获取旧名称
const oldPlatform = await prisma.platform.findUnique({ where: { id } })
if (!oldPlatform) {
return NextResponse.json({ error: '平台分类不存在' }, { status: 404 })
}
// 更新平台分类
const platform = await prisma.platform.update({
where: { id },
data: { name: name.trim() }
})
// 更新所有使用该平台的素材
await prisma.material.updateMany({
where: { platformName: oldPlatform.name },
data: { platformName: name.trim() }
})
return NextResponse.json(platform)
} catch (error) {
console.error('Error updating platform:', error)
return NextResponse.json({ error: '更新平台分类失败' }, { status: 500 })
}
}
// DELETE - 删除平台分类
export async function DELETE(request: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session || session.user.role !== 'ADMIN') {
return NextResponse.json({ error: '需要管理员权限' }, { status: 403 })
}
const { searchParams } = new URL(request.url)
const id = searchParams.get('id')
if (!id) {
return NextResponse.json({ error: '平台分类ID不能为空' }, { status: 400 })
}
// 检查是否有素材使用该平台
const platform = await prisma.platform.findUnique({ where: { id } })
if (!platform) {
return NextResponse.json({ error: '平台分类不存在' }, { status: 404 })
}
const materialCount = await prisma.material.count({
where: { platformName: platform.name }
})
if (materialCount > 0) {
return NextResponse.json({
error: `无法删除:有 ${materialCount} 个素材正在使用该平台分类`
}, { status: 400 })
}
// 删除平台分类
await prisma.platform.delete({ where: { id } })
return NextResponse.json({ message: '平台分类已删除' })
} catch (error) {
console.error('Error deleting platform:', error)
return NextResponse.json({ error: '删除平台分类失败' }, { status: 500 })
}
}

View File

@ -17,6 +17,9 @@ export default function LoginPage() {
// 系统设置
const [loginLogoUrl, setLoginLogoUrl] = useState('http://s3.1080p.hk/shuzhou/2025/05/18/8ebadf0a7cc34eaea00e8619b8efb827.png')
const [siteName, setSiteName] = useState('由壹点3D素材')
// 钉钉配置(从环境变量或配置文件获取)
const DINGTALK_CLIENT_ID = process.env.NEXT_PUBLIC_DINGTALK_CLIENT_ID || 'ding1bs1gxwrcfu16x0f'
// 加载系统设置
useEffect(() => {
@ -128,9 +131,6 @@ export default function LoginPage() {
setLoading(false)
}
}
// 钉钉登录配置
const DINGTALK_CLIENT_ID = 'ding1bs1gxwrcfu16x0f'
const handleDingtalkLogin = () => {
// 强制使用外网域名作为回调地址,支持内网访问

View File

@ -41,8 +41,10 @@ export default function Home() {
const [selectedCategory, setSelectedCategory] = useState('')
const [selectedScene, setSelectedScene] = useState('')
const [selectedMaterialType, setSelectedMaterialType] = useState('') // 素材类型筛选
const [selectedPlatform, setSelectedPlatform] = useState('') // 平台分类筛选
const [categories, setCategories] = useState<Array<{ id: string; name: string; count: number }>>([])
const [scenes, setScenes] = useState<Array<{ id: string; name: string; count: number }>>([])
const [platforms, setPlatforms] = useState<Array<{ id: string; name: string; count: number }>>([])
const [materialTypes] = useState([
{ value: '3DMAX', label: '3DMAX' },
{ value: 'PSD', label: 'PSD' },
@ -120,6 +122,7 @@ export default function Home() {
fetchMaterials()
fetchCategories()
fetchScenes()
fetchPlatforms()
fetchThemeColor()
}, [])
@ -143,14 +146,14 @@ export default function Home() {
useEffect(() => {
setCurrentPage(1) // 重置到第一页
}, [searchKeyword, selectedCategory, selectedScene, selectedMaterialType, selectedMonth, sortBy])
}, [searchKeyword, selectedCategory, selectedScene, selectedMaterialType, selectedPlatform, selectedMonth, sortBy])
useEffect(() => {
if (status === 'authenticated') {
fetchMaterials()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentPage, searchKeyword, selectedCategory, selectedScene, selectedMaterialType, selectedMonth, sortBy])
}, [currentPage, searchKeyword, selectedCategory, selectedScene, selectedMaterialType, selectedPlatform, selectedMonth, sortBy])
const fetchCategories = async () => {
try {
@ -179,6 +182,18 @@ export default function Home() {
}
}
const fetchPlatforms = async () => {
try {
const response = await fetch('/api/platforms')
if (response.ok) {
const data = await response.json()
setPlatforms(data)
}
} catch (error) {
console.error('Error fetching platforms:', error)
}
}
const fetchMaterials = async () => {
try {
const params = new URLSearchParams()
@ -186,6 +201,7 @@ export default function Home() {
if (selectedCategory) params.append('category', selectedCategory)
if (selectedScene) params.append('scene', selectedScene)
if (selectedMaterialType) params.append('materialType', selectedMaterialType)
if (selectedPlatform) params.append('platform', selectedPlatform)
if (selectedMonth) params.append('month', selectedMonth)
if (sortBy) params.append('sortBy', sortBy)
params.append('page', currentPage.toString())
@ -459,6 +475,45 @@ export default function Home() {
</div>
</div>
{/* Material Type Filter (类型分页) - 移到最顶部 */}
<div className="mb-4">
<div className="flex items-center justify-between mb-3">
<h2 className="text-sm font-medium text-gray-700 dark:text-gray-300">类型分页</h2>
{selectedMaterialType && (
<span className="text-xs text-gray-500 dark:text-gray-400">
{materials.length} 个素材
</span>
)}
</div>
<div className="flex flex-wrap gap-2">
<button
onClick={() => setSelectedMaterialType('')}
className={`px-4 py-2 rounded-full text-sm font-medium transition-all ${
selectedMaterialType === ''
? 'text-white'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700'
}`}
style={selectedMaterialType === '' ? { backgroundColor: themeColor } : {}}
>
全部
</button>
{materialTypes.map((type) => (
<button
key={type.value}
onClick={() => setSelectedMaterialType(type.value === selectedMaterialType ? '' : type.value)}
className={`px-4 py-2 rounded-full text-sm font-medium transition-all ${
selectedMaterialType === type.value
? 'text-white'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700'
}`}
style={selectedMaterialType === type.value ? { backgroundColor: themeColor } : {}}
>
{type.label}
</button>
))}
</div>
</div>
{/* Category Filter (使用店铺) */}
<div className="mb-4">
<div className="flex items-center justify-between mb-3">
@ -565,44 +620,60 @@ export default function Home() {
</div>
</div>
{/* Material Type Filter (素材类型) */}
<div className="mb-4">
<div className="flex items-center justify-between mb-3">
<h2 className="text-sm font-medium text-gray-700 dark:text-gray-300">素材类型</h2>
{selectedMaterialType && (
<span className="text-xs text-gray-500 dark:text-gray-400">
{materials.length} 个素材
</span>
)}
</div>
<div className="flex flex-wrap gap-2">
<button
onClick={() => setSelectedMaterialType('')}
className={`px-4 py-2 rounded-full text-sm font-medium transition-all ${
selectedMaterialType === ''
? 'text-white'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700'
}`}
style={selectedMaterialType === '' ? { backgroundColor: themeColor } : {}}
>
全部
</button>
{materialTypes.map((type) => (
{/* Platform Filter (平台分类) - 条件显示,仅在有平台时显示 */}
{platforms.length > 0 && (
<div className="mb-4">
<div className="flex items-center justify-between mb-3">
<h2 className="text-sm font-medium text-gray-700 dark:text-gray-300">平台分类</h2>
{selectedPlatform && (
<span className="text-xs text-gray-500 dark:text-gray-400">
{materials.length} 个素材
</span>
)}
</div>
<div className="flex flex-wrap gap-2">
<button
key={type.value}
onClick={() => setSelectedMaterialType(type.value === selectedMaterialType ? '' : type.value)}
onClick={() => setSelectedPlatform('')}
className={`px-4 py-2 rounded-full text-sm font-medium transition-all ${
selectedMaterialType === type.value
selectedPlatform === ''
? 'text-white'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700'
}`}
style={selectedMaterialType === type.value ? { backgroundColor: themeColor } : {}}
style={selectedPlatform === '' ? { backgroundColor: themeColor } : {}}
>
{type.label}
全部
<span className={`ml-1.5 text-xs ${
selectedPlatform === ''
? 'text-gray-300'
: 'text-gray-500 dark:text-gray-400'
}`}>
({totalMaterialsCount})
</span>
</button>
))}
{platforms.map((platform) => (
<button
key={platform.id}
onClick={() => setSelectedPlatform(platform.name === selectedPlatform ? '' : platform.name)}
className={`px-4 py-2 rounded-full text-sm font-medium transition-all ${
selectedPlatform === platform.name
? 'text-white'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700'
}`}
style={selectedPlatform === platform.name ? { backgroundColor: themeColor } : {}}
>
{platform.name}
<span className={`ml-1.5 text-xs ${
selectedPlatform === platform.name
? 'text-gray-300'
: 'text-gray-500 dark:text-gray-400'
}`}>
({platform.count || 0})
</span>
</button>
))}
</div>
</div>
</div>
)}
{/* Month Filter (上传月份) */}
<div className="mb-4">
@ -684,7 +755,7 @@ export default function Home() {
</div>
{/* Active Filters Display */}
{(searchKeyword || selectedCategory || selectedScene || selectedMaterialType || selectedMonth) && (
{(searchKeyword || selectedCategory || selectedScene || selectedMaterialType || selectedPlatform || selectedMonth) && (
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-apple p-3 mb-4">
<div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 flex-wrap">
<span className="font-medium text-blue-600 dark:text-blue-400">当前筛选:</span>
@ -732,6 +803,17 @@ export default function Home() {
</button>
</span>
)}
{selectedPlatform && (
<span className="inline-flex items-center gap-1 px-3 py-1 bg-gray-100 dark:bg-gray-800 rounded-full">
平台分类: {selectedPlatform}
<button
onClick={() => setSelectedPlatform('')}
className="text-gray-500 hover:text-gray-700 dark:hover:text-gray-300"
>
×
</button>
</span>
)}
{selectedMonth && (
<span className="inline-flex items-center gap-1 px-3 py-1 bg-gray-100 dark:bg-gray-800 rounded-full">
月份: {months.find(m => m.value === selectedMonth)?.label || selectedMonth}
@ -749,6 +831,7 @@ export default function Home() {
setSelectedCategory('')
setSelectedScene('')
setSelectedMaterialType('')
setSelectedPlatform('')
setSelectedMonth('')
}}
className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 underline ml-2 font-medium"
@ -771,7 +854,7 @@ export default function Home() {
) : materials.length === 0 ? (
<div className="text-center py-16">
<p className="text-gray-500 dark:text-gray-400 text-lg">
{searchKeyword || selectedCategory || selectedScene || selectedMaterialType ? '没有找到匹配的素材' : '还没有素材,快来上传第一个吧!'}
{searchKeyword || selectedCategory || selectedScene || selectedMaterialType || selectedPlatform ? '没有找到匹配的素材' : '还没有素材,快来上传第一个吧!'}
</p>
</div>
) : (
@ -781,7 +864,7 @@ export default function Home() {
<div key={material.id} className="card-apple overflow-hidden dark:bg-gray-800 dark:border-gray-700">
{/* Preview Image */}
<div
className="relative w-full h-[400px] bg-gray-200 dark:bg-gray-700 cursor-pointer group"
className="relative w-full h-[400px] bg-gray-200 dark:bg-gray-700 cursor-pointer group overflow-hidden"
onClick={() => {
// PSD和模特类型直接跳转到详情页,其他类型打开预览弹窗
if (material.materialType === 'PSD' || material.materialType === '模特') {

View File

@ -285,105 +285,105 @@ export default function SharePage() {
</div>
) : (
/* 非PSD类型:原有布局 */
<div className="max-w-4xl mx-auto">
<div className="bg-white dark:bg-gray-800 rounded-2xl shadow-lg overflow-hidden">
<div className="max-w-4xl mx-auto">
<div className="bg-white dark:bg-gray-800 rounded-2xl shadow-lg overflow-hidden">
{/* 普通预览图 */}
<div className="relative w-full h-96 bg-gray-200 dark:bg-gray-700">
<Image
src={material.previewUrl}
alt={material.productModel}
fill
unoptimized
className="object-contain"
sizes="(max-width: 1024px) 100vw, 1024px"
/>
<div className="relative w-full h-96 bg-gray-200 dark:bg-gray-700">
<Image
src={material.previewUrl}
alt={material.productModel}
fill
unoptimized
className="object-contain"
sizes="(max-width: 1024px) 100vw, 1024px"
/>
</div>
{/* Material Info */}
<div className="p-8">
<div className="mb-6">
<h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
{material.productModel}
</h1>
<div className="flex items-center gap-3 mb-4">
<span className="inline-flex items-center px-3 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-full text-sm font-medium">
{material.categoryName}
</span>
<span className="inline-flex items-center px-3 py-1 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 rounded-full text-sm font-medium">
{material.sceneName}
</span>
</div>
</div>
{/* Material Info */}
<div className="p-8">
<div className="mb-6">
<h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
{material.productModel}
</h1>
<div className="flex items-center gap-3 mb-4">
<span className="inline-flex items-center px-3 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-full text-sm font-medium">
{material.categoryName}
</span>
<span className="inline-flex items-center px-3 py-1 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 rounded-full text-sm font-medium">
{material.sceneName}
</span>
</div>
<div className="grid grid-cols-2 gap-6 mb-6">
<div>
<p className="text-sm text-gray-500 dark:text-gray-400 mb-1">作者</p>
<p className="text-lg font-medium text-gray-900 dark:text-white">{material.authorName}</p>
</div>
<div className="grid grid-cols-2 gap-6 mb-6">
<div>
<p className="text-sm text-gray-500 dark:text-gray-400 mb-1">作者</p>
<p className="text-lg font-medium text-gray-900 dark:text-white">{material.authorName}</p>
</div>
<div>
<p className="text-sm text-gray-500 dark:text-gray-400 mb-1">文件大小</p>
<p className="text-lg font-medium text-blue-600 dark:text-blue-400">{formatFileSize(material.zipFileSize)}</p>
</div>
<div>
<p className="text-sm text-gray-500 dark:text-gray-400 mb-1">下载次数</p>
<p className="text-lg font-medium text-gray-900 dark:text-white">{material.downloadCount}</p>
</div>
<div>
<p className="text-sm text-gray-500 dark:text-gray-400 mb-1">点赞数</p>
<p className="text-lg font-medium text-gray-900 dark:text-white">{material.likeCount}</p>
</div>
<div>
<p className="text-sm text-gray-500 dark:text-gray-400 mb-1">文件大小</p>
<p className="text-lg font-medium text-blue-600 dark:text-blue-400">{formatFileSize(material.zipFileSize)}</p>
</div>
<div className="mb-6">
<p className="text-sm text-gray-500 dark:text-gray-400 mb-1">文件名</p>
<p className="text-sm text-gray-700 dark:text-gray-300 break-all">{material.zipFileName}</p>
<div>
<p className="text-sm text-gray-500 dark:text-gray-400 mb-1">下载次数</p>
<p className="text-lg font-medium text-gray-900 dark:text-white">{material.downloadCount}</p>
</div>
<div className="mb-6">
<p className="text-sm text-gray-500 dark:text-gray-400 mb-1">上传时间</p>
<p className="text-sm text-gray-700 dark:text-gray-300">
{format(new Date(material.createdAt), 'yyyy-MM-dd HH:mm')}
</p>
<div>
<p className="text-sm text-gray-500 dark:text-gray-400 mb-1">点赞数</p>
<p className="text-lg font-medium text-gray-900 dark:text-white">{material.likeCount}</p>
</div>
</div>
{/* Download Button */}
<button
onClick={handleDownload}
disabled={downloading}
className="w-full btn-primary py-4 text-lg font-medium relative overflow-hidden disabled:opacity-75"
>
{downloading ? (
<>
<div
className="absolute left-0 top-0 bottom-0 bg-blue-600 transition-all duration-300"
style={{ width: `${downloadProgress}%` }}
/>
<span className="relative z-10 flex items-center justify-center gap-2">
<svg className="w-6 h-6 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
下载中 {downloadProgress}%
</span>
</>
) : (
<span className="flex items-center justify-center gap-2">
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
<div className="mb-6">
<p className="text-sm text-gray-500 dark:text-gray-400 mb-1">文件名</p>
<p className="text-sm text-gray-700 dark:text-gray-300 break-all">{material.zipFileName}</p>
</div>
<div className="mb-6">
<p className="text-sm text-gray-500 dark:text-gray-400 mb-1">上传时间</p>
<p className="text-sm text-gray-700 dark:text-gray-300">
{format(new Date(material.createdAt), 'yyyy-MM-dd HH:mm')}
</p>
</div>
{/* Download Button */}
<button
onClick={handleDownload}
disabled={downloading}
className="w-full btn-primary py-4 text-lg font-medium relative overflow-hidden disabled:opacity-75"
>
{downloading ? (
<>
<div
className="absolute left-0 top-0 bottom-0 bg-blue-600 transition-all duration-300"
style={{ width: `${downloadProgress}%` }}
/>
<span className="relative z-10 flex items-center justify-center gap-2">
<svg className="w-6 h-6 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
立即下载
下载中 {downloadProgress}%
</span>
)}
</button>
</>
) : (
<span className="flex items-center justify-center gap-2">
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
立即下载
</span>
)}
</button>
<button
onClick={() => router.push('/')}
className="w-full mt-4 py-3 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-xl font-medium hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
>
返回首页
</button>
</div>
<button
onClick={() => router.push('/')}
className="w-full mt-4 py-3 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-xl font-medium hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
>
返回首页
</button>
</div>
</div>
</div>
)}
</main>

View File

@ -30,6 +30,10 @@ export default function UploadModal({ onClose, onSuccess }: UploadModalProps) {
const [showNewSceneInput, setShowNewSceneInput] = useState(false)
const [newSceneName, setNewSceneName] = useState('')
// 平台分类(可选)
const [platformName, setPlatformName] = useState('')
const [platforms, setPlatforms] = useState<Array<{ id: string; name: string }>>([])
// 素材类型
const [materialType, setMaterialType] = useState('3DMAX')
@ -42,6 +46,7 @@ export default function UploadModal({ onClose, onSuccess }: UploadModalProps) {
const [error, setError] = useState('')
const [isDragging, setIsDragging] = useState(false)
const [isDisplayImageDragging, setIsDisplayImageDragging] = useState(false) // PSD展示图片拖拽状态
const [isPreviewDragging, setIsPreviewDragging] = useState(false) // 预览图片拖拽状态
const [retryCount, setRetryCount] = useState(0)
const MAX_RETRY = 2
@ -49,12 +54,14 @@ export default function UploadModal({ onClose, onSuccess }: UploadModalProps) {
const zipInputRef = useRef<HTMLInputElement>(null)
const dropZoneRef = useRef<HTMLDivElement>(null)
const displayImageDropZoneRef = useRef<HTMLDivElement>(null) // PSD展示图片拖拽区域
const previewDropZoneRef = useRef<HTMLDivElement>(null) // 预览图片拖拽区域
const xhrRef = useRef<XMLHttpRequest | null>(null)
// 加载分类和场景列表
useEffect(() => {
fetchCategories()
fetchScenes()
fetchPlatforms()
}, [])
const fetchCategories = async () => {
@ -81,6 +88,18 @@ export default function UploadModal({ onClose, onSuccess }: UploadModalProps) {
}
}
const fetchPlatforms = async () => {
try {
const response = await fetch('/api/platforms')
if (response.ok) {
const data = await response.json()
setPlatforms(data)
}
} catch (error) {
console.error('Error fetching platforms:', error)
}
}
const handlePreviewChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (file) {
@ -238,6 +257,50 @@ export default function UploadModal({ onClose, onSuccess }: UploadModalProps) {
}
}
// 预览图片拖拽处理
const handlePreviewDragEnter = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
setIsPreviewDragging(true)
}
const handlePreviewDragLeave = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
const x = e.clientX
const y = e.clientY
if (x <= rect.left || x >= rect.right || y <= rect.top || y >= rect.bottom) {
setIsPreviewDragging(false)
}
}
const handlePreviewDragOver = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
}
const handlePreviewDrop = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
setIsPreviewDragging(false)
const files = Array.from(e.dataTransfer.files)
if (files.length === 0) return
const imageFiles = files.filter(f => f.type.startsWith('image/'))
if (imageFiles.length > 0) {
const imgFile = imageFiles[0]
setPreviewImage(imgFile)
setPreviewUrl(URL.createObjectURL(imgFile))
setError('')
} else {
setError('请拖拽图片文件')
}
}
// PSD展示图片拖拽处理
const handleDisplayImageDragEnter = (e: React.DragEvent) => {
e.preventDefault()
@ -363,8 +426,14 @@ export default function UploadModal({ onClose, onSuccess }: UploadModalProps) {
setError('')
// Validation - 基础信息验证
if (!productModel || !categoryName || !sceneName) {
setError('请填写所有必填字段(产品型号、分类、场景)')
if (!productModel) {
setError(materialType === '材质' ? '请填写材质名称' : '请填写SPU型号')
return
}
// 材质类型不需要店铺和场景
if (materialType !== '材质' && (!categoryName || !sceneName)) {
setError('请填写所有必填字段(店铺、场景)')
return
}
@ -413,11 +482,13 @@ export default function UploadModal({ onClose, onSuccess }: UploadModalProps) {
}
// 素材文件对于模特类型是可选的
if (zipFile) {
formData.append('zipFile', zipFile)
formData.append('zipFile', zipFile)
}
formData.append('productModel', productModel)
formData.append('categoryName', categoryName)
formData.append('sceneName', sceneName)
// 材质类型使用默认值
formData.append('categoryName', materialType === '材质' ? '通用' : categoryName)
formData.append('sceneName', materialType === '材质' ? '通用' : sceneName)
formData.append('platformName', platformName || '') // 平台分类可选
formData.append('materialType', materialType)
formData.append('renderer', renderer)
@ -588,42 +659,55 @@ export default function UploadModal({ onClose, onSuccess }: UploadModalProps) {
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
预览图片 *
</label>
<div className="flex items-center space-x-4">
{previewUrl ? (
<div className="relative w-32 h-32 rounded-apple overflow-hidden border-2 border-gray-200 dark:border-gray-600">
<Image
src={previewUrl}
alt="Preview"
fill
unoptimized
className="object-cover"
/>
</div>
) : (
<div className="w-32 h-32 rounded-apple bg-gray-100 dark:bg-gray-700 flex items-center justify-center">
<svg className="w-12 h-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
</div>
)}
<div className="flex-1">
<input
ref={previewInputRef}
type="file"
onChange={handlePreviewChange}
accept="image/*"
className="hidden"
<div
ref={previewDropZoneRef}
className={`border-2 border-dashed rounded-apple p-4 transition-colors ${
isPreviewDragging
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
: 'border-gray-300 dark:border-gray-600'
}`}
onDragEnter={handlePreviewDragEnter}
onDragLeave={handlePreviewDragLeave}
onDragOver={handlePreviewDragOver}
onDrop={handlePreviewDrop}
>
<div className="flex items-center space-x-4">
{previewUrl ? (
<div className="relative w-32 h-32 rounded-apple overflow-hidden border-2 border-gray-200 dark:border-gray-600">
<Image
src={previewUrl}
alt="Preview"
fill
unoptimized
className="object-cover"
/>
<button
type="button"
onClick={() => previewInputRef.current?.click()}
className="btn-secondary"
>
选择图片
</button>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
支持 JPG、PNG、WebP 等格式
</p>
</div>
) : (
<div className="w-32 h-32 rounded-apple bg-gray-100 dark:bg-gray-700 flex items-center justify-center">
<svg className="w-12 h-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
</div>
)}
<div className="flex-1">
<input
ref={previewInputRef}
type="file"
onChange={handlePreviewChange}
accept="image/*"
className="hidden"
/>
<button
type="button"
onClick={() => previewInputRef.current?.click()}
className="btn-secondary"
>
选择图片
</button>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
支持 JPG、PNG、WebP 等格式,可拖拽上传
</p>
</div>
</div>
</div>
</div>
@ -685,17 +769,17 @@ export default function UploadModal({ onClose, onSuccess }: UploadModalProps) {
</p>
<p className="text-xs text-blue-600 dark:text-blue-400 mt-1">
💡 第一张图会自动作为预览图,高度超过1500px会自动切割
</p>
</div>
</div>
</p>
</div>
</div>
</div>
</div>
)}
{/* 模特展示图片(仅模特类型显示) */}
{materialType === '模特' && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
模特展示图片 * (可上传多张)
</label>
<div className="border-2 border-dashed rounded-apple p-4 border-gray-300 dark:border-gray-600">
@ -765,25 +849,30 @@ export default function UploadModal({ onClose, onSuccess }: UploadModalProps) {
</div>
)}
{/* SPU */}
{/* SPU 或材质名称 */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
SPU型号 *
{materialType === '材质' ? '材质名称 *' : 'SPU型号 *'}
</label>
<input
type="text"
value={productModel}
onChange={(e) => {
// 只允许英文、数字和常见符号(- _ .),过滤中文,自动转大写
// 材质类型支持中文,其他类型只允许英文、数字和常见符号
if (materialType === '材质') {
setProductModel(e.target.value)
} else {
const value = e.target.value.replace(/[^a-zA-Z0-9\-_.]/g, '').toUpperCase()
setProductModel(value)
}
}}
className="w-full px-4 py-2 rounded-apple border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:border-gray-900 dark:focus:border-gray-400 focus:ring-2 focus:ring-gray-200 dark:focus:ring-gray-600 outline-none"
placeholder="例如:XY-2024-001"
/>
</div>
{/* 使用店铺 */}
{/* 使用店铺(材质类型不需要) */}
{materialType !== '材质' && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
使用店铺 *
@ -839,8 +928,10 @@ export default function UploadModal({ onClose, onSuccess }: UploadModalProps) {
</div>
)}
</div>
)}
{/* 场景类别 */}
{/* 场景类别(材质类型不需要) */}
{materialType !== '材质' && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
场景类别 *
@ -896,6 +987,28 @@ export default function UploadModal({ onClose, onSuccess }: UploadModalProps) {
</div>
)}
</div>
)}
{/* 平台分类(可选,仅在后台配置了平台时显示) */}
{platforms.length > 0 && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
平台分类(可选)
</label>
<select
value={platformName}
onChange={(e) => setPlatformName(e.target.value)}
className="w-full px-4 py-2 rounded-apple border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:border-gray-900 dark:focus:border-gray-400 focus:ring-2 focus:ring-gray-200 dark:focus:ring-gray-600 outline-none"
>
<option value="">不选择平台</option>
{platforms.map((platform) => (
<option key={platform.id} value={platform.name}>
{platform.name}
</option>
))}
</select>
</div>
)}
{/* 渲染器(仅3DMAX显示) */}
{materialType === '3DMAX' && (

View File

@ -62,14 +62,14 @@ export async function initializeNetwork(): Promise<NetworkStatus> {
const host = getCurrentHost()
const isInternal = isInternalIP(hostname)
currentNetwork = {
currentNetwork = {
isInternal,
host
}
if (isInternal) {
console.log(`✅ 检测到内网访问 (${hostname})`)
} else {
} else {
console.log(`🌐 检测到公网访问 (${hostname})`)
}

View File

@ -13,7 +13,7 @@ const s3Client = new S3Client({
requestTimeout: 300000, // 5分钟超时
connectionTimeout: 30000, // 30秒连接超时
},
maxAttempts: 3, // 失败重试3次
maxAttempts: 10, // 失败重试10次,确保上传成功
})
export async function uploadToS3(
@ -31,9 +31,15 @@ export async function uploadToS3(
ACL: 'public-read',
})
try {
await s3Client.send(command)
return `${process.env.S3_PUBLIC_DOMAIN}/${key}`
} catch (error) {
// S3上传失败会自动重试(maxAttempts: 10),这里只记录日志
console.error('[S3] Upload error (after all retries):', error)
// 重新抛出错误,让上层处理
throw new Error('S3上传失败,请稍后重试')
}
}
export async function deleteFromS3(fileUrl: string): Promise<void> {

View File

@ -17,6 +17,7 @@ model User {
username String @unique
password String
department String @default("") // 用户部门
managedDepartment String? // 管理员负责的部门(如果是部门管理员)
role Role @default(USER)
isActive Boolean @default(false) // 是否激活,默认未激活
canDownload Boolean @default(true) // 是否允许下载,默认允许
@ -43,6 +44,7 @@ model Material {
productModel String // SPU
categoryName String // 使用店铺
sceneName String // 场景类别
platformName String @default("") // 平台分类(可选)
materialType String @default("3DMAX") // 素材类型:3DMAX/PSD/AI/CAD/C4D/材质/模特/标准饰品/其他
renderer String @default("CR") // 渲染器:CR/VR/其它(仅3DMAX使用)
authorName String // 作者花名
@ -64,6 +66,7 @@ model Material {
@@index([createdAt])
@@index([categoryName])
@@index([sceneName])
@@index([platformName])
@@index([materialType])
@@index([downloadCount])
@@index([likeCount])
@ -100,6 +103,14 @@ model Scene {
@@map("scenes")
}
model Platform {
id String @id @default(uuid())
name String @unique // 平台分类名称
createdAt DateTime @default(now())
@@map("platforms")
}
model SystemSettings {
id String @id @default(uuid())
headerBgColor String @default("#1f2937") // 顶部导航栏背景色

Binary file not shown.