Updated admins page. Added observer permission
Deploy Frontend / build-and-deploy (push) Successful in 26s
Details
Deploy Frontend / build-and-deploy (push) Successful in 26s
Details
This commit is contained in:
parent
c1cdb95557
commit
740669c90b
|
|
@ -12,6 +12,8 @@ export interface CreateAdminRequest {
|
||||||
login: string
|
login: string
|
||||||
name?: string
|
name?: string
|
||||||
is_root?: boolean
|
is_root?: boolean
|
||||||
|
is_observer?: boolean // 🆕
|
||||||
|
telegram_id?: number // 🆕
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateAdminRequest {
|
export interface UpdateAdminRequest {
|
||||||
|
|
@ -19,6 +21,8 @@ export interface UpdateAdminRequest {
|
||||||
name?: string
|
name?: string
|
||||||
is_blocked?: boolean
|
is_blocked?: boolean
|
||||||
is_root?: boolean
|
is_root?: boolean
|
||||||
|
is_observer?: boolean // 🆕
|
||||||
|
telegram_id?: number | null // 🆕
|
||||||
}
|
}
|
||||||
|
|
||||||
export const adminsApi = {
|
export const adminsApi = {
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { useState } from 'react'
|
import { useState, useMemo } from 'react'
|
||||||
import { NavLink, Box, Text, Stack } from '@mantine/core'
|
import { NavLink, Box, Text, Stack, Badge } from '@mantine/core'
|
||||||
import {
|
import {
|
||||||
IconDashboard,
|
IconDashboard,
|
||||||
IconFileCheck,
|
IconFileCheck,
|
||||||
|
|
@ -15,47 +15,70 @@ import {
|
||||||
IconUserCheck,
|
IconUserCheck,
|
||||||
IconGitBranch,
|
IconGitBranch,
|
||||||
IconUserCog,
|
IconUserCog,
|
||||||
IconCheck, IconBellRinging,
|
IconCheck,
|
||||||
|
IconBellRinging,
|
||||||
} from '@tabler/icons-react'
|
} from '@tabler/icons-react'
|
||||||
import { useLocation, useNavigate } from 'react-router-dom'
|
import { useLocation, useNavigate } from 'react-router-dom'
|
||||||
|
import { useAuth } from '@/hooks/useAuth'
|
||||||
|
|
||||||
interface MenuItem {
|
interface MenuItem {
|
||||||
label: string
|
label: string
|
||||||
icon?: any
|
icon?: any
|
||||||
path?: string
|
path?: string
|
||||||
children?: MenuItem[]
|
children?: MenuItem[]
|
||||||
|
adminOnly?: boolean // скрывать от наблюдателей
|
||||||
}
|
}
|
||||||
|
|
||||||
const menuItems: MenuItem[] = [
|
const menuItems: MenuItem[] = [
|
||||||
{ label: 'Обзор', icon: IconDashboard, path: '/' },
|
{ label: 'Обзор', icon: IconDashboard, path: '/' },
|
||||||
{ label: 'Администраторы', icon: IconUserCog, path: '/admins' },
|
{ label: 'Администраторы', icon: IconUserCog, path: '/admins', adminOnly: true },
|
||||||
{ label: 'Уведомления', icon: IconBellRinging, path: '/notifications' },
|
{ label: 'Уведомления', icon: IconBellRinging, path: '/notifications', adminOnly: true },
|
||||||
{
|
{
|
||||||
label: 'Система согласований',
|
label: 'Система согласований',
|
||||||
icon: IconFileCheck,
|
icon: IconFileCheck,
|
||||||
children: [
|
children: [
|
||||||
{ label: 'Панель управления', icon: IconDashboard, path: '/approval-dash' },
|
{ label: 'Панель управления', icon: IconDashboard, path: '/approval-dash', adminOnly: true },
|
||||||
{ label: 'Заявки', icon: IconList, path: '/approvals' },
|
{ label: 'Заявки', icon: IconList, path: '/approvals' },
|
||||||
{ label: 'Задачи', icon: IconCheck, path: '/approval-tasks' },
|
{ label: 'Задачи', icon: IconCheck, path: '/approval-tasks' },
|
||||||
{ label: 'Пользователи', icon: IconUsers, path: '/users' },
|
{ label: 'Пользователи', icon: IconUsers, path: '/users' },
|
||||||
{ label: 'Отделы', icon: IconBuilding, path: '/departments' },
|
{ label: 'Отделы', icon: IconBuilding, path: '/departments', adminOnly: true },
|
||||||
{ label: 'Роли', icon: IconShield, path: '/roles' },
|
{ label: 'Роли', icon: IconShield, path: '/roles', adminOnly: true },
|
||||||
{ label: 'Права', icon: IconKey, path: '/permissions' },
|
{ label: 'Права', icon: IconKey, path: '/permissions', adminOnly: true },
|
||||||
{
|
{
|
||||||
label: 'Темы согласований',
|
label: 'Темы согласований',
|
||||||
icon: IconBriefcase,
|
icon: IconBriefcase,
|
||||||
|
adminOnly: true,
|
||||||
children: [
|
children: [
|
||||||
{ label: 'Категории', icon: IconCategory, path: '/categories' },
|
{ label: 'Категории', icon: IconCategory, path: '/categories' },
|
||||||
{ label: 'Темы', icon: IconBriefcase, path: '/topics' },
|
{ label: 'Темы', icon: IconBriefcase, path: '/topics' },
|
||||||
{ label: 'Исполнители', icon: IconUserCheck, path: '/executors' },
|
{ label: 'Исполнители', icon: IconUserCheck, path: '/executors' },
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{ label: 'Иерархия', icon: IconGitBranch, path: '/hierarchies' },
|
{ label: 'Иерархия', icon: IconGitBranch, path: '/hierarchies', adminOnly: true },
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{ label: 'Настройки', icon: IconSettings, path: '/settings' },
|
{ 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 }) {
|
function MenuItemLink({ item, level }: { item: MenuItem; level: number }) {
|
||||||
const location = useLocation()
|
const location = useLocation()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
@ -67,7 +90,6 @@ function MenuItemLink({ item, level }: { item: MenuItem; level: number }) {
|
||||||
child.path ? location.pathname === child.path : false
|
child.path ? location.pathname === child.path : false
|
||||||
) || false
|
) || false
|
||||||
|
|
||||||
// ✅ Используем padding вместо marginLeft для правильного выравнивания
|
|
||||||
const paddingLeft = 16 + level * 20
|
const paddingLeft = 16 + level * 20
|
||||||
|
|
||||||
if (hasChildren) {
|
if (hasChildren) {
|
||||||
|
|
@ -137,6 +159,15 @@ function MenuItemLink({ item, level }: { item: MenuItem; level: number }) {
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Sidebar() {
|
export default function Sidebar() {
|
||||||
|
const { user } = useAuth()
|
||||||
|
const isObserver = user?.is_observer === true
|
||||||
|
|
||||||
|
// 🆕 Фильтруем меню в зависимости от роли
|
||||||
|
const filteredMenuItems = useMemo(
|
||||||
|
() => filterMenuByRole(menuItems, isObserver),
|
||||||
|
[isObserver]
|
||||||
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box
|
<Box
|
||||||
style={{
|
style={{
|
||||||
|
|
@ -159,8 +190,17 @@ export default function Sidebar() {
|
||||||
Главное меню
|
Главное меню
|
||||||
</Text>
|
</Text>
|
||||||
|
|
||||||
|
{/* 🆕 Индикатор режима наблюдателя */}
|
||||||
|
{isObserver && (
|
||||||
|
<Box px="sm" mb="md">
|
||||||
|
<Badge color="blue" variant="light" size="sm" fullWidth>
|
||||||
|
👁 Режим наблюдателя
|
||||||
|
</Badge>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
<Stack gap={4}>
|
<Stack gap={4}>
|
||||||
{menuItems.map((item) => (
|
{filteredMenuItems.map((item) => (
|
||||||
<MenuItemLink key={item.label} item={item} level={0} />
|
<MenuItemLink key={item.label} item={item} level={0} />
|
||||||
))}
|
))}
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,7 @@ export function useCreateAdmin() {
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (data: CreateAdminRequest) => {
|
mutationFn: async (data: CreateAdminRequest) => {
|
||||||
const response = await adminsApi.create(data)
|
const response = await adminsApi.create(data)
|
||||||
return response.data // ✅ Извлекаем Admin из AxiosResponse
|
return response.data
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [ADMINS_QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: [ADMINS_QUERY_KEY] })
|
||||||
|
|
@ -33,6 +33,10 @@ export function useCreateAdmin() {
|
||||||
message = 'Администратор с таким логином уже существует'
|
message = 'Администратор с таким логином уже существует'
|
||||||
} else if (errorMsg === 'only_root_can_create_admins') {
|
} else if (errorMsg === 'only_root_can_create_admins') {
|
||||||
message = 'Только root-администратор может создавать новых администраторов'
|
message = 'Только root-администратор может создавать новых администраторов'
|
||||||
|
} else if (errorMsg === 'telegram_id_required_for_observer') {
|
||||||
|
message = 'Для наблюдателя необходимо указать Telegram-аккаунт'
|
||||||
|
} else if (errorMsg === 'telegram_user_not_found') {
|
||||||
|
message = 'Пользователь с таким Telegram ID не найден в боте'
|
||||||
}
|
}
|
||||||
|
|
||||||
notifications.show({
|
notifications.show({
|
||||||
|
|
@ -65,6 +69,10 @@ export function useUpdateAdmin() {
|
||||||
message = 'Нельзя заблокировать root-администратора'
|
message = 'Нельзя заблокировать root-администратора'
|
||||||
} else if (errorMsg === 'cannot_block_self') {
|
} else if (errorMsg === 'cannot_block_self') {
|
||||||
message = 'Нельзя заблокировать свой собственный аккаунт'
|
message = 'Нельзя заблокировать свой собственный аккаунт'
|
||||||
|
} else if (errorMsg === 'telegram_id_required_for_observer') {
|
||||||
|
message = 'Для наблюдателя необходимо указать Telegram-аккаунт'
|
||||||
|
} else if (errorMsg === 'telegram_user_not_found') {
|
||||||
|
message = 'Пользователь с таким Telegram ID не найден в боте'
|
||||||
}
|
}
|
||||||
|
|
||||||
notifications.show({
|
notifications.show({
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ import {
|
||||||
IconLockOpen,
|
IconLockOpen,
|
||||||
IconPencil,
|
IconPencil,
|
||||||
IconShield,
|
IconShield,
|
||||||
|
IconUser,
|
||||||
} from '@tabler/icons-react'
|
} from '@tabler/icons-react'
|
||||||
import { modals } from '@mantine/modals'
|
import { modals } from '@mantine/modals'
|
||||||
import { notifications } from '@mantine/notifications'
|
import { notifications } from '@mantine/notifications'
|
||||||
|
|
@ -207,6 +208,8 @@ export default function AdminsPage() {
|
||||||
<Table.Th style={{ width: 60 }}>ID</Table.Th>
|
<Table.Th style={{ width: 60 }}>ID</Table.Th>
|
||||||
<Table.Th>Логин</Table.Th>
|
<Table.Th>Логин</Table.Th>
|
||||||
<Table.Th>Имя</Table.Th>
|
<Table.Th>Имя</Table.Th>
|
||||||
|
<Table.Th>Роль</Table.Th>
|
||||||
|
<Table.Th>Telegram</Table.Th>
|
||||||
<Table.Th>Создан</Table.Th>
|
<Table.Th>Создан</Table.Th>
|
||||||
<Table.Th>Последний вход</Table.Th>
|
<Table.Th>Последний вход</Table.Th>
|
||||||
<Table.Th>Последний IP</Table.Th>
|
<Table.Th>Последний IP</Table.Th>
|
||||||
|
|
@ -217,7 +220,7 @@ export default function AdminsPage() {
|
||||||
<Table.Tbody>
|
<Table.Tbody>
|
||||||
{data?.data?.length === 0 ? (
|
{data?.data?.length === 0 ? (
|
||||||
<Table.Tr>
|
<Table.Tr>
|
||||||
<Table.Td colSpan={8}>
|
<Table.Td colSpan={10}>
|
||||||
<Center p={40}>
|
<Center p={40}>
|
||||||
<Text c="dimmed">Администраторы не найдены</Text>
|
<Text c="dimmed">Администраторы не найдены</Text>
|
||||||
</Center>
|
</Center>
|
||||||
|
|
@ -253,6 +256,34 @@ export default function AdminsPage() {
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Text size="sm">{admin.name || '—'}</Text>
|
<Text size="sm">{admin.name || '—'}</Text>
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
<Group gap={4}>
|
||||||
|
{isAdminRoot && (
|
||||||
|
<Badge size="xs" color="red" variant="filled" leftSection={<IconShield size={10} />}>
|
||||||
|
ROOT
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{admin.is_observer && (
|
||||||
|
<Badge size="xs" color="blue" variant="filled" leftSection={<IconUser size={10} />}>
|
||||||
|
Наблюдатель
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{!isAdminRoot && !admin.is_observer && (
|
||||||
|
<Badge size="xs" color="gray" variant="light">
|
||||||
|
Админ
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
</Table.Td>
|
||||||
|
<Table.Td>
|
||||||
|
{admin.telegram_user ? (
|
||||||
|
<Text size="sm">{admin.telegram_user.full_name || admin.telegram_user.username || '—'}</Text>
|
||||||
|
) : admin.telegram_id ? (
|
||||||
|
<Text size="sm" c="dimmed">ID: {admin.telegram_id}</Text>
|
||||||
|
) : (
|
||||||
|
<Text size="sm" c="dimmed">—</Text>
|
||||||
|
)}
|
||||||
|
</Table.Td>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Text size="sm" c="dimmed">
|
<Text size="sm" c="dimmed">
|
||||||
{admin.created_at
|
{admin.created_at
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { useState } from 'react'
|
import { useState, useEffect } from 'react'
|
||||||
import {
|
import {
|
||||||
Modal,
|
Modal,
|
||||||
Stack,
|
Stack,
|
||||||
|
|
@ -13,10 +13,12 @@ import {
|
||||||
Paper,
|
Paper,
|
||||||
Code,
|
Code,
|
||||||
Switch,
|
Switch,
|
||||||
|
Select,
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { useForm } from '@mantine/form'
|
import { useForm } from '@mantine/form'
|
||||||
import { IconCheck, IconCopy, IconKey, IconAlertCircle, IconShield } from '@tabler/icons-react'
|
import { IconCheck, IconCopy, IconKey, IconAlertCircle, IconShield, IconUser } from '@tabler/icons-react'
|
||||||
import { useCreateAdmin } from '@/features/admins/hooks/useAdmins'
|
import { useCreateAdmin } from '@/features/admins/hooks/useAdmins'
|
||||||
|
import { useUsers } from '@/features/users/hooks/useUsers'
|
||||||
import type { Admin } from '@/types/api'
|
import type { Admin } from '@/types/api'
|
||||||
|
|
||||||
interface CreateAdminModalProps {
|
interface CreateAdminModalProps {
|
||||||
|
|
@ -27,12 +29,15 @@ interface CreateAdminModalProps {
|
||||||
export default function CreateAdminModal({ opened, onClose }: CreateAdminModalProps) {
|
export default function CreateAdminModal({ opened, onClose }: CreateAdminModalProps) {
|
||||||
const [createdAdmin, setCreatedAdmin] = useState<Admin | null>(null)
|
const [createdAdmin, setCreatedAdmin] = useState<Admin | null>(null)
|
||||||
const createAdmin = useCreateAdmin()
|
const createAdmin = useCreateAdmin()
|
||||||
|
const { data: usersData } = useUsers({ limit: 1000 })
|
||||||
|
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
initialValues: {
|
initialValues: {
|
||||||
login: '',
|
login: '',
|
||||||
name: '',
|
name: '',
|
||||||
is_root: false,
|
is_root: false,
|
||||||
|
is_observer: false,
|
||||||
|
telegram_id: null as number | null,
|
||||||
},
|
},
|
||||||
validate: {
|
validate: {
|
||||||
login: (value) => {
|
login: (value) => {
|
||||||
|
|
@ -40,15 +45,38 @@ export default function CreateAdminModal({ opened, onClose }: CreateAdminModalPr
|
||||||
if (!/^[a-zA-Z0-9_]+$/.test(value)) return 'Логин может содержать только буквы, цифры и подчеркивания'
|
if (!/^[a-zA-Z0-9_]+$/.test(value)) return 'Логин может содержать только буквы, цифры и подчеркивания'
|
||||||
return null
|
return null
|
||||||
},
|
},
|
||||||
|
telegram_id: (value, values) => {
|
||||||
|
if (values.is_observer && !value) {
|
||||||
|
return 'Для наблюдателя обязательно выберите Telegram-аккаунт'
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Сброс telegram_id при снятии галочки наблюдателя
|
||||||
|
useEffect(() => {
|
||||||
|
if (!form.values.is_observer) {
|
||||||
|
form.setFieldValue('telegram_id', null)
|
||||||
|
}
|
||||||
|
}, [form.values.is_observer])
|
||||||
|
|
||||||
|
// Опции пользователей Telegram (только те, у кого есть telegram_id)
|
||||||
|
const userOptions = usersData?.data
|
||||||
|
?.filter((u) => u.telegram_id && u.telegram_id > 0)
|
||||||
|
.map((u) => ({
|
||||||
|
value: String(u.telegram_id),
|
||||||
|
label: u.full_name || u.username || `ID: ${u.telegram_id}`,
|
||||||
|
})) || []
|
||||||
|
|
||||||
const handleSubmit = async (values: typeof form.values) => {
|
const handleSubmit = async (values: typeof form.values) => {
|
||||||
try {
|
try {
|
||||||
const admin = await createAdmin.mutateAsync({
|
const admin = await createAdmin.mutateAsync({
|
||||||
login: values.login,
|
login: values.login,
|
||||||
name: values.name || undefined,
|
name: values.name || undefined,
|
||||||
is_root: values.is_root,
|
is_root: values.is_root,
|
||||||
|
is_observer: values.is_observer,
|
||||||
|
telegram_id: values.is_observer ? values.telegram_id! : undefined,
|
||||||
})
|
})
|
||||||
setCreatedAdmin(admin)
|
setCreatedAdmin(admin)
|
||||||
form.reset()
|
form.reset()
|
||||||
|
|
@ -59,6 +87,7 @@ export default function CreateAdminModal({ opened, onClose }: CreateAdminModalPr
|
||||||
|
|
||||||
const handleClose = () => {
|
const handleClose = () => {
|
||||||
setCreatedAdmin(null)
|
setCreatedAdmin(null)
|
||||||
|
form.reset()
|
||||||
onClose()
|
onClose()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -84,6 +113,11 @@ export default function CreateAdminModal({ opened, onClose }: CreateAdminModalPr
|
||||||
Выданы root-права 👑
|
Выданы root-права 👑
|
||||||
</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
|
{createdAdmin.is_observer && (
|
||||||
|
<Text size="sm" fw={600} mt={4}>
|
||||||
|
Роль: Наблюдатель 👁
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
</Text>
|
</Text>
|
||||||
</Alert>
|
</Alert>
|
||||||
|
|
||||||
|
|
@ -158,9 +192,41 @@ export default function CreateAdminModal({ opened, onClose }: CreateAdminModalPr
|
||||||
checked={form.values.is_root}
|
checked={form.values.is_root}
|
||||||
onChange={(e) => form.setFieldValue('is_root', e.currentTarget.checked)}
|
onChange={(e) => form.setFieldValue('is_root', e.currentTarget.checked)}
|
||||||
color="red"
|
color="red"
|
||||||
|
disabled={form.values.is_observer}
|
||||||
/>
|
/>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
|
<Paper withBorder p="md" bg={form.values.is_observer ? 'blue.0' : 'gray.0'}>
|
||||||
|
<Switch
|
||||||
|
label={
|
||||||
|
<Group gap="xs">
|
||||||
|
<IconUser size={16} color="blue" />
|
||||||
|
<Text fw={600}>Наблюдатель</Text>
|
||||||
|
</Group>
|
||||||
|
}
|
||||||
|
description="Ограниченный доступ: только пользователи, заявки и задачи. Обязательна привязка к Telegram-аккаунту"
|
||||||
|
checked={form.values.is_observer}
|
||||||
|
onChange={(e) => form.setFieldValue('is_observer', e.currentTarget.checked)}
|
||||||
|
color="blue"
|
||||||
|
disabled={form.values.is_root}
|
||||||
|
/>
|
||||||
|
</Paper>
|
||||||
|
|
||||||
|
{form.values.is_observer && (
|
||||||
|
<Select
|
||||||
|
label="Telegram-аккаунт"
|
||||||
|
placeholder="Выберите пользователя"
|
||||||
|
data={userOptions}
|
||||||
|
value={form.values.telegram_id ? String(form.values.telegram_id) : null}
|
||||||
|
onChange={(v) => form.setFieldValue('telegram_id', v ? Number(v) : null)}
|
||||||
|
searchable
|
||||||
|
required
|
||||||
|
error={form.errors.telegram_id}
|
||||||
|
description="Пользователь бота, от имени которого будут выгружаться данные"
|
||||||
|
nothingFoundMessage="Пользователи не найдены"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{form.values.is_root && (
|
{form.values.is_root && (
|
||||||
<Alert icon={<IconAlertCircle size={16} />} color="red" variant="light">
|
<Alert icon={<IconAlertCircle size={16} />} color="red" variant="light">
|
||||||
<Text size="sm">
|
<Text size="sm">
|
||||||
|
|
@ -169,6 +235,14 @@ export default function CreateAdminModal({ opened, onClose }: CreateAdminModalPr
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{form.values.is_observer && (
|
||||||
|
<Alert icon={<IconAlertCircle size={16} />} color="blue" variant="light">
|
||||||
|
<Text size="sm">
|
||||||
|
<b>Наблюдатель</b> видит только пользователей, заявки и задачи. Данные выгружаются только те, что доступны выбранному Telegram-аккаунту в боте.
|
||||||
|
</Text>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
<Group justify="flex-end" mt="md">
|
<Group justify="flex-end" mt="md">
|
||||||
<Button variant="default" onClick={handleClose} disabled={createAdmin.isPending}>
|
<Button variant="default" onClick={handleClose} disabled={createAdmin.isPending}>
|
||||||
Отмена
|
Отмена
|
||||||
|
|
|
||||||
|
|
@ -10,11 +10,13 @@ import {
|
||||||
Switch,
|
Switch,
|
||||||
Paper,
|
Paper,
|
||||||
Alert,
|
Alert,
|
||||||
|
Select,
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { useForm } from '@mantine/form'
|
import { useForm } from '@mantine/form'
|
||||||
import { IconShield, IconAlertCircle } from '@tabler/icons-react'
|
import { IconShield, IconAlertCircle, IconUser } from '@tabler/icons-react'
|
||||||
import { useUpdateAdmin } from '@/features/admins/hooks/useAdmins'
|
import { useUpdateAdmin } from '@/features/admins/hooks/useAdmins'
|
||||||
import { useAuth } from '@/hooks/useAuth'
|
import { useAuth } from '@/hooks/useAuth'
|
||||||
|
import { useUsers } from '@/features/users/hooks/useUsers'
|
||||||
import type { Admin } from '@/types/api'
|
import type { Admin } from '@/types/api'
|
||||||
|
|
||||||
interface EditAdminModalProps {
|
interface EditAdminModalProps {
|
||||||
|
|
@ -26,11 +28,22 @@ interface EditAdminModalProps {
|
||||||
export default function EditAdminModal({ admin, opened, onClose }: EditAdminModalProps) {
|
export default function EditAdminModal({ admin, opened, onClose }: EditAdminModalProps) {
|
||||||
const updateAdmin = useUpdateAdmin()
|
const updateAdmin = useUpdateAdmin()
|
||||||
const { user: currentUser } = useAuth()
|
const { user: currentUser } = useAuth()
|
||||||
|
const { data: usersData } = useUsers({ limit: 1000 })
|
||||||
|
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
initialValues: {
|
initialValues: {
|
||||||
name: '',
|
name: '',
|
||||||
is_root: false,
|
is_root: false,
|
||||||
|
is_observer: false,
|
||||||
|
telegram_id: null as number | null,
|
||||||
|
},
|
||||||
|
validate: {
|
||||||
|
telegram_id: (value, values) => {
|
||||||
|
if (values.is_observer && !value) {
|
||||||
|
return 'Для наблюдателя обязательно выберите Telegram-аккаунт'
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -39,18 +52,35 @@ export default function EditAdminModal({ admin, opened, onClose }: EditAdminModa
|
||||||
form.setValues({
|
form.setValues({
|
||||||
name: admin.name || '',
|
name: admin.name || '',
|
||||||
is_root: admin.is_root ?? false,
|
is_root: admin.is_root ?? false,
|
||||||
|
is_observer: admin.is_observer ?? false,
|
||||||
|
telegram_id: admin.telegram_id || null,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}, [admin])
|
}, [admin])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!form.values.is_observer) {
|
||||||
|
form.setFieldValue('telegram_id', null)
|
||||||
|
}
|
||||||
|
}, [form.values.is_observer])
|
||||||
|
|
||||||
const isCurrentUser = currentUser?.id === admin?.id
|
const isCurrentUser = currentUser?.id === admin?.id
|
||||||
|
|
||||||
|
const userOptions = usersData?.data
|
||||||
|
?.filter((u) => u.telegram_id && u.telegram_id > 0)
|
||||||
|
.map((u) => ({
|
||||||
|
value: String(u.telegram_id),
|
||||||
|
label: u.full_name || u.username || `ID: ${u.telegram_id}`,
|
||||||
|
})) || []
|
||||||
|
|
||||||
const handleSubmit = async (values: typeof form.values) => {
|
const handleSubmit = async (values: typeof form.values) => {
|
||||||
if (!admin?.id) return
|
if (!admin?.id) return
|
||||||
await updateAdmin.mutateAsync({
|
await updateAdmin.mutateAsync({
|
||||||
id: admin.id,
|
id: admin.id,
|
||||||
name: values.name || undefined,
|
name: values.name || undefined,
|
||||||
is_root: values.is_root,
|
is_root: values.is_root,
|
||||||
|
is_observer: values.is_observer,
|
||||||
|
telegram_id: values.is_observer ? values.telegram_id! : null,
|
||||||
})
|
})
|
||||||
onClose()
|
onClose()
|
||||||
}
|
}
|
||||||
|
|
@ -68,6 +98,11 @@ export default function EditAdminModal({ admin, opened, onClose }: EditAdminModa
|
||||||
ROOT
|
ROOT
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
|
{admin?.is_observer && (
|
||||||
|
<Badge color="blue" variant="filled" leftSection={<IconUser size={12} />}>
|
||||||
|
Наблюдатель
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
</Group>
|
</Group>
|
||||||
}
|
}
|
||||||
size="md"
|
size="md"
|
||||||
|
|
@ -100,14 +135,45 @@ export default function EditAdminModal({ admin, opened, onClose }: EditAdminModa
|
||||||
checked={form.values.is_root}
|
checked={form.values.is_root}
|
||||||
onChange={(e) => form.setFieldValue('is_root', e.currentTarget.checked)}
|
onChange={(e) => form.setFieldValue('is_root', e.currentTarget.checked)}
|
||||||
color="red"
|
color="red"
|
||||||
disabled={isCurrentUser}
|
disabled={isCurrentUser || form.values.is_observer}
|
||||||
/>
|
/>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
|
<Paper withBorder p="md" bg={form.values.is_observer ? 'blue.0' : 'gray.0'}>
|
||||||
|
<Switch
|
||||||
|
label={
|
||||||
|
<Group gap="xs">
|
||||||
|
<IconUser size={16} color="blue" />
|
||||||
|
<Text fw={600}>Наблюдатель</Text>
|
||||||
|
</Group>
|
||||||
|
}
|
||||||
|
description="Ограниченный доступ: только пользователи, заявки и задачи"
|
||||||
|
checked={form.values.is_observer}
|
||||||
|
onChange={(e) => form.setFieldValue('is_observer', e.currentTarget.checked)}
|
||||||
|
color="blue"
|
||||||
|
disabled={isCurrentUser || form.values.is_root}
|
||||||
|
/>
|
||||||
|
</Paper>
|
||||||
|
|
||||||
|
{form.values.is_observer && (
|
||||||
|
<Select
|
||||||
|
label="Telegram-аккаунт"
|
||||||
|
placeholder="Выберите пользователя"
|
||||||
|
data={userOptions}
|
||||||
|
value={form.values.telegram_id ? String(form.values.telegram_id) : null}
|
||||||
|
onChange={(v) => form.setFieldValue('telegram_id', v ? Number(v) : null)}
|
||||||
|
searchable
|
||||||
|
required
|
||||||
|
error={form.errors.telegram_id}
|
||||||
|
description="Пользователь бота, от имени которого будут выгружаться данные"
|
||||||
|
nothingFoundMessage="Пользователи не найдены"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{isCurrentUser && (
|
{isCurrentUser && (
|
||||||
<Alert icon={<IconAlertCircle size={16} />} color="yellow" variant="light">
|
<Alert icon={<IconAlertCircle size={16} />} color="yellow" variant="light">
|
||||||
<Text size="sm">
|
<Text size="sm">
|
||||||
Вы не можете изменить свои собственные root-права.
|
Вы не можете изменить свои собственные права.
|
||||||
</Text>
|
</Text>
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
|
||||||
|
|
@ -53,6 +53,9 @@ export interface Admin {
|
||||||
login: string
|
login: string
|
||||||
name?: string
|
name?: string
|
||||||
is_root?: boolean
|
is_root?: boolean
|
||||||
|
is_observer?: boolean // 🆕
|
||||||
|
telegram_id?: number // 🆕
|
||||||
|
telegram_user?: User // 🆕
|
||||||
created_at?: string
|
created_at?: string
|
||||||
last_login?: string
|
last_login?: string
|
||||||
last_ip_login?: string
|
last_ip_login?: string
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue