admin_ruspet/src/components/Layout/Sidebar.tsx

221 lines
8.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState, useMemo } from 'react'
import { NavLink, Box, Text, Stack, Badge } from '@mantine/core'
import {
IconDashboard,
IconFileCheck,
IconSettings,
IconChevronRight,
IconList,
IconUsers,
IconBuilding,
IconShield,
IconKey,
IconCategory,
IconBriefcase,
IconUserCheck,
IconGitBranch,
IconUserCog,
IconCheck,
IconBellRinging,
IconBlocks,
IconHistory, IconChartBar, IconBrandTelegram,
} from '@tabler/icons-react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useAuth } from '@/hooks/useAuth'
interface MenuItem {
label: string
icon?: any
path?: string
children?: MenuItem[]
adminOnly?: boolean // скрывать от наблюдателей
}
const menuItems: MenuItem[] = [
{ label: 'Обзор', icon: IconDashboard, path: '/' },
{ label: 'Администраторы', icon: IconUserCog, path: '/admins', adminOnly: true },
{ label: 'Уведомления', icon: IconBellRinging, path: '/notifications', adminOnly: true },
{ label: 'Журнал действий', icon: IconHistory, path: '/logs', adminOnly: true },
{
label: 'Заказы на месяц',
icon: IconChartBar,
path: '/monthly-orders-settings',
adminOnly: true, // Скрываем от наблюдателей
// Если нужно скрыть от менеджеров, можно добавить флаг analystOnly: true и фильтровать
},
{ label: 'Телефония', icon: IconBrandTelegram, path: '/telegram-managers', adminOnly: true },
{
label: 'Система согласований',
icon: IconFileCheck,
children: [
{ label: 'Панель управления', icon: IconDashboard, path: '/approval-dash', adminOnly: true },
{ label: 'Заявки', icon: IconList, path: '/approvals' },
{ label: 'Задачи', icon: IconCheck, path: '/approval-tasks' },
{ label: 'Пользователи', icon: IconUsers, path: '/users', adminOnly: true },
{ label: 'Отделы', icon: IconBuilding, path: '/departments', adminOnly: true },
{ label: 'Роли', icon: IconShield, path: '/roles', adminOnly: true },
{ label: 'Права', icon: IconKey, path: '/permissions', adminOnly: true },
{
label: 'Темы согласований',
icon: IconBriefcase,
adminOnly: true,
children: [
{ label: 'Настройки категорий', icon: IconCategory, path: '/categories' },
{ label: 'Настройки тем', icon: IconBriefcase, path: '/topics', adminOnly: true },
{ label: 'Исполнители', icon: IconUserCheck, path: '/executors', adminOnly: true },
]
},
{ label: 'Конструктор тем', icon: IconBlocks, path: '/nodes', adminOnly: true },
{ label: 'Иерархия', icon: IconGitBranch, path: '/hierarchies', adminOnly: true },
]
},
{ label: 'Настройки', icon: IconSettings, path: '/settings'},
]
function filterMenuByRole(items: MenuItem[], isObserver: boolean): MenuItem[] {
return items
.filter((item) => {
if (isObserver && item.adminOnly) return false
return true
})
.map((item) => {
if (item.children) {
const filteredChildren = filterMenuByRole(item.children, isObserver)
// Если после фильтрации детей не осталось — скрываем родителя
if (filteredChildren.length === 0) return null
return { ...item, children: filteredChildren }
}
return item
})
.filter((item): item is MenuItem => item !== null)
}
function MenuItemLink({ item, level }: { item: MenuItem; level: number }) {
const location = useLocation()
const navigate = useNavigate()
const [opened, setOpened] = useState(false)
const hasChildren = item.children && item.children.length > 0
const isActive = item.path ? location.pathname === item.path : false
const hasActiveChild = item.children?.some(child =>
child.path ? location.pathname === child.path : false
) || false
const paddingLeft = 16 + level * 20
if (hasChildren) {
return (
<Box>
<NavLink
label={item.label}
leftSection={item.icon ? <item.icon size={18} /> : undefined}
rightSection={
<IconChevronRight
size={16}
style={{
transform: opened ? 'rotate(90deg)' : 'none',
transition: 'transform 0.2s ease',
}}
/>
}
active={hasActiveChild}
onClick={() => setOpened(!opened)}
styles={{
root: {
paddingLeft,
paddingRight: 12,
borderRadius: '8px',
marginBottom: 2,
'&:hover': {
backgroundColor: 'var(--mantine-color-gray-0)',
},
},
}}
/>
{opened && (
<Stack gap={2} mt={2}>
{item.children!.map((child) => (
<MenuItemLink key={child.label} item={child} level={level + 1} />
))}
</Stack>
)}
</Box>
)
}
return (
<NavLink
label={item.label}
leftSection={item.icon ? <item.icon size={18} /> : undefined}
active={isActive}
onClick={() => {
if (item.path) navigate(item.path)
}}
styles={{
root: {
paddingLeft,
paddingRight: 12,
borderRadius: '8px',
marginBottom: 2,
'&:hover': {
backgroundColor: 'var(--mantine-color-gray-0)',
},
},
label: {
fontWeight: isActive ? 600 : 400,
},
}}
/>
)
}
export default function Sidebar() {
const { user } = useAuth()
const isObserver = user?.is_observer === true
const isAnalyst = user?.is_analyst === true || user?.is_root === true
// 🆕 Фильтруем меню в зависимости от роли
const filteredMenuItems = useMemo(
() => filterMenuByRole(menuItems, isObserver),
[isObserver]
)
return (
<Box
style={{
padding: '12px 8px',
height: '100%',
overflowY: 'auto',
}}
>
<Text
size="xs"
c="dimmed"
fw={700}
mb="md"
px="sm"
style={{
textTransform: 'uppercase',
letterSpacing: '0.5px',
}}
>
Главное меню
</Text>
{/* 🆕 Индикатор режима наблюдателя */}
{isObserver && (
<Box px="sm" mb="md">
<Badge color="blue" variant="light" size="sm" fullWidth>
Режим наблюдателя
</Badge>
</Box>
)}
<Stack gap={4}>
{filteredMenuItems.map((item) => (
<MenuItemLink key={item.label} item={item} level={0} />
))}
</Stack>
</Box>
)
}