diff --git a/src/App.tsx b/src/App.tsx
index d2e487b..bcccc15 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -22,6 +22,7 @@ import FlowTreeGuidePage from './pages/flowNodes/FlowTreeGuidePage'
import NotificationsPage from "@/pages/notifications/NotificationsPage.tsx"
import AdminLogsPage from './pages/adminLogs/AdminLogsPage'
import MonthlyOrdersSettingsPage from "@/pages/monthlyOrders/MonthlyOrdersSettingsPage.tsx";
+import TelegramManagersPage from "@/pages/telegramManagers/TelegramManagersPage.tsx";
const Placeholder = ({ title }: { title: string }) => (
@@ -73,6 +74,7 @@ function App() {
} />
} />
} />
+
} />
)
diff --git a/src/api/telegramManagers.ts b/src/api/telegramManagers.ts
new file mode 100644
index 0000000..beb6402
--- /dev/null
+++ b/src/api/telegramManagers.ts
@@ -0,0 +1,24 @@
+import axios from 'axios'
+
+// Изолированный клиент ТОЛЬКО для сервера менеджеров
+const managerApiClient = axios.create({
+ baseURL: 'https://37.252.5.229.nip.io/tg-api/api',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-API-Key': 'supersecretkey',
+ },
+})
+
+export const telegramManagersApi = {
+ getStatus: () =>
+ managerApiClient.get('/managers/status'),
+
+ sendCode: (phone: string, name: string) =>
+ managerApiClient.post('/managers/auth/send-code', { phone, name }),
+
+ verifyCode: (phone: string, code: string, password?: string) =>
+ managerApiClient.post('/managers/auth/verify-code', { phone, code, password }),
+
+ delete: (managerId: number) =>
+ managerApiClient.delete(`/managers/${managerId}`),
+}
\ No newline at end of file
diff --git a/src/components/Layout/Sidebar.tsx b/src/components/Layout/Sidebar.tsx
index 89e5547..6470293 100644
--- a/src/components/Layout/Sidebar.tsx
+++ b/src/components/Layout/Sidebar.tsx
@@ -18,7 +18,7 @@ import {
IconCheck,
IconBellRinging,
IconBlocks,
- IconHistory, IconChartBar,
+ IconHistory, IconChartBar, IconBrandTelegram,
} from '@tabler/icons-react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useAuth } from '@/hooks/useAuth'
@@ -43,6 +43,7 @@ const menuItems: MenuItem[] = [
adminOnly: true, // Скрываем от наблюдателей
// Если нужно скрыть от менеджеров, можно добавить флаг analystOnly: true и фильтровать
},
+ { label: 'Менеджеры Telegram', icon: IconBrandTelegram, path: '/telegram-managers', adminOnly: true },
{
label: 'Система согласований',
icon: IconFileCheck,
diff --git a/src/features/telegramManagers/useTelegramManagers.ts b/src/features/telegramManagers/useTelegramManagers.ts
new file mode 100644
index 0000000..3054680
--- /dev/null
+++ b/src/features/telegramManagers/useTelegramManagers.ts
@@ -0,0 +1,37 @@
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
+import { notifications } from '@mantine/notifications'
+import { telegramManagersApi } from '@/api/telegramManagers'
+
+export function useTelegramManagers() {
+ return useQuery({
+ queryKey: ['telegram-managers-status'],
+ queryFn: async () => {
+ const response = await telegramManagersApi.getStatus()
+ return response.data
+ },
+ refetchInterval: 10000, // Автоматическое обновление статуса каждые 10 секунд
+ })
+}
+
+export function useDeleteTelegramManager() {
+ const queryClient = useQueryClient()
+
+ return useMutation({
+ mutationFn: (managerId: number) => telegramManagersApi.delete(managerId),
+ onSuccess: () => {
+ notifications.show({
+ title: 'Успешно',
+ message: 'Сессия менеджера завершена',
+ color: 'green',
+ })
+ queryClient.invalidateQueries({ queryKey: ['telegram-managers-status'] })
+ },
+ onError: (error: any) => {
+ notifications.show({
+ title: 'Ошибка',
+ message: error.response?.data?.detail || 'Не удалось удалить сессию',
+ color: 'red',
+ })
+ },
+ })
+}
\ No newline at end of file
diff --git a/src/pages/telegramManagers/TelegramManagersPage.tsx b/src/pages/telegramManagers/TelegramManagersPage.tsx
new file mode 100644
index 0000000..611e62a
--- /dev/null
+++ b/src/pages/telegramManagers/TelegramManagersPage.tsx
@@ -0,0 +1,133 @@
+import { useState } from 'react'
+import {
+ Paper,
+ Table,
+ Badge,
+ Group,
+ ActionIcon,
+ Button,
+ Text,
+ Loader,
+ Center,
+ Tooltip,
+ Stack,
+ Box,
+} from '@mantine/core'
+import { IconTrash, IconPlus, IconCircleCheck, IconCircleX } from '@tabler/icons-react'
+import { modals } from '@mantine/modals'
+import AddManagerModal from './components/AddManagerModal'
+import dayjs from 'dayjs'
+import 'dayjs/locale/ru'
+import { formatMsk } from '@/utils/date.ts'
+import {useDeleteTelegramManager, useTelegramManagers} from "@/features/telegramManagers/useTelegramManagers.ts";
+
+dayjs.locale('ru')
+
+export default function TelegramManagersPage() {
+ const [createModalOpened, setCreateModalOpened] = useState(false)
+ const { data: managers, isLoading, isFetching } = useTelegramManagers()
+ const deleteManager = useDeleteTelegramManager()
+
+ const handleDelete = (managerId: number, name: string) => {
+ modals.openConfirmModal({
+ title: 'Подтвердите удаление сессии',
+ children: (
+
+ Вы уверены, что хотите отключить сессию менеджера {name}? Скрипт перестанет читать его переписку.
+
+ ),
+ labels: { confirm: 'Отключить', cancel: 'Отмена' },
+ confirmProps: { color: 'red' },
+ onConfirm: () => deleteManager.mutate(managerId),
+ })
+ }
+
+ return (
+
+
+
+ Менеджеры Telegram
+ Управление активными сессиями пользовательских аккаунтов (Userbot)
+
+ } onClick={() => setCreateModalOpened(true)}>
+ Подключить менеджера
+
+
+
+
+ {isLoading ? (
+
+ ) : (
+
+
+
+ ID
+ Имя
+ Телефон
+ Статус сессии
+ Последнее входящее
+ Последнее исходящее
+ Действия
+
+
+
+ {managers?.length === 0 ? (
+
+
+ Подключенные менеджеры не найдены
+
+
+ ) : (
+ managers?.map((mgr) => (
+
+ {mgr.manager_id}
+ {mgr.name}
+ +{mgr.phone}
+
+ : }
+ >
+ {mgr.is_online ? 'Онлайн (Активна)' : 'Оффлайн / Слетела'}
+
+
+
+
+ {mgr.last_incoming_message_at ? formatMsk(mgr.last_incoming_message_at) : '—'}
+
+
+
+
+ {mgr.last_outgoing_message_at ? formatMsk(mgr.last_outgoing_message_at) : '—'}
+
+
+
+
+ handleDelete(mgr.manager_id, mgr.name)}
+ >
+
+
+
+
+
+ ))
+ )}
+
+
+ )}
+
+
+ {isFetching && !isLoading && (
+
+
+
+ )}
+
+ setCreateModalOpened(false)} />
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/telegramManagers/components/AddManagerModal.tsx b/src/pages/telegramManagers/components/AddManagerModal.tsx
new file mode 100644
index 0000000..6d07f2b
--- /dev/null
+++ b/src/pages/telegramManagers/components/AddManagerModal.tsx
@@ -0,0 +1,112 @@
+import { useState } from 'react'
+import { Modal, Stack, TextInput, Button, Text, Alert, Group } from '@mantine/core'
+import { useForm } from '@mantine/form'
+import { notifications } from '@mantine/notifications'
+import { IconDeviceMobile, IconLock } from '@tabler/icons-react'
+import { useQueryClient } from '@tanstack/react-query'
+import {telegramManagersApi} from "@/api/telegramManagers.ts";
+
+interface AddManagerModalProps {
+ opened: boolean
+ onClose: () => void
+}
+
+export default function AddManagerModal({ opened, onClose }: AddManagerModalProps) {
+ const [step, setStep] = useState<'phone' | 'code'>('phone')
+ const [loading, setLoading] = useState(false)
+ const queryClient = useQueryClient()
+
+ const form = useForm({
+ initialValues: {
+ phone: '',
+ name: '',
+ code: '',
+ password: '',
+ },
+ })
+
+ const handleSendCode = async (values: typeof form.values) => {
+ setLoading(true)
+ try {
+ await telegramManagersApi.sendCode(values.phone, values.name)
+ notifications.show({ title: 'Код отправлен', message: 'Проверьте Telegram-аккаунт менеджера', color: 'green' })
+ setStep('code')
+ } catch (error: any) {
+ notifications.show({ title: 'Ошибка', message: error.response?.data?.detail || 'Не удалось отправить код', color: 'red' })
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ const handleVerifyCode = async (values: typeof form.values) => {
+ setLoading(true)
+ try {
+ await telegramManagersApi.verifyCode(values.phone, values.code, values.password || undefined)
+ notifications.show({ title: 'Успешно', message: 'Менеджер успешно авторизован и добавлен', color: 'green' })
+ queryClient.invalidateQueries({ queryKey: ['telegram-managers-status'] })
+ handleClose()
+ } catch (error: any) {
+ notifications.show({ title: 'Ошибка', message: error.response?.data?.detail || 'Неверный код или ошибка входа', color: 'red' })
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ const handleClose = () => {
+ setStep('phone')
+ form.reset()
+ onClose()
+ }
+
+ return (
+
+ {step === 'phone' ? (
+
+ ) : (
+
+ )}
+
+ )
+}
\ No newline at end of file
diff --git a/src/types/api.ts b/src/types/api.ts
index a2abbd2..5177c03 100644
--- a/src/types/api.ts
+++ b/src/types/api.ts
@@ -1,3 +1,17 @@
+export interface ManagerSession {
+ manager_id: number
+ name: string
+ phone: string
+ is_online: boolean
+ last_incoming_message_at: string | null
+ last_outgoing_message_at: string | null
+}
+
+export interface ManagersStatusResponse {
+ // Если ваш бэкенд возвращает массив напрямую или обертку, скорректируйте по аналогии
+ data: ManagerSession[]
+}
+
export interface User {
id?: number
telegram_id?: number