TT-005: unify platform frontend and permissions
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { Routes, Route, Navigate } from 'react-router-dom'
|
||||
import { AuthProvider, useAuth } from './contexts/AuthContext'
|
||||
import Layout from './components/Layout'
|
||||
import PermissionGuard from './components/PermissionGuard'
|
||||
import Login from './pages/Login'
|
||||
import Register from './pages/Register'
|
||||
import Dashboard from './pages/Dashboard'
|
||||
@@ -24,9 +25,21 @@ export default function App() {
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/" element={<ProtectedRoute><Layout /></ProtectedRoute>}>
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="users" element={<Users />} />
|
||||
<Route path="roles" element={<Roles />} />
|
||||
<Route path="modules" element={<Modules />} />
|
||||
<Route path="users" element={
|
||||
<PermissionGuard permission="platform.users.read">
|
||||
<Users />
|
||||
</PermissionGuard>
|
||||
} />
|
||||
<Route path="roles" element={
|
||||
<PermissionGuard permission="platform.roles.read">
|
||||
<Roles />
|
||||
</PermissionGuard>
|
||||
} />
|
||||
<Route path="modules" element={
|
||||
<PermissionGuard permission="platform.modules.read">
|
||||
<Modules />
|
||||
</PermissionGuard>
|
||||
} />
|
||||
<Route path="module/:id" element={<ModuleView />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
|
||||
@@ -2,23 +2,52 @@ import { useState, useEffect } from 'react'
|
||||
import { Outlet, Link, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { Package, LogOut } from 'lucide-react'
|
||||
import { Package, LogOut, LayoutDashboard, Users, Key, Puzzle } from 'lucide-react'
|
||||
|
||||
interface NavItem {
|
||||
label: string
|
||||
path: string
|
||||
icon: any
|
||||
permission?: string
|
||||
}
|
||||
|
||||
const navigation: NavItem[] = [
|
||||
{ label: 'Панель', path: '/', icon: LayoutDashboard, permission: 'platform.dashboard.read' },
|
||||
{ label: 'Пользователи', path: '/users', icon: Users, permission: 'platform.users.read' },
|
||||
{ label: 'Роли', path: '/roles', icon: Key, permission: 'platform.roles.read' },
|
||||
{ label: 'Модули', path: '/modules', icon: Puzzle, permission: 'platform.modules.read' },
|
||||
]
|
||||
|
||||
export default function Layout() {
|
||||
const { user, logout } = useAuth()
|
||||
const { user, logout, hasPermission } = useAuth()
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const [modules, setModules] = useState<any[]>([])
|
||||
|
||||
const isAdmin = user?.is_superadmin || user?.roles?.includes('platform_admin')
|
||||
const isModuleView = location.pathname.startsWith('/module/')
|
||||
|
||||
useEffect(() => {
|
||||
modulesApi.list().then(res => setModules(res.data.filter((m: any) => m.is_active))).catch(() => {})
|
||||
modulesApi.list()
|
||||
.then(res => {
|
||||
const activeModules = res.data.filter((m: any) => m.is_active)
|
||||
setModules(activeModules)
|
||||
})
|
||||
.catch(() => {})
|
||||
}, [])
|
||||
|
||||
const handleLogout = () => { logout(); navigate('/login') }
|
||||
|
||||
// Filter navigation items based on permissions
|
||||
const visibleNav = navigation.filter(item =>
|
||||
!item.permission || hasPermission(item.permission)
|
||||
)
|
||||
|
||||
// Filter modules based on permissions
|
||||
const visibleModules = modules.filter(mod => {
|
||||
// Check if user has at least read permission for the module
|
||||
return hasPermission(`${mod.id}.read`) || user?.is_superadmin
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-screen bg-gray-100">
|
||||
{/* Top header */}
|
||||
@@ -28,45 +57,56 @@ export default function Layout() {
|
||||
<div className="flex items-center gap-6">
|
||||
<Link to="/" className="text-lg font-bold text-gray-800 whitespace-nowrap">Платформа</Link>
|
||||
<nav className="flex items-center gap-1">
|
||||
<Link to="/"
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname === '/' ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
Панель
|
||||
</Link>
|
||||
{isAdmin && (
|
||||
<>
|
||||
<Link to="/users"
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname.startsWith('/users') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
Пользователи
|
||||
</Link>
|
||||
<Link to="/roles"
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname.startsWith('/roles') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
Роли
|
||||
</Link>
|
||||
<Link to="/modules"
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname.startsWith('/modules') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
Модули
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
{visibleNav.map(item => (
|
||||
<Link
|
||||
key={item.path}
|
||||
to={item.path}
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors flex items-center gap-1.5 ${
|
||||
location.pathname === item.path
|
||||
? 'bg-blue-50 text-blue-700 font-medium'
|
||||
: 'text-gray-600 hover:bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
<item.icon className="w-4 h-4" />
|
||||
{item.label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{/* Center: module tabs */}
|
||||
{modules.length > 0 && (
|
||||
{visibleModules.length > 0 && (
|
||||
<div className="flex items-center gap-1">
|
||||
{modules.map(mod => (
|
||||
<Link key={mod.id} to={`/module/${mod.id}`}
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors flex items-center gap-1.5 ${location.pathname === `/module/${mod.id}` ? 'bg-blue-600 text-white font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
<Package className="w-3.5 h-3.5" />{mod.name}
|
||||
{visibleModules.map(mod => (
|
||||
<Link
|
||||
key={mod.id}
|
||||
to={`/module/${mod.id}`}
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors flex items-center gap-1.5 ${
|
||||
location.pathname === `/module/${mod.id}`
|
||||
? 'bg-blue-600 text-white font-medium'
|
||||
: 'text-gray-600 hover:bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
<Package className="w-3.5 h-3.5" />
|
||||
{mod.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Right: logout */}
|
||||
<button onClick={handleLogout} className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded-md">
|
||||
<LogOut className="w-4 h-4" />Выход
|
||||
</button>
|
||||
{/* Right: user info + logout */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="text-right">
|
||||
<p className="text-sm font-medium text-gray-700">{user?.first_name} {user?.last_name}</p>
|
||||
<p className="text-xs text-gray-500">{user?.email}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded-md"
|
||||
>
|
||||
<LogOut className="w-4 h-4" />Выход
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
|
||||
interface PermissionGuardProps {
|
||||
children: ReactNode
|
||||
permission?: string
|
||||
permissions?: string[]
|
||||
requireAll?: boolean
|
||||
fallback?: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Guard component that checks user permissions before rendering children.
|
||||
*
|
||||
* Usage:
|
||||
* <PermissionGuard permission="platform.users.read">
|
||||
* <UsersPage />
|
||||
* </PermissionGuard>
|
||||
*
|
||||
* <PermissionGuard permissions={["platform.users.read", "platform.users.write"]} requireAll>
|
||||
* <UsersEditPage />
|
||||
* </PermissionGuard>
|
||||
*/
|
||||
export default function PermissionGuard({
|
||||
children,
|
||||
permission,
|
||||
permissions,
|
||||
requireAll = false,
|
||||
fallback,
|
||||
}: PermissionGuardProps) {
|
||||
const { user, loading, hasPermission, hasAnyPermission } = useAuth()
|
||||
|
||||
if (loading) {
|
||||
return <div className="flex items-center justify-center h-screen">Загрузка...</div>
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return <Navigate to="/login" />
|
||||
}
|
||||
|
||||
// Check single permission
|
||||
if (permission && !hasPermission(permission)) {
|
||||
if (fallback) return <>{fallback}</>
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="text-center">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-2">403</h2>
|
||||
<p className="text-gray-500">Нет прав доступа</p>
|
||||
<p className="text-sm text-gray-400 mt-1">Требуется: {permission}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Check multiple permissions
|
||||
if (permissions && permissions.length > 0) {
|
||||
const hasAccess = requireAll
|
||||
? permissions.every(p => hasPermission(p))
|
||||
: hasAnyPermission(permissions)
|
||||
|
||||
if (!hasAccess) {
|
||||
if (fallback) return <>{fallback}</>
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="text-center">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-2">403</h2>
|
||||
<p className="text-gray-500">Нет прав доступа</p>
|
||||
<p className="text-sm text-gray-400 mt-1">
|
||||
Требуется: {permissions.join(requireAll ? ' + ' : ' или ')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createContext, useContext, useState, useEffect } from 'react'
|
||||
import { createContext, useContext, useState, useEffect, useCallback } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { authApi } from '../api/client'
|
||||
|
||||
@@ -11,6 +11,7 @@ interface User {
|
||||
is_superadmin: boolean
|
||||
roles: string[]
|
||||
module_roles: Record<string, string[]>
|
||||
permissions: string[]
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
@@ -18,6 +19,8 @@ interface AuthContextType {
|
||||
loading: boolean
|
||||
login: (email: string, password: string) => Promise<void>
|
||||
logout: () => void
|
||||
hasPermission: (permission: string) => boolean
|
||||
hasAnyPermission: (permissions: string[]) => boolean
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
||||
@@ -49,8 +52,20 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
setUser(null)
|
||||
}
|
||||
|
||||
const hasPermission = useCallback((permission: string): boolean => {
|
||||
if (!user) return false
|
||||
if (user.is_superadmin) return true
|
||||
return user.permissions?.includes(permission) ?? false
|
||||
}, [user])
|
||||
|
||||
const hasAnyPermission = useCallback((permissions: string[]): boolean => {
|
||||
if (!user) return false
|
||||
if (user.is_superadmin) return true
|
||||
return permissions.some(p => user.permissions?.includes(p) ?? false)
|
||||
}, [user])
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout }}>
|
||||
<AuthContext.Provider value={{ user, loading, login, logout, hasPermission, hasAnyPermission }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useState, useCallback } from 'react'
|
||||
|
||||
/**
|
||||
* Hook for managing async operations with loading state and duplicate-action protection.
|
||||
*
|
||||
* Usage:
|
||||
* const { loading, execute } = useAsyncAction()
|
||||
*
|
||||
* const handleDelete = async () => {
|
||||
* await execute(async () => {
|
||||
* await usersApi.delete(userId)
|
||||
* fetchUsers()
|
||||
* })
|
||||
* }
|
||||
*
|
||||
* <button onClick={handleDelete} disabled={loading}>
|
||||
* {loading ? 'Удаление...' : 'Удалить'}
|
||||
* </button>
|
||||
*/
|
||||
export function useAsyncAction() {
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const execute = useCallback(async (action: () => Promise<void>): Promise<boolean> => {
|
||||
if (loading) return false
|
||||
setLoading(true)
|
||||
try {
|
||||
await action()
|
||||
return true
|
||||
} catch (error) {
|
||||
throw error
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [loading])
|
||||
|
||||
return { loading, execute }
|
||||
}
|
||||
@@ -1,14 +1,11 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { ExternalLink, Loader2 } from 'lucide-react'
|
||||
|
||||
const isDev = import.meta.env.DEV
|
||||
|
||||
/**
|
||||
* Get the frontend URL for a module based on environment.
|
||||
* Returns null if frontend info is not available.
|
||||
*/
|
||||
function getModuleFrontend(module: any): string | null {
|
||||
if (!module.frontend) return null
|
||||
const url = isDev ? module.frontend.dev_url : module.frontend.prod_path
|
||||
@@ -17,6 +14,7 @@ function getModuleFrontend(module: any): string | null {
|
||||
|
||||
export default function ModuleView() {
|
||||
const { id } = useParams()
|
||||
const { hasPermission, loading: authLoading } = useAuth()
|
||||
const [module, setModule] = useState<any>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [iframeLoading, setIframeLoading] = useState(true)
|
||||
@@ -32,8 +30,11 @@ export default function ModuleView() {
|
||||
.finally(() => setLoading(false))
|
||||
}, [id])
|
||||
|
||||
// Permission check
|
||||
const hasAccess = module ? hasPermission(`${module.id}.read`) : false
|
||||
|
||||
useEffect(() => {
|
||||
if (!module) return
|
||||
if (!module || !hasAccess) return
|
||||
|
||||
const frontendUrl = getModuleFrontend(module)
|
||||
if (!frontendUrl) {
|
||||
@@ -84,18 +85,37 @@ export default function ModuleView() {
|
||||
window.removeEventListener('storage', handleStorage)
|
||||
clearInterval(interval)
|
||||
}
|
||||
}, [module])
|
||||
}, [module, hasAccess])
|
||||
|
||||
useEffect(() => {
|
||||
setIframeLoading(true)
|
||||
}, [id])
|
||||
|
||||
if (loading) return (
|
||||
if (loading || authLoading) return (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-blue-500" />
|
||||
</div>
|
||||
)
|
||||
|
||||
if (!module) return (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<p className="text-gray-500">Модуль не найден</p>
|
||||
</div>
|
||||
)
|
||||
|
||||
// Permission check - show 403 if no access
|
||||
if (!hasAccess) {
|
||||
return (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-2">403</h2>
|
||||
<p className="text-gray-500">Нет прав доступа к модулю</p>
|
||||
<p className="text-sm text-gray-400 mt-1">Требуется: {module.id}.read</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) return (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
@@ -105,12 +125,6 @@ export default function ModuleView() {
|
||||
</div>
|
||||
)
|
||||
|
||||
if (!module) return (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<p className="text-gray-500">Модуль не найден</p>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col h-full">
|
||||
<div className="flex items-center justify-between px-6 py-3 bg-white border-b flex-shrink-0">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { Plus, RefreshCw, Trash2, ExternalLink, Key } from 'lucide-react'
|
||||
import { Plus, RefreshCw, Trash2, ExternalLink, Key, Loader2 } from 'lucide-react'
|
||||
|
||||
export default function Modules() {
|
||||
const navigate = useNavigate()
|
||||
@@ -16,65 +16,64 @@ export default function Modules() {
|
||||
icon: 'Package',
|
||||
})
|
||||
const [error, setError] = useState('')
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [syncingId, setSyncingId] = useState<number | null>(null)
|
||||
const [syncResult, setSyncResult] = useState('')
|
||||
const [deletingId, setDeletingId] = useState<number | null>(null)
|
||||
const [expandedRoles, setExpandedRoles] = useState<number | null>(null)
|
||||
const [moduleRoles, setModuleRoles] = useState<any[]>([])
|
||||
|
||||
const fetchModules = () => {
|
||||
modulesApi
|
||||
.list()
|
||||
.then(res => setModules(res.data))
|
||||
.catch(() => {})
|
||||
modulesApi.list().then(res => setModules(res.data)).catch(() => {})
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchModules()
|
||||
}, [])
|
||||
useEffect(() => { fetchModules() }, [])
|
||||
|
||||
const handleCreate = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (creating) return
|
||||
setError('')
|
||||
|
||||
setCreating(true)
|
||||
try {
|
||||
const res = await modulesApi.create(form)
|
||||
|
||||
setForm({
|
||||
name: '',
|
||||
slug: '',
|
||||
url: '',
|
||||
description: '',
|
||||
icon: 'Package',
|
||||
})
|
||||
|
||||
setForm({ name: '', slug: '', url: '', description: '', icon: 'Package' })
|
||||
setShowForm(false)
|
||||
fetchModules()
|
||||
|
||||
alert(
|
||||
`Модуль создан. API Key: ${res.data.api_key}\nСохраните его — он нужен для настройки модуля.`
|
||||
)
|
||||
alert(`Модуль создан. API Key: ${res.data.api_key}\nСохраните его — он нужен для настройки модуля.`)
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка')
|
||||
} finally {
|
||||
setCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSync = async (id: number) => {
|
||||
if (syncingId) return
|
||||
setSyncResult('')
|
||||
|
||||
setSyncingId(id)
|
||||
try {
|
||||
const res = await modulesApi.syncRoles(id)
|
||||
|
||||
setSyncResult(`Импортировано: ${res.data.message}`)
|
||||
fetchModules()
|
||||
} catch (err: any) {
|
||||
setSyncResult(`Ошибка: ${err.response?.data?.detail || err.message}`)
|
||||
} finally {
|
||||
setSyncingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
if (!confirm('Отключить модуль?')) return
|
||||
|
||||
await modulesApi.delete(id)
|
||||
fetchModules()
|
||||
if (deletingId) return
|
||||
setDeletingId(id)
|
||||
try {
|
||||
await modulesApi.delete(id)
|
||||
fetchModules()
|
||||
} catch (err: any) {
|
||||
alert(err.response?.data?.detail || 'Ошибка удаления')
|
||||
} finally {
|
||||
setDeletingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const toggleRoles = async (moduleId: number) => {
|
||||
@@ -83,34 +82,20 @@ export default function Modules() {
|
||||
setModuleRoles([])
|
||||
} else {
|
||||
setExpandedRoles(moduleId)
|
||||
|
||||
modulesApi
|
||||
.getRoles(moduleId)
|
||||
.then(res => setModuleRoles(res.data))
|
||||
.catch(() => {})
|
||||
modulesApi.getRoles(moduleId).then(res => setModuleRoles(res.data)).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
const handleOpenModule = (slug: string) => {
|
||||
if (!slug) {
|
||||
setError('У модуля отсутствует slug')
|
||||
return
|
||||
}
|
||||
|
||||
navigate(`/module/${slug}`)
|
||||
const handleOpenModule = (id: string) => {
|
||||
navigate(`/module/${id}`)
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900">Модули</h1>
|
||||
|
||||
<button
|
||||
onClick={() => setShowForm(!showForm)}
|
||||
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 onClick={() => setShowForm(!showForm)} 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>
|
||||
|
||||
@@ -119,196 +104,82 @@ export default function Modules() {
|
||||
<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={form.name}
|
||||
onChange={e =>
|
||||
setForm({
|
||||
...form,
|
||||
name: e.target.value,
|
||||
})
|
||||
}
|
||||
required
|
||||
placeholder="Service Desk"
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Название</label>
|
||||
<input type="text" value={form.name} onChange={e => setForm({...form, name: e.target.value})} required placeholder="Service Desk"
|
||||
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">
|
||||
Slug
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
value={form.slug}
|
||||
onChange={e =>
|
||||
setForm({
|
||||
...form,
|
||||
slug: e.target.value,
|
||||
})
|
||||
}
|
||||
required
|
||||
placeholder="service-desk"
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Slug</label>
|
||||
<input type="text" value={form.slug} onChange={e => setForm({...form, slug: e.target.value})} required placeholder="service-desk"
|
||||
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">
|
||||
URL
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
value={form.url}
|
||||
onChange={e =>
|
||||
setForm({
|
||||
...form,
|
||||
url: e.target.value,
|
||||
})
|
||||
}
|
||||
required
|
||||
placeholder="http://localhost:8000"
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">URL</label>
|
||||
<input type="text" value={form.url} onChange={e => setForm({...form, url: e.target.value})} required placeholder="http://localhost:8000"
|
||||
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={form.description}
|
||||
onChange={e =>
|
||||
setForm({
|
||||
...form,
|
||||
description: e.target.value,
|
||||
})
|
||||
}
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Описание</label>
|
||||
<input type="text" value={form.description} onChange={e => setForm({...form, description: e.target.value})}
|
||||
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-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={() => setShowForm(false)}
|
||||
className="px-4 py-2 border rounded-lg hover:bg-gray-100"
|
||||
>
|
||||
Отмена
|
||||
<button type="submit" disabled={creating}
|
||||
className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 flex items-center gap-2">
|
||||
{creating && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
{creating ? 'Подключение...' : 'Подключить'}
|
||||
</button>
|
||||
<button type="button" onClick={() => setShowForm(false)} className="px-4 py-2 border rounded-lg hover:bg-gray-100">Отмена</button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-red-500 text-sm">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{error && <p className="text-red-500 text-sm">{error}</p>}
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{syncResult && (
|
||||
<div className="bg-blue-50 text-blue-800 p-3 rounded-lg mb-4 text-sm">
|
||||
{syncResult}
|
||||
</div>
|
||||
<div className="bg-blue-50 text-blue-800 p-3 rounded-lg mb-4 text-sm">{syncResult}</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{modules.map(mod => (
|
||||
<div
|
||||
key={mod.id}
|
||||
className="bg-white rounded-lg shadow p-4"
|
||||
>
|
||||
<div key={mod.id} className="bg-white rounded-lg shadow p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="font-semibold text-lg">
|
||||
{mod.name}
|
||||
</h3>
|
||||
|
||||
<p className="text-sm text-gray-500">
|
||||
{mod.description}
|
||||
</p>
|
||||
|
||||
<p className="text-xs text-gray-400 mt-1">
|
||||
slug: {mod.slug}
|
||||
{' · '}
|
||||
ролей: {mod.roles_count ?? 0}
|
||||
</p>
|
||||
<h3 className="font-semibold text-lg">{mod.name}</h3>
|
||||
<p className="text-sm text-gray-500">{mod.description}</p>
|
||||
<p className="text-xs text-gray-400 mt-1">slug: {mod.slug} · ролей: {mod.roles_count ?? 0}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => toggleRoles(mod.id)}
|
||||
className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50"
|
||||
title="Роли"
|
||||
>
|
||||
<Key className="w-4 h-4" />
|
||||
Роли
|
||||
<button onClick={() => toggleRoles(mod.id)}
|
||||
className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50">
|
||||
<Key className="w-4 h-4" />Роли
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleSync(mod.id)}
|
||||
className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50"
|
||||
title="Синхронизировать роли"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
Синхронизировать
|
||||
<button onClick={() => handleSync(mod.id)} disabled={syncingId === mod.id}
|
||||
className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50 disabled:opacity-50">
|
||||
{syncingId === mod.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
|
||||
{syncingId === mod.id ? 'Синхронизация...' : 'Синхронизировать'}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleOpenModule(mod.slug)}
|
||||
className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50"
|
||||
title="Открыть модуль"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
Открыть
|
||||
<button onClick={() => handleOpenModule(mod.id)}
|
||||
className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50">
|
||||
<ExternalLink className="w-4 h-4" />Открыть
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleDelete(mod.id)}
|
||||
className="flex items-center px-3 py-2 text-sm border rounded-lg hover:bg-red-50 text-red-600"
|
||||
title="Отключить модуль"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
<button onClick={() => handleDelete(mod.id)} disabled={deletingId === mod.id}
|
||||
className="flex items-center px-3 py-2 text-sm border rounded-lg hover:bg-red-50 text-red-600 disabled:opacity-50">
|
||||
{deletingId === mod.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{expandedRoles === mod.id && (
|
||||
<div className="mt-4 pt-4 border-t">
|
||||
<h4 className="text-sm font-semibold mb-2">
|
||||
Роли модуля
|
||||
</h4>
|
||||
|
||||
<h4 className="text-sm font-semibold mb-2">Роли модуля</h4>
|
||||
{moduleRoles.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">
|
||||
Нет ролей. Нажмите "Синхронизировать".
|
||||
</p>
|
||||
<p className="text-sm text-gray-500">Нет ролей. Нажмите "Синхронизировать".</p>
|
||||
) : (
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
{moduleRoles.map(mr => (
|
||||
<span
|
||||
key={mr.id}
|
||||
className="px-3 py-1 text-sm bg-purple-100 text-purple-800 rounded-full"
|
||||
>
|
||||
{mr.role_name}
|
||||
</span>
|
||||
<span key={mr.id} className="px-3 py-1 text-sm bg-purple-100 text-purple-800 rounded-full">{mr.role_name}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
@@ -319,4 +190,4 @@ export default function Modules() {
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { rolesApi } from '../api/client'
|
||||
import { Plus, Trash2, Lock } from 'lucide-react'
|
||||
import { Plus, Trash2, Lock, Loader2 } from 'lucide-react'
|
||||
|
||||
export default function Roles() {
|
||||
const [roles, setRoles] = useState<any[]>([])
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [form, setForm] = useState({ name: '', description: '' })
|
||||
const [error, setError] = useState('')
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [deletingId, setDeletingId] = useState<number | null>(null)
|
||||
|
||||
const fetchRoles = () => { rolesApi.list().then(res => setRoles(res.data)).catch(() => {}) }
|
||||
useEffect(() => { fetchRoles() }, [])
|
||||
|
||||
const handleCreate = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (creating) return
|
||||
setError('')
|
||||
setCreating(true)
|
||||
try {
|
||||
await rolesApi.create(form)
|
||||
setForm({ name: '', description: '' })
|
||||
@@ -21,14 +25,24 @@ export default function Roles() {
|
||||
fetchRoles()
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка')
|
||||
} finally {
|
||||
setCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number, isSystem: boolean) => {
|
||||
if (isSystem) return
|
||||
if (!confirm('Удалить роль?')) return
|
||||
await rolesApi.delete(id)
|
||||
fetchRoles()
|
||||
if (deletingId) return
|
||||
setDeletingId(id)
|
||||
try {
|
||||
await rolesApi.delete(id)
|
||||
fetchRoles()
|
||||
} catch (err: any) {
|
||||
alert(err.response?.data?.detail || 'Ошибка удаления')
|
||||
} finally {
|
||||
setDeletingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -53,7 +67,11 @@ export default function Roles() {
|
||||
<input type="text" value={form.description} onChange={e => setForm({...form, description: e.target.value})}
|
||||
className="w-full px-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-green-600 text-white rounded-lg hover:bg-green-700">Создать</button>
|
||||
<button type="submit" disabled={creating}
|
||||
className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 flex items-center gap-2">
|
||||
{creating && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
{creating ? 'Создание...' : 'Создать'}
|
||||
</button>
|
||||
</form>
|
||||
{error && <p className="text-red-500 text-sm mt-2">{error}</p>}
|
||||
</div>
|
||||
@@ -83,8 +101,9 @@ export default function Roles() {
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
{!r.is_system && (
|
||||
<button onClick={() => handleDelete(r.id, r.is_system)} className="text-red-500 hover:text-red-700">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
<button onClick={() => handleDelete(r.id, r.is_system)} disabled={deletingId === r.id}
|
||||
className="text-red-500 hover:text-red-700 disabled:opacity-50">
|
||||
{deletingId === r.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { usersApi, rolesApi, modulesApi } from '../api/client'
|
||||
import { Search, Shield, Package, Plus, Edit, Trash2, X } from 'lucide-react'
|
||||
import { Search, Shield, Package, Plus, Edit, Trash2, X, Loader2 } from 'lucide-react'
|
||||
|
||||
export default function Users() {
|
||||
const [users, setUsers] = useState<any[]>([])
|
||||
@@ -17,6 +17,9 @@ export default function Users() {
|
||||
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 [creating, setCreating] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [deletingId, setDeletingId] = useState<number | null>(null)
|
||||
const pageSize = 20
|
||||
|
||||
const fetchUsers = () => {
|
||||
@@ -65,7 +68,9 @@ export default function Users() {
|
||||
|
||||
const handleCreate = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (creating) return
|
||||
setError('')
|
||||
setCreating(true)
|
||||
try {
|
||||
await usersApi.create(createForm)
|
||||
setCreateForm({ email: '', password: '', first_name: '', last_name: '', is_superadmin: false })
|
||||
@@ -73,13 +78,16 @@ export default function Users() {
|
||||
fetchUsers()
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка создания')
|
||||
} finally {
|
||||
setCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleEdit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!selectedUser) return
|
||||
if (!selectedUser || saving) return
|
||||
setError('')
|
||||
setSaving(true)
|
||||
try {
|
||||
const data: any = { ...editForm }
|
||||
if (!data.password) delete data.password
|
||||
@@ -90,15 +98,25 @@ export default function Users() {
|
||||
setSelectedUser(res.data)
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка обновления')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (userId: number) => {
|
||||
if (!confirm('Удалить пользователя? Это действие нельзя отменить.')) return
|
||||
await usersApi.delete(userId)
|
||||
fetchUsers()
|
||||
if (selectedUser?.id === userId) {
|
||||
setSelectedUser(null)
|
||||
if (deletingId) return
|
||||
setDeletingId(userId)
|
||||
try {
|
||||
await usersApi.delete(userId)
|
||||
fetchUsers()
|
||||
if (selectedUser?.id === userId) {
|
||||
setSelectedUser(null)
|
||||
}
|
||||
} catch (err: any) {
|
||||
alert(err.response?.data?.detail || 'Ошибка удаления')
|
||||
} finally {
|
||||
setDeletingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,7 +178,11 @@ export default function Users() {
|
||||
</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="submit" disabled={creating}
|
||||
className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 flex items-center gap-2">
|
||||
{creating && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
{creating ? 'Создание...' : 'Создать'}
|
||||
</button>
|
||||
<button type="button" onClick={() => setShowCreateForm(false)} className="px-4 py-2 border rounded-lg hover:bg-gray-100">Отмена</button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -209,7 +231,11 @@ export default function Users() {
|
||||
</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="submit" disabled={saving}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center gap-2">
|
||||
{saving && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
{saving ? 'Сохранение...' : 'Сохранить'}
|
||||
</button>
|
||||
<button type="button" onClick={() => setShowEditForm(false)} className="px-4 py-2 border rounded-lg hover:bg-gray-100">Отмена</button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -257,12 +283,13 @@ export default function Users() {
|
||||
</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="Редактировать">
|
||||
<div className="flex gap-2">
|
||||
<button onClick={() => openEditForm(u)} className="p-1 text-blue-500 hover:text-blue-700">
|
||||
<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 onClick={() => handleDelete(u.id)} disabled={deletingId === u.id}
|
||||
className="p-1 text-red-500 hover:text-red-700 disabled:opacity-50">
|
||||
{deletingId === u.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
Reference in New Issue
Block a user