342 lines
18 KiB
TypeScript
342 lines
18 KiB
TypeScript
import { useState, useEffect } from 'react'
|
||
import { usersApi, rolesApi, modulesApi } from '../api/client'
|
||
import { Search, Shield, Package, Plus, Edit, Trash2, X } from 'lucide-react'
|
||
|
||
export default function Users() {
|
||
const [users, setUsers] = useState<any[]>([])
|
||
const [roles, setRoles] = useState<any[]>([])
|
||
const [modules, setModules] = useState<any[]>([])
|
||
const [moduleRoles, setModuleRoles] = useState<any[]>([])
|
||
const [loading, setLoading] = useState(true)
|
||
const [search, setSearch] = useState('')
|
||
const [page, setPage] = useState(1)
|
||
const [total, setTotal] = useState(0)
|
||
const [selectedUser, setSelectedUser] = useState<any>(null)
|
||
const [showCreateForm, setShowCreateForm] = useState(false)
|
||
const [showEditForm, setShowEditForm] = useState(false)
|
||
const [editForm, setEditForm] = useState({ first_name: '', last_name: '', email: '', password: '', is_active: true, is_superadmin: false })
|
||
const [createForm, setCreateForm] = useState({ email: '', password: '', first_name: '', last_name: '', is_superadmin: false })
|
||
const [error, setError] = useState('')
|
||
const pageSize = 20
|
||
|
||
const fetchUsers = () => {
|
||
setLoading(true)
|
||
usersApi.list({ page, page_size: pageSize, search: search || undefined })
|
||
.then(res => { setUsers(res.data.users); setTotal(res.data.total) })
|
||
.finally(() => setLoading(false))
|
||
}
|
||
|
||
useEffect(() => { fetchUsers() }, [page])
|
||
useEffect(() => {
|
||
rolesApi.list().then(res => setRoles(res.data)).catch(() => {})
|
||
modulesApi.list().then(res => setModules(res.data)).catch(() => {})
|
||
}, [])
|
||
|
||
const loadModuleRoles = (moduleId: number) => {
|
||
modulesApi.getRoles(moduleId).then(res => setModuleRoles(res.data)).catch(() => {})
|
||
}
|
||
|
||
const handleAssignRole = async (userId: number, roleId: number) => {
|
||
await usersApi.assignRole(userId, roleId)
|
||
fetchUsers()
|
||
if (selectedUser?.id === userId) {
|
||
const res = await usersApi.get(userId)
|
||
setSelectedUser(res.data)
|
||
}
|
||
}
|
||
|
||
const handleRemoveRole = async (userId: number, roleId: number) => {
|
||
await usersApi.removeRole(userId, roleId)
|
||
fetchUsers()
|
||
if (selectedUser?.id === userId) {
|
||
const res = await usersApi.get(userId)
|
||
setSelectedUser(res.data)
|
||
}
|
||
}
|
||
|
||
const handleAssignModuleRole = async (userId: number, moduleRoleId: number) => {
|
||
await usersApi.assignModuleRole(userId, moduleRoleId)
|
||
fetchUsers()
|
||
if (selectedUser?.id === userId) {
|
||
const res = await usersApi.get(userId)
|
||
setSelectedUser(res.data)
|
||
}
|
||
}
|
||
|
||
const handleCreate = async (e: React.FormEvent) => {
|
||
e.preventDefault()
|
||
setError('')
|
||
try {
|
||
await usersApi.create(createForm)
|
||
setCreateForm({ email: '', password: '', first_name: '', last_name: '', is_superadmin: false })
|
||
setShowCreateForm(false)
|
||
fetchUsers()
|
||
} catch (err: any) {
|
||
setError(err.response?.data?.detail || 'Ошибка создания')
|
||
}
|
||
}
|
||
|
||
const handleEdit = async (e: React.FormEvent) => {
|
||
e.preventDefault()
|
||
if (!selectedUser) return
|
||
setError('')
|
||
try {
|
||
const data: any = { ...editForm }
|
||
if (!data.password) delete data.password
|
||
await usersApi.update(selectedUser.id, data)
|
||
setShowEditForm(false)
|
||
fetchUsers()
|
||
const res = await usersApi.get(selectedUser.id)
|
||
setSelectedUser(res.data)
|
||
} catch (err: any) {
|
||
setError(err.response?.data?.detail || 'Ошибка обновления')
|
||
}
|
||
}
|
||
|
||
const handleDelete = async (userId: number) => {
|
||
if (!confirm('Удалить пользователя? Это действие нельзя отменить.')) return
|
||
await usersApi.delete(userId)
|
||
fetchUsers()
|
||
if (selectedUser?.id === userId) {
|
||
setSelectedUser(null)
|
||
}
|
||
}
|
||
|
||
const openEditForm = (user: any) => {
|
||
setEditForm({
|
||
first_name: user.first_name,
|
||
last_name: user.last_name,
|
||
email: user.email,
|
||
password: '',
|
||
is_active: user.is_active,
|
||
is_superadmin: user.is_superadmin,
|
||
})
|
||
setShowEditForm(true)
|
||
setError('')
|
||
}
|
||
|
||
return (
|
||
<div>
|
||
<div className="flex items-center justify-between mb-6">
|
||
<h1 className="text-2xl font-bold text-gray-900">Пользователи</h1>
|
||
<button onClick={() => { setShowCreateForm(true); setError('') }} className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
|
||
<Plus className="w-4 h-4 mr-2" />Добавить
|
||
</button>
|
||
</div>
|
||
|
||
{/* Create form */}
|
||
{showCreateForm && (
|
||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||
<div className="flex items-center justify-between mb-4">
|
||
<h3 className="font-semibold">Новый пользователь</h3>
|
||
<button onClick={() => setShowCreateForm(false)}><X className="w-5 h-5 text-gray-400" /></button>
|
||
</div>
|
||
<form onSubmit={handleCreate} className="space-y-4">
|
||
<div className="grid grid-cols-2 gap-4">
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
|
||
<input type="text" value={createForm.first_name} onChange={e => setCreateForm({...createForm, first_name: e.target.value})} required
|
||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||
</div>
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Фамилия</label>
|
||
<input type="text" value={createForm.last_name} onChange={e => setCreateForm({...createForm, last_name: e.target.value})} required
|
||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||
</div>
|
||
</div>
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||
<input type="email" value={createForm.email} onChange={e => setCreateForm({...createForm, email: e.target.value})} required
|
||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||
</div>
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
|
||
<input type="password" value={createForm.password} onChange={e => setCreateForm({...createForm, password: e.target.value})} required minLength={6}
|
||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||
</div>
|
||
<label className="flex items-center gap-2">
|
||
<input type="checkbox" checked={createForm.is_superadmin} onChange={e => setCreateForm({...createForm, is_superadmin: e.target.checked})} className="rounded" />
|
||
<span className="text-sm text-gray-700">Суперадминистратор</span>
|
||
</label>
|
||
{error && <p className="text-red-500 text-sm">{error}</p>}
|
||
<div className="flex gap-2">
|
||
<button type="submit" className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">Создать</button>
|
||
<button type="button" onClick={() => setShowCreateForm(false)} className="px-4 py-2 border rounded-lg hover:bg-gray-100">Отмена</button>
|
||
</div>
|
||
</form>
|
||
</div>
|
||
)}
|
||
|
||
{/* Edit form */}
|
||
{showEditForm && selectedUser && (
|
||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||
<div className="flex items-center justify-between mb-4">
|
||
<h3 className="font-semibold">Редактирование: {selectedUser.first_name} {selectedUser.last_name}</h3>
|
||
<button onClick={() => setShowEditForm(false)}><X className="w-5 h-5 text-gray-400" /></button>
|
||
</div>
|
||
<form onSubmit={handleEdit} className="space-y-4">
|
||
<div className="grid grid-cols-2 gap-4">
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
|
||
<input type="text" value={editForm.first_name} onChange={e => setEditForm({...editForm, first_name: e.target.value})} required
|
||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||
</div>
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Фамилия</label>
|
||
<input type="text" value={editForm.last_name} onChange={e => setEditForm({...editForm, last_name: e.target.value})} required
|
||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||
</div>
|
||
</div>
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||
<input type="email" value={editForm.email} onChange={e => setEditForm({...editForm, email: e.target.value})} required
|
||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||
</div>
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Новый пароль (оставьте пустым, чтобы не менять)</label>
|
||
<input type="password" value={editForm.password} onChange={e => setEditForm({...editForm, password: e.target.value})} minLength={6}
|
||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||
</div>
|
||
<div className="flex gap-4">
|
||
<label className="flex items-center gap-2">
|
||
<input type="checkbox" checked={editForm.is_active} onChange={e => setEditForm({...editForm, is_active: e.target.checked})} className="rounded" />
|
||
<span className="text-sm text-gray-700">Активен</span>
|
||
</label>
|
||
<label className="flex items-center gap-2">
|
||
<input type="checkbox" checked={editForm.is_superadmin} onChange={e => setEditForm({...editForm, is_superadmin: e.target.checked})} className="rounded" />
|
||
<span className="text-sm text-gray-700">Суперадминистратор</span>
|
||
</label>
|
||
</div>
|
||
{error && <p className="text-red-500 text-sm">{error}</p>}
|
||
<div className="flex gap-2">
|
||
<button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Сохранить</button>
|
||
<button type="button" onClick={() => setShowEditForm(false)} className="px-4 py-2 border rounded-lg hover:bg-gray-100">Отмена</button>
|
||
</div>
|
||
</form>
|
||
</div>
|
||
)}
|
||
|
||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||
<form onSubmit={e => { e.preventDefault(); setPage(1); fetchUsers() }} className="flex gap-4">
|
||
<div className="flex-1 relative">
|
||
<Search className="absolute left-3 top-2.5 w-4 h-4 text-gray-400" />
|
||
<input type="text" value={search} onChange={e => setSearch(e.target.value)} placeholder="Поиск..."
|
||
className="w-full pl-10 pr-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||
</div>
|
||
<button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Найти</button>
|
||
</form>
|
||
</div>
|
||
|
||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||
<div className="lg:col-span-2 bg-white rounded-lg shadow overflow-hidden">
|
||
{loading ? <div className="p-8 text-center">Загрузка...</div> : (
|
||
<table className="w-full">
|
||
<thead className="bg-gray-50">
|
||
<tr>
|
||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Пользователь</th>
|
||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Роли</th>
|
||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Статус</th>
|
||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Действия</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody className="divide-y divide-gray-200">
|
||
{users.map(u => (
|
||
<tr key={u.id} className="hover:bg-gray-50 cursor-pointer" onClick={() => setSelectedUser(u)}>
|
||
<td className="px-4 py-3">
|
||
<p className="text-sm font-medium">{u.first_name} {u.last_name}</p>
|
||
<p className="text-xs text-gray-500">{u.email}</p>
|
||
</td>
|
||
<td className="px-4 py-3">
|
||
<div className="flex gap-1 flex-wrap">
|
||
{u.roles?.map((r: string) => <span key={r} className="px-2 py-0.5 text-xs bg-blue-100 text-blue-800 rounded-full">{r}</span>)}
|
||
</div>
|
||
</td>
|
||
<td className="px-4 py-3">
|
||
<span className={`px-2 py-1 text-xs rounded-full ${u.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
|
||
{u.is_active ? 'Активен' : 'Неактивен'}
|
||
</span>
|
||
</td>
|
||
<td className="px-4 py-3" onClick={e => e.stopPropagation()}>
|
||
<div className="flex gap-1">
|
||
<button onClick={() => { setSelectedUser(u); openEditForm(u) }} className="p-1 text-blue-500 hover:text-blue-700" title="Редактировать">
|
||
<Edit className="w-4 h-4" />
|
||
</button>
|
||
<button onClick={() => handleDelete(u.id)} className="p-1 text-red-500 hover:text-red-700" title="Удалить">
|
||
<Trash2 className="w-4 h-4" />
|
||
</button>
|
||
</div>
|
||
</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
)}
|
||
{total > pageSize && (
|
||
<div className="px-4 py-3 border-t flex justify-between">
|
||
<button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1} className="px-3 py-1 border rounded disabled:opacity-50">Назад</button>
|
||
<span className="text-sm text-gray-500">Страница {page}</span>
|
||
<button onClick={() => setPage(p => p + 1)} disabled={page * pageSize >= total} className="px-3 py-1 border rounded disabled:opacity-50">Далее</button>
|
||
</div>
|
||
)}
|
||
</div>
|
||
|
||
{selectedUser && !showEditForm && (
|
||
<div className="bg-white rounded-lg shadow p-4">
|
||
<div className="flex items-center justify-between mb-2">
|
||
<h3 className="font-semibold text-lg">{selectedUser.first_name} {selectedUser.last_name}</h3>
|
||
<button onClick={() => openEditForm(selectedUser)} className="text-blue-500 hover:text-blue-700">
|
||
<Edit className="w-4 h-4" />
|
||
</button>
|
||
</div>
|
||
<p className="text-sm text-gray-500 mb-4">{selectedUser.email}</p>
|
||
|
||
<div className="mb-4">
|
||
<h4 className="text-sm font-semibold text-gray-700 mb-2 flex items-center gap-1"><Shield className="w-4 h-4" /> Глобальные роли</h4>
|
||
<div className="space-y-1">
|
||
{roles.map(r => {
|
||
const assigned = selectedUser.roles?.includes(r.name)
|
||
return (
|
||
<div key={r.id} className="flex items-center justify-between text-sm">
|
||
<span>{r.name}</span>
|
||
{assigned ? (
|
||
<button onClick={() => handleRemoveRole(selectedUser.id, r.id)} className="text-red-500 hover:text-red-700 text-xs">Убрать</button>
|
||
) : (
|
||
<button onClick={() => handleAssignRole(selectedUser.id, r.id)} className="text-blue-500 hover:text-blue-700 text-xs">Назначить</button>
|
||
)}
|
||
</div>
|
||
)
|
||
})}
|
||
</div>
|
||
</div>
|
||
|
||
<div>
|
||
<h4 className="text-sm font-semibold text-gray-700 mb-2 flex items-center gap-1"><Package className="w-4 h-4" /> Роли модулей</h4>
|
||
{modules.map(mod => (
|
||
<div key={mod.id} className="mb-2">
|
||
<p className="text-xs font-medium text-gray-600">{mod.name}</p>
|
||
<button onClick={() => loadModuleRoles(mod.id)} className="text-xs text-blue-500 hover:text-blue-700">Загрузить роли</button>
|
||
<div className="mt-1 space-y-1">
|
||
{moduleRoles.filter(mr => mr.module_id === mod.id).map(mr => {
|
||
const assigned = selectedUser.module_roles?.[mod.slug]?.includes(mr.role_name)
|
||
return (
|
||
<div key={mr.id} className="flex items-center justify-between text-xs pl-2">
|
||
<span>{mr.role_name}</span>
|
||
{assigned ? (
|
||
<button onClick={() => usersApi.removeModuleRole(selectedUser.id, mr.id).then(() => { usersApi.get(selectedUser.id).then(r => setSelectedUser(r.data)); fetchUsers() })} className="text-red-500">Убрать</button>
|
||
) : (
|
||
<button onClick={() => handleAssignModuleRole(selectedUser.id, mr.id)} className="text-blue-500">Назначить</button>
|
||
)}
|
||
</div>
|
||
)
|
||
})}
|
||
</div>
|
||
</div>
|
||
))}
|
||
</div>
|
||
</div>
|
||
)}
|
||
</div>
|
||
</div>
|
||
)
|
||
}
|