mirror of
https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git
synced 2025-08-14 00:25:46 +02:00
Починка adm3
This commit is contained in:
166
backend/app/bot/parse_all_chats.py
Normal file
166
backend/app/bot/parse_all_chats.py
Normal file
@@ -0,0 +1,166 @@
|
||||
from telethon import TelegramClient
|
||||
from telethon.tl.types import User, Channel
|
||||
import asyncio
|
||||
import os
|
||||
from typing import List, Set
|
||||
import time
|
||||
|
||||
# Открытые чаты (можно получить список участников)
|
||||
OPEN_CHATS = [
|
||||
'https://t.me/imichatchallenge',
|
||||
'https://t.me/neironutii',
|
||||
'https://t.me/forgetmeai_chat',
|
||||
'https://t.me/incubeaichat',
|
||||
'https://t.me/neyrodev'
|
||||
]
|
||||
|
||||
# Закрытые чаты (получаем через сообщения)
|
||||
CLOSED_CHATS = [
|
||||
'https://t.me/neuroart0',
|
||||
'https://t.me/+szDfPREr1rpjMWRi',
|
||||
'https://t.me/saburov_chat',
|
||||
'https://t.me/integromat_russia',
|
||||
'https://t.me/+V2toPTWQB4RkYWRi'
|
||||
]
|
||||
|
||||
def remove_duplicates_from_file(filename: str) -> None:
|
||||
"""
|
||||
Удаляет дубликаты строк из файла и сохраняет только уникальные значения
|
||||
|
||||
Args:
|
||||
filename (str): Имя файла для обработки
|
||||
"""
|
||||
try:
|
||||
# Проверяем существование файла
|
||||
if not os.path.exists(filename):
|
||||
print(f"Файл {filename} не найден")
|
||||
return
|
||||
|
||||
# Читаем все строки из файла
|
||||
with open(filename, 'r', encoding='utf-8') as file:
|
||||
lines = file.readlines()
|
||||
|
||||
# Подсчитываем начальное количество строк
|
||||
initial_count = len(lines)
|
||||
|
||||
# Создаем множество уникальных строк (удаляем пробелы и пустые строки)
|
||||
unique_lines = set(line.strip() for line in lines if line.strip())
|
||||
|
||||
# Сортируем строки
|
||||
sorted_lines = sorted(unique_lines)
|
||||
|
||||
# Записываем уникальные значения обратно в файл
|
||||
with open(filename, 'w', encoding='utf-8') as file:
|
||||
for line in sorted_lines:
|
||||
file.write(f"{line}\n")
|
||||
|
||||
# Выводим статистику
|
||||
final_count = len(sorted_lines)
|
||||
removed_count = initial_count - final_count
|
||||
print(f"\nУдаление дубликатов из файла {filename}:")
|
||||
print(f"Было строк: {initial_count}")
|
||||
print(f"Стало строк: {final_count}")
|
||||
print(f"Удалено дубликатов: {removed_count}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Ошибка при обработке файла {filename}: {str(e)}")
|
||||
|
||||
async def get_users_from_participants(client: TelegramClient, chat_link: str) -> Set[str]:
|
||||
"""
|
||||
Получает список пользователей из участников чата (для открытых чатов)
|
||||
"""
|
||||
try:
|
||||
chat = await client.get_entity(chat_link)
|
||||
unique_usernames = set()
|
||||
|
||||
print(f"Получаю список участников из открытого чата {chat_link}...")
|
||||
async for participant in client.iter_participants(chat):
|
||||
if isinstance(participant, User) and not participant.bot and participant.username:
|
||||
unique_usernames.add(f"@{participant.username}")
|
||||
|
||||
print(f"Собрано {len(unique_usernames)} уникальных пользователей из {chat_link}")
|
||||
return unique_usernames
|
||||
|
||||
except Exception as e:
|
||||
print(f"Ошибка при обработке открытого чата {chat_link}: {str(e)}")
|
||||
return set()
|
||||
|
||||
async def get_users_from_messages(client: TelegramClient, chat_link: str) -> Set[str]:
|
||||
"""
|
||||
Получает список пользователей из истории сообщений (для закрытых чатов)
|
||||
"""
|
||||
try:
|
||||
chat = await client.get_entity(chat_link)
|
||||
unique_usernames = set()
|
||||
|
||||
print(f"Получаю сообщения из закрытого чата {chat_link}...")
|
||||
async for message in client.iter_messages(chat, limit=None):
|
||||
if message.sender and isinstance(message.sender, User) and not message.sender.bot:
|
||||
if message.sender.username:
|
||||
unique_usernames.add(f"@{message.sender.username}")
|
||||
|
||||
print(f"Собрано {len(unique_usernames)} уникальных пользователей из {chat_link}")
|
||||
return unique_usernames
|
||||
|
||||
except Exception as e:
|
||||
print(f"Ошибка при обработке закрытого чата {chat_link}: {str(e)}")
|
||||
return set()
|
||||
|
||||
async def main():
|
||||
# Инициализация клиента с заданными параметрами
|
||||
client = TelegramClient(
|
||||
session='anon15',
|
||||
api_id=22454710,
|
||||
api_hash='4eb535b17a9b8b832d985d269944b184',
|
||||
proxy=None,
|
||||
device_model='PC',
|
||||
system_version='1.0',
|
||||
app_version='1.0',
|
||||
lang_code='en',
|
||||
system_lang_code='en',
|
||||
connection_retries=5,
|
||||
auto_reconnect=True,
|
||||
timeout=10
|
||||
)
|
||||
|
||||
await client.start()
|
||||
|
||||
try:
|
||||
all_usernames = set()
|
||||
|
||||
# Обрабатываем открытые чаты
|
||||
print("\nОбработка открытых чатов...")
|
||||
for chat in OPEN_CHATS:
|
||||
try:
|
||||
usernames = await get_users_from_participants(client, chat)
|
||||
all_usernames.update(usernames)
|
||||
await asyncio.sleep(2)
|
||||
except Exception as e:
|
||||
print(f"Не удалось обработать открытый чат {chat}: {str(e)}")
|
||||
|
||||
# Обрабатываем закрытые чаты
|
||||
print("\nОбработка закрытых чатов...")
|
||||
for chat in CLOSED_CHATS:
|
||||
try:
|
||||
usernames = await get_users_from_messages(client, chat)
|
||||
all_usernames.update(usernames)
|
||||
await asyncio.sleep(2)
|
||||
except Exception as e:
|
||||
print(f"Не удалось обработать закрытый чат {chat}: {str(e)}")
|
||||
|
||||
# Сохраняем результаты в файл
|
||||
print(f"\nВсего найдено {len(all_usernames)} уникальных пользователей")
|
||||
with open('bigparsing', 'w', encoding='utf-8') as file:
|
||||
for username in sorted(all_usernames):
|
||||
file.write(f"{username}\n")
|
||||
|
||||
print(f"Результаты сохранены в файл 'bigparsing'")
|
||||
|
||||
# Удаляем дубликаты из файла
|
||||
remove_duplicates_from_file('bigparsing')
|
||||
|
||||
finally:
|
||||
await client.disconnect()
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
35
backend/app/bot/remove_duplicates.py
Normal file
35
backend/app/bot/remove_duplicates.py
Normal file
@@ -0,0 +1,35 @@
|
||||
def remove_duplicates(filename: str):
|
||||
"""
|
||||
Удаляет дубликаты из файла и сохраняет уникальные значения
|
||||
|
||||
Args:
|
||||
filename (str): Имя файла для обработки
|
||||
"""
|
||||
try:
|
||||
# Читаем все строки из файла
|
||||
with open(filename, 'r', encoding='utf-8') as file:
|
||||
lines = file.readlines()
|
||||
|
||||
# Убираем пробелы и пустые строки, создаем множество уникальных значений
|
||||
unique_lines = set(line.strip() for line in lines if line.strip())
|
||||
|
||||
# Сортируем строки для удобства чтения
|
||||
sorted_lines = sorted(unique_lines)
|
||||
|
||||
# Записываем уникальные значения обратно в файл
|
||||
with open(filename, 'w', encoding='utf-8') as file:
|
||||
for line in sorted_lines:
|
||||
file.write(f"{line}\n")
|
||||
|
||||
print(f"Обработка завершена:")
|
||||
print(f"Было строк: {len(lines)}")
|
||||
print(f"Стало строк: {len(sorted_lines)}")
|
||||
print(f"Удалено дубликатов: {len(lines) - len(sorted_lines)}")
|
||||
|
||||
except FileNotFoundError:
|
||||
print(f"Ошибка: Файл {filename} не найден")
|
||||
except Exception as e:
|
||||
print(f"Произошла ошибка: {str(e)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
remove_duplicates('userai.txt')
|
@@ -72,7 +72,7 @@ onMounted(fetchEmployees);
|
||||
@click="showAddForm = true"
|
||||
class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700"
|
||||
>
|
||||
Добавить сотрудника
|
||||
Добавить сотрудника222
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
@@ -1,64 +1,95 @@
|
||||
<template>
|
||||
<div class="container mx-auto px-4 py-8">
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<div class="space-y-6">
|
||||
<div class="flex justify-between items-center">
|
||||
<h1 class="text-2xl font-bold">Панель администратора</h1>
|
||||
<button
|
||||
@click="handleLogout"
|
||||
class="bg-red-600 text-white px-4 py-2 rounded-md hover:bg-red-700 transition-colors"
|
||||
<button
|
||||
@click="router.push('/admin/employees/add')"
|
||||
class="bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg flex items-center gap-2 transition-colors"
|
||||
>
|
||||
Выйти
|
||||
<PlusCircle class="w-5 h-5" />
|
||||
Добавить работника
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="bg-white rounded-lg shadow-lg p-6">
|
||||
<div class="border-b border-gray-200">
|
||||
<nav class="-mb-px flex space-x-8">
|
||||
<button
|
||||
v-for="tab in tabs"
|
||||
:key="tab.id"
|
||||
@click="currentTab = tab.id"
|
||||
:class="[
|
||||
currentTab === tab.id
|
||||
? 'border-blue-500 text-blue-600'
|
||||
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300',
|
||||
'whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm'
|
||||
]"
|
||||
>
|
||||
{{ tab.name }}
|
||||
</button>
|
||||
</nav>
|
||||
<!-- Statistics -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<div v-for="stat in statistics" :key="stat.period" class="bg-white p-4 rounded-lg shadow">
|
||||
<h3 class="text-lg font-semibold">{{ stat.label }}</h3>
|
||||
<p class="text-2xl font-bold">{{ stat.value }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-6">
|
||||
<StatisticsPanel v-if="currentTab === 'statistics'" />
|
||||
<RequestList v-if="currentTab === 'requests'" />
|
||||
<EmployeeList v-if="currentTab === 'employees'" />
|
||||
<!-- Requests -->
|
||||
<div class="bg-white rounded-lg shadow">
|
||||
<div class="p-4">
|
||||
<h2 class="text-xl font-semibold">Последние заявки</h2>
|
||||
</div>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full">
|
||||
<thead class="bg-gray-50">
|
||||
<tr>
|
||||
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
|
||||
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Сотрудник</th>
|
||||
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Тип</th>
|
||||
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Статус</th>
|
||||
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Дата</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="bg-white divide-y divide-gray-200">
|
||||
<tr v-for="request in requests" :key="request.id">
|
||||
<td class="px-6 py-4 whitespace-nowrap">{{ request.id }}</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap">{{ request.employee_last_name }}</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap">{{ request.request_type }}</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap">{{ request.status }}</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap">{{ formatDate(request.created_at) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import RequestList from '@/components/admin/RequestList.vue';
|
||||
import EmployeeList from '@/components/admin/EmployeeList.vue';
|
||||
import StatisticsPanel from '@/components/admin/StatisticsPanel.vue';
|
||||
import { PlusCircle } from 'lucide-vue-next';
|
||||
|
||||
const router = useRouter();
|
||||
const authStore = useAuthStore();
|
||||
const statistics = ref([]);
|
||||
const requests = ref([]);
|
||||
|
||||
const tabs = [
|
||||
{ id: 'statistics', name: 'Статистика' },
|
||||
{ id: 'requests', name: 'Заявки' },
|
||||
{ id: 'employees', name: 'Сотрудники' }
|
||||
];
|
||||
const formatDate = (date: string) => {
|
||||
return new Date(date).toLocaleString('ru-RU');
|
||||
};
|
||||
|
||||
const currentTab = ref('statistics');
|
||||
const fetchStatistics = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/admin/statistics?period=week');
|
||||
if (!response.ok) throw new Error('Failed to fetch statistics');
|
||||
const data = await response.json();
|
||||
statistics.value = [
|
||||
{ period: 'total', label: 'Всего заявок', value: data.totalRequests },
|
||||
{ period: 'resolved', label: 'Решено', value: data.resolvedRequests },
|
||||
{ period: 'avgTime', label: 'Среднее время', value: data.averageResolutionTime }
|
||||
];
|
||||
} catch (error) {
|
||||
console.error('Error fetching statistics:', error);
|
||||
}
|
||||
};
|
||||
|
||||
function handleLogout() {
|
||||
authStore.logout();
|
||||
router.push('/admin');
|
||||
}
|
||||
const fetchRequests = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/admin/requests');
|
||||
if (!response.ok) throw new Error('Failed to fetch requests');
|
||||
requests.value = await response.json();
|
||||
} catch (error) {
|
||||
console.error('Error fetching requests:', error);
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
fetchStatistics();
|
||||
fetchRequests();
|
||||
});
|
||||
</script>
|
Reference in New Issue
Block a user