Merge branch 'master' of git.smartsoltech.kr:trevor/touchh_bot

This commit is contained in:
2024-12-14 08:37:30 +09:00
20 changed files with 5927 additions and 194 deletions

2
.gitignore vendored
View File

@@ -12,5 +12,5 @@ package.json
old_bot old_bot
*.mmdb *.mmdb
*.log *.log
.sqlite3
# Ignore files # Ignore files

View File

@@ -51,13 +51,6 @@ class HotelAdmin(admin.ModelAdmin):
except Exception as e: except Exception as e:
self.message_user(request, f"Ошибка: {str(e)}", level="error") self.message_user(request, f"Ошибка: {str(e)}", level="error")
return redirect("..") return redirect("..")
@admin.register(FraudLog)
class FroudAdmin(admin.ModelAdmin):
list_display = ('hotel', 'reservation_id', 'guest_name', 'check_in_date', 'detected_at', 'message')
search_fields = ('hotel__name', 'reservation_id', 'guest_name', 'check_in_date', 'message')
list_filter = ('hotel', 'check_in_date', 'detected_at')
ordering = ('-detected_at',)
@admin.register(UserHotel) @admin.register(UserHotel)
class UserHotelAdmin(admin.ModelAdmin): class UserHotelAdmin(admin.ModelAdmin):
@@ -66,7 +59,6 @@ class UserHotelAdmin(admin.ModelAdmin):
# list_filter = ('hotel',) # list_filter = ('hotel',)
# ordering = ('-hotel',) # ordering = ('-hotel',)
@admin.register(Reservation) @admin.register(Reservation)
class ReservationAdmin(admin.ModelAdmin): class ReservationAdmin(admin.ModelAdmin):
list_display = ('reservation_id', 'hotel', 'room_number', 'room_type', 'check_in', 'check_out', 'status', 'price', 'discount') list_display = ('reservation_id', 'hotel', 'room_number', 'room_type', 'check_in', 'check_out', 'status', 'price', 'discount')

View File

@@ -0,0 +1,18 @@
# Generated by Django 5.1.4 on 2024-12-11 10:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hotels', '0003_initial'),
]
operations = [
migrations.AlterField(
model_name='reservation',
name='room_number',
field=models.CharField(blank=True, max_length=255, null=True),
),
]

View File

@@ -0,0 +1,29 @@
# Generated by Django 5.1.4 on 2024-12-13 01:01
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hotels', '0004_alter_reservation_room_number'),
]
operations = [
migrations.AddField(
model_name='hotel',
name='import_status',
field=models.CharField(choices=[('not_started', 'Не начат'), ('in_progress', 'В процессе'), ('completed', 'Завершен')], default='not_started', max_length=50, verbose_name='Статус импорта'),
),
migrations.AddField(
model_name='hotel',
name='imported_at',
field=models.DateTimeField(blank=True, null=True, verbose_name='Дата импорта'),
),
migrations.AddField(
model_name='hotel',
name='imported_from',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='imported_hotels', to='hotels.hotel', verbose_name='Импортированный отель'),
),
]

View File

@@ -88,7 +88,7 @@ class APIRequestLog(models.Model):
class Reservation(models.Model): class Reservation(models.Model):
hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, verbose_name="Отель") hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, verbose_name="Отель")
reservation_id = models.BigIntegerField(unique=True, verbose_name="ID бронирования") reservation_id = models.BigIntegerField(unique=True, verbose_name="ID бронирования")
room_number = models.CharField(max_length=50, verbose_name="Номер комнаты") room_number = models.CharField(max_length=255, null=True, blank=True)
room_type = models.CharField(max_length=255, verbose_name="Тип комнаты") room_type = models.CharField(max_length=255, verbose_name="Тип комнаты")
check_in = models.DateTimeField(verbose_name="Дата заезда") check_in = models.DateTimeField(verbose_name="Дата заезда")
check_out = models.DateTimeField(verbose_name="Дата выезда") check_out = models.DateTimeField(verbose_name="Дата выезда")

4302
import_hotels.log Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -3,7 +3,7 @@ import json
from datetime import datetime, timedelta from datetime import datetime, timedelta
from .base_plugin import BasePMSPlugin from .base_plugin import BasePMSPlugin
from asgiref.sync import sync_to_async from asgiref.sync import sync_to_async
from pms_integration.models import PMSConfiguration # Убедитесь, что модель существует from pms_integration.models import PMSConfiguration
class BnovoPMSPlugin(BasePMSPlugin): class BnovoPMSPlugin(BasePMSPlugin):

View File

@@ -1,11 +1,11 @@
from .base_plugin import BasePMSPlugin from .base_plugin import BasePMSPlugin
import requests
class EcviPMS(BasePMSPlugin): class EcviPMS(BasePMSPlugin):
""" """
Плагин для PMS Shelter. Плагин для PMS ECVI.
""" """
def fetch_data(self): def _fetch_data(self):
print("Fetching data from Ecvi PMS...") print("Fetching data from Ecvi PMS...")
# Реализация метода получения данных из PMS Shelter # Реализация метода получения данных из PMS Shelter
response = requests.get(self.pms_config.url, headers={"Authorization": f"Bearer {self.pms_config.token}"}) response = requests.get(self.pms_config.url, headers={"Authorization": f"Bearer {self.pms_config.token}"})

View File

@@ -1,103 +1,212 @@
import requests import requests
import json import json
from datetime import datetime, timedelta from datetime import datetime, timedelta, timezone
from asgiref.sync import sync_to_async
from .base_plugin import BasePMSPlugin
from hotels.models import Reservation
from hotels.models import Hotel
from asgiref.sync import sync_to_async
from hotels.models import Reservation, Hotel
from .base_plugin import BasePMSPlugin
from pms_integration.models import PMSConfiguration
class Shelter(BasePMSPlugin): class Shelter(BasePMSPlugin):
""" """
Плагин для PMS Shelter Coud. Плагин для интеграции с Shelter PMS.
""" """
def __init__(self, config): def __init__(self, pms_config):
super().__init__(config) super().__init__(pms_config)
self.token = config.token self.api_url = pms_config.url
self.token = pms_config.token
self.pagination_count = 50
def get_default_parser_settings(self): def get_default_parser_settings(self):
""" """
Возвращает настройки по умолчанию для обработки данных. Возвращает настройки по умолчанию для разбора данных PMS Shelter.
""" """
return { return {
"date_format": "%Y-%m-%dT%H:%M:%S", "fields_mapping": {
"timezone": "UTC" "reservation_id": "id",
} "hotel_id": "hotelId",
"hotel_name": "hotelName",
"check_in": "from",
"check_out": "until",
"reservation_date": "date",
"room_type_id": "roomTypeId",
"room_id": "roomId",
"room_number": "roomNumber",
"room_type_name": "roomTypeName",
"check_in_status": "checkInStatus",
"is_annul": "isAnnul",
"reservation_price": "reservationPrice",
"discount": "discount",
def _fetch_data(self): },
"date_format": "%Y-%m-%dT%H:%M:%S",
"timezone": "UTC",
}
async def _get_last_saved_date(self):
""" """
Выполняет запрос к API PMS для получения данных. Получает дату последнего сохраненного бронирования для отеля.
""" """
url = 'https://pms.frontdesk24.ru/sheltercloudapi/Reservations/ByFilter' try:
last_reservation = await sync_to_async(
Reservation.objects.filter(hotel__pms=self.pms_config).order_by('-check_in').first
)()
return last_reservation.check_in if last_reservation else None
except Exception as e:
print(f"[ERROR] Ошибка получения последнего сохраненного бронирования: {e}")
return None
async def _fetch_data(self):
"""
Получает данные о бронированиях из PMS.
Данные обрабатываются по временным промежуткам и сразу записываются в БД.
Возвращает отчёт о проделанной работе.
"""
now = datetime.utcnow().replace(tzinfo=timezone.utc)
start_date = await self._get_last_saved_date() or (now - timedelta(days=90))
end_date = now + timedelta(days=30)
headers = { headers = {
'accept': 'text/plain', 'accept': 'text/plain',
'Authorization': f'Bearer {self.token}', 'Authorization': f'Bearer {self.token}',
'Content-Type': 'application/json', 'Content-Type': 'application/json',
} }
from_index = 0 print(f"[DEBUG] Fetching data from {start_date} to {end_date}")
count_per_request = 50
total_count = None
all_items = []
now = datetime.now()
start_date = (now - timedelta(days=60)).strftime('%Y-%m-%dT%H:%M:%SZ')
end_date = (now + timedelta(days=60)).strftime('%Y-%m-%dT%H:%M:%SZ')
while total_count is None or from_index < total_count: # Результаты выполнения
data = { report = {
"from": start_date, "processed_intervals": 0,
"until": end_date, "processed_items": 0,
"pagination": { "errors": [],
"from": from_index, }
"count": count_per_request
} # Разделение на временные интервалы
interval_days = 5 # Например, каждые 5 дней
current_start_date = start_date
while current_start_date < end_date:
current_end_date = min(current_start_date + timedelta(days=interval_days), end_date)
# Формирование payload
payload = {
"from": current_start_date.strftime('%Y-%m-%dT%H:%M:%SZ'),
"until": current_end_date.strftime('%Y-%m-%dT%H:%M:%SZ'),
} }
print(f"[DEBUG] Sending payload: {json.dumps(payload)}")
response = requests.post(url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
response_data = response.json()
items = response_data.get("items", [])
all_items.extend(items)
if total_count is None:
total_count = response_data.get("count", 0)
from_index += len(items)
else:
raise ValueError(f'Shelter API Error: {response.status_code}')
return all_items
async def _save_to_db(self, data, hotel_id):
"""
Сохраняет данные о бронированиях в таблицу Reservation.
:param data: Список данных о бронированиях.
:param hotel_id: ID отеля, к которому относятся бронирования.
"""
hotel = await sync_to_async(Hotel.objects.get)(id=hotel_id)
for item in data:
print(f"Данные для сохранения: {item}")
try: try:
reservation, created = await sync_to_async(Reservation.objects.update_or_create)( response = await sync_to_async(requests.post)(self.api_url, headers=headers, data=json.dumps(payload))
response.raise_for_status()
except requests.exceptions.RequestException as e:
error_message = f"[ERROR] Request error between {current_start_date} and {current_end_date}: {e}"
print(error_message)
report["errors"].append(error_message)
current_start_date = current_end_date
continue
try:
data = response.json()
print(f"[DEBUG] Received response: {data}")
except json.JSONDecodeError as e:
error_message = f"[ERROR] Ошибка декодирования JSON между {current_start_date} и {current_end_date}: {e}"
print(error_message)
report["errors"].append(error_message)
current_start_date = current_end_date
continue
total_count = data.get("count", 0)
items = data.get("items", [])
print(f"[DEBUG] Retrieved {len(items)} items (Total: {total_count}).")
# Если данных нет, пропускаем текущий интервал
if not items:
print(f"[WARNING] No items found between {current_start_date} and {current_end_date}.")
else:
for idx, item in enumerate(items, start=1):
print(f"[DEBUG] Processing item #{idx}/{len(items)}: {item}")
try:
await self._save_to_db(item)
report["processed_items"] += 1
except Exception as e:
error_message = f"[ERROR] Error processing item {item.get('id', 'Unknown')}: {e}"
print(error_message)
report["errors"].append(error_message)
# Отмечаем обработанный интервал
report["processed_intervals"] += 1
# Обновляем начало интервала
current_start_date = current_end_date
print(f"[DEBUG] Data fetching completed from {start_date} to {end_date}.")
return report
async def _save_to_db(self, item):
"""
Сохраняет данные о бронировании в БД.
Проверяет, существует ли уже бронирование с таким ID.
"""
try:
print(f"[DEBUG] Starting to save reservation {item['id']} to the database.")
hotel = await sync_to_async(Hotel.objects.get)(pms=self.pms_config)
print(f"[DEBUG] Hotel found: {hotel.name}")
date_format = '%Y-%m-%dT%H:%M:%S'
print(f"[DEBUG] Parsing check-in and check-out dates for reservation {item['id']}")
try:
check_in = datetime.strptime(item["from"], date_format).replace(tzinfo=timezone.utc)
check_out = datetime.strptime(item["until"], date_format).replace(tzinfo=timezone.utc)
print(f"[DEBUG] Parsed check-in: {check_in}, check-out: {check_out}")
except Exception as e:
print(f"[ERROR] Ошибка парсинга дат для бронирования {item['id']}: {e}")
raise
room_number = item.get("roomNumber", "") or "Unknown"
print(f"[DEBUG] Room number determined: {room_number}")
print(f"[DEBUG] Checking if reservation with ID {item['id']} already exists.")
existing_reservation = await sync_to_async(
Reservation.objects.filter(reservation_id=item["id"]).first
)()
if existing_reservation:
print(f"[DEBUG] Reservation with ID {item['id']} already exists. Updating it...")
print(f"[DEBUG] Updating existing reservation {item['id']}.")
await sync_to_async(Reservation.objects.update_or_create)(
reservation_id=item["id"], reservation_id=item["id"],
hotel=hotel, hotel=hotel,
defaults={ defaults={
"room_number": item.get("roomNumber", ""), # Номер комнаты "room_number": room_number,
"room_type": item.get("roomTypeName", ""), # Тип комнаты "room_type": item.get("roomTypeName", ""),
"check_in": datetime.strptime(item["from"], '%Y-%m-%dT%H:%M:%S'), # Дата заезда "check_in": check_in,
"check_out": datetime.strptime(item["until"], '%Y-%m-%dT%H:%M:%S'), # Дата выезда "check_out": check_out,
"status": item.get("checkInStatus", ""), # Статус бронирования "status": item.get("checkInStatus", ""),
"price": item.get("reservationPrice", 0), # Цена "price": item.get("reservationPrice", 0),
"discount": item.get("discount", 0), # Скидка "discount": item.get("discount", 0),
} },
) )
if created: print(f"[DEBUG] Updated existing reservation {item['id']}.")
print(f"Создана запись: {reservation}") else:
else: print(f"[DEBUG] No existing reservation found for ID {item['id']}. Creating a new one...")
print(f"Обновлена запись: {reservation}") print(f"[DEBUG] Creating a new reservation {item['id']}.")
except Exception as e: await sync_to_async(Reservation.objects.create)(
print(f"Ошибка при сохранении бронирования ID {item['id']}: {e}") reservation_id=item["id"],
hotel=hotel,
room_number=room_number,
room_type=item.get("roomTypeName", ""),
check_in=check_in,
check_out=check_out,
status=item.get("checkInStatus", ""),
price=item.get("reservationPrice", 0),
discount=item.get("discount", 0),
)
print(f"[DEBUG] Created a new reservation {item['id']}.")
print(f"[DEBUG] {'Created' if not existing_reservation else 'Updated'} reservation {item['id']} / {hotel.name}.")
except ValueError as ve:
print(f"[ERROR] Ошибка обработки даты для бронирования {item['id']}: {ve}")
except Exception as e:
print(f"[ERROR] Ошибка сохранения бронирования {item['id']}: {e}")

Binary file not shown.

Binary file not shown.

View File

@@ -52,3 +52,58 @@ ua-parser-builtins==0.18.0.post1
urllib3==2.2.3 urllib3==2.2.3
user-agents==2.2.0 user-agents==2.2.0
yarl==1.18.3 yarl==1.18.3
ace_tools==0.0
aiohappyeyeballs==2.4.4
aiohttp==3.11.10
aiosignal==1.3.1
anyio==4.6.2.post1
APScheduler==3.11.0
asgiref==3.8.1
async-timeout==5.0.1
attrs==24.2.0
certifi==2024.8.30
charset-normalizer==3.4.0
Django==5.1.4
django-filter==24.3
django-health-check==3.18.3
django-jazzmin==3.0.1
django-jet==1.0.8
et_xmlfile==2.0.0
exceptiongroup==1.2.2
fpdf==1.7.2
frozenlist==1.5.0
geoip2==4.8.1
h11==0.14.0
httpcore==1.0.7
httpx==0.28.0
idna==3.10
jsonschema==4.23.0
jsonschema-specifications==2024.10.1
maxminddb==2.6.2
multidict==6.1.0
numpy==2.1.3
openpyxl==3.1.5
pandas==2.2.3
pathspec==0.12.1
pillow==11.0.0
propcache==0.2.1
PyMySQL==1.1.1
python-dateutil==2.9.0.post0
python-dotenv==1.0.1
python-telegram-bot==21.8
pytz==2024.2
PyYAML==6.0.2
referencing==0.35.1
requests==2.32.3
rpds-py==0.22.3
six==1.17.0
sniffio==1.3.1
sqlparse==0.5.2
typing_extensions==4.12.2
tzdata==2024.2
tzlocal==5.2
ua-parser==1.0.0
ua-parser-builtins==0.18.0.post1
urllib3==2.2.3
user-agents==2.2.0
yarl==1.18.3

View File

@@ -50,7 +50,7 @@ class ScheduledTaskForm(forms.ModelForm):
@admin.register(ScheduledTask) @admin.register(ScheduledTask)
class ScheduledTaskAdmin(admin.ModelAdmin): class ScheduledTaskAdmin(admin.ModelAdmin):
form = ScheduledTaskForm form = ScheduledTaskForm
list_display = ("task_name", "function_path", "active", "formatted_last_run") list_display = ("task_name", "function_path", "minutes", "hours", "months", "weekdays", "active", "formatted_last_run")
list_filter = ("active",) list_filter = ("active",)
search_fields = ("task_name", "function_path") search_fields = ("task_name", "function_path")

0
static/css/styles.css Normal file
View File

File diff suppressed because it is too large Load Diff

View File

@@ -27,8 +27,12 @@ SECRET_KEY = 'django-insecure-l_8uu8#p*^zf)9zry80)6u+!+2g1a4tg!wx7@^!uw(+^axyh&h
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True DEBUG = True
ALLOWED_HOSTS = ['0.0.0.0', '192.168.219.140', '127.0.0.1', '192.168.219.114'] ALLOWED_HOSTS = ['0.0.0.0', '192.168.219.140', '127.0.0.1', '192.168.219.114', 'c710-182-226-158-253.ngrok-free.app']
CSRF_TRUSTED_ORIGINS = [
'https://c710-182-226-158-253.ngrok-free.app',
'https://*.ngrok.io', # Это подойдет для любых URL, связанных с ngrok
]
# Application definition # Application definition
@@ -44,7 +48,12 @@ INSTALLED_APPS = [
'pms_integration', 'pms_integration',
'hotels', 'hotels',
'users', 'users',
'scheduler' 'scheduler',
'antifroud',
'health_check',
'health_check.db',
'health_check.cache',
] ]
MIDDLEWARE = [ MIDDLEWARE = [
@@ -113,30 +122,46 @@ AUTH_PASSWORD_VALIDATORS = [
}, },
] ]
# settings.py
LOGGING = { LOGGING = {
'version': 1, 'version': 1,
'disable_existing_loggers': False, 'disable_existing_loggers': False,
'handlers': { 'handlers': {
'console': { 'file': {
'class': 'logging.StreamHandler', 'level': 'WARNING',
'class': 'logging.FileHandler',
'filename': 'import_hotels.log', # Лог будет записываться в этот файл
}, },
}, },
'root': { 'loggers': {
'handlers': ['console'], 'django': {
'level': 'WARNING', 'handlers': ['file'],
'level': 'WARNING',
'propagate': True,
},
'antifroud': {
'handlers': ['file'],
'level': 'WARNING',
'propagate': True,
},
}, },
} }
# Internationalization # Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/ # https://docs.djangoproject.com/en/5.1/topics/i18n/
LANGUAGE_CODE = 'ru-RU' LANGUAGE_CODE = 'ru'
TIME_ZONE = 'UTC' TIME_ZONE = 'Europe/Moscow'
USE_TZ = True
USE_I18N = True USE_I18N = True
USE_TZ = True USE_L10N = True
# Static files (CSS, JavaScript, Images) # Static files (CSS, JavaScript, Images)
@@ -154,32 +179,33 @@ DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
JAZZMIN_SETTINGS = { JAZZMIN_SETTINGS = {
"site_title": "Hotel Management", "use_bootstrap5": True,
"site_header": "Hotel Manager Admin", "site_title": "TOUCHH Hotel Management",
"site_brand": "HotelPro", "site_header": "TOUCHH Hotel Manager Admin",
"welcome_sign": "Welcome to Hotel Management System", "site_brand": "TOUCHH",
"welcome_sign": "Welcome to TOUCHH Hotel Management System",
"show_sidebar": True, "show_sidebar": True,
"navigation_expanded": True, "navigation_expanded": False,
"hide_models": ["users", "guests"], "hide_models": ["auth.Users", "guests"],
"site_logo": None, # Путь к логотипу, например "static/images/logo.png" "site_logo": None, # Путь к логотипу, например "static/images/logo.png"
"site_logo_classes": "img-circle", # Классы CSS для логотипа "site_logo_classes": "img-circle", # Классы CSS для логотипа
"site_icon": None, # Иконка сайта (favicon), например "static/images/favicon.ico" "site_icon": None, # Иконка сайта (favicon), например "static/images/favicon.ico"
"welcome_sign": "Welcome to Touchh Admin", # Приветствие на странице входа "welcome_sign": "Welcome to Touchh Admin", # Приветствие на странице входа
"copyright": "Touchh © 2024", # Кастомный текст в футере "copyright": "Touchh", # Кастомный текст в футере
"search_model": "auth.User", # Модель для строки поиска
"icons": { "icons": {
"auth": "fas fa-users-cog", "auth": "fas fa-users-cog",
"users": "fas fa-user-circle", "users": "fas fa-user-circle",
"hotels": "fas fa-hotel", "hotels": "fas fa-hotel",
}, },
"theme": "flatly", "theme": "sandstone",
"dark_mode_theme": "cyborg", "dark_mode_theme": "darkly",
"footer": { "footer": {
"copyright": "Touchh © 2024", "copyright": "SmartSolTech.kr © 2024",
"version": False, "version": False,
}, },
"dashboard_links": [ "dashboard_links": [
{"name": "Google", "url": "https://google.com", "new_window": True}, {"name": "Google", "url": "https://touchh.com", "new_window": True},
{"name": "Smartsoltech", "url": "https://smartsoltech.kr", "new_window": True}
], ],
"custom_links": { # Кастомные ссылки в боковом меню "custom_links": { # Кастомные ссылки в боковом меню

View File

@@ -1,6 +1,12 @@
from django.contrib import admin from django.contrib import admin
from django.urls import path, include from django.urls import path, include
from antifroud import views
app_name = 'touchh'
urlpatterns = [ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('health/', include('health_check.urls')),
path('antifroud/', include('antifroud.urls')),
] ]

View File

@@ -1,5 +1,5 @@
from django.contrib import admin from django.contrib import admin
from .models import User, UserConfirmation, UserActivityLog, NotificationSettings from .models import User, NotificationSettings
@admin.register(User) @admin.register(User)
class UserAdmin(admin.ModelAdmin): class UserAdmin(admin.ModelAdmin):
@@ -8,19 +8,7 @@ class UserAdmin(admin.ModelAdmin):
list_filter = ('role', 'confirmed') list_filter = ('role', 'confirmed')
ordering = ('-id',) ordering = ('-id',)
@admin.register(UserConfirmation)
class UserConfirmationAdmin(admin.ModelAdmin):
list_display = ('user', 'confirmation_code', 'created_at')
search_fields = ('user__username', 'confirmation_code')
list_filter = ('created_at',)
@admin.register(UserActivityLog)
class UserActivityLogAdmin(admin.ModelAdmin):
list_display = ( 'id', 'user_id', 'ip', 'timestamp', 'date_time', 'agent', 'platform', 'version', 'model', 'device', 'UAString', 'location', 'page_id', 'url_parameters', 'page_title', 'type', 'last_counter', 'hits', 'honeypot', 'reply', 'page_url')
search_fields = ('user_id', 'ip', 'datetime', 'agent', 'platform', 'version', 'model', 'device', 'UAString', 'location', 'page_id', 'url_parameters', 'page_title', 'type', 'last_counter', 'hits', 'honeypot', 'reply', 'page_url')
list_filter = ('page_title', 'user_id', 'ip')
ordering = ('-id',)
@admin.register(NotificationSettings) @admin.register(NotificationSettings)
class NotificationSettingsAdmin(admin.ModelAdmin): class NotificationSettingsAdmin(admin.ModelAdmin):
list_display = ('user', 'email', 'telegram_enabled', 'email_enabled', 'notification_time') list_display = ('user', 'email', 'telegram_enabled', 'email_enabled', 'notification_time')

View File

@@ -0,0 +1,22 @@
# Generated by Django 5.1.4 on 2024-12-13 00:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.DeleteModel(
name='LocalUserActivityLog',
),
migrations.DeleteModel(
name='UserActivityLog',
),
migrations.DeleteModel(
name='UserConfirmation',
),
]

View File

@@ -47,73 +47,7 @@ class User(AbstractUser):
verbose_name_plural = "Пользователи" verbose_name_plural = "Пользователи"
class UserConfirmation(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Пользователь")
confirmation_code = models.UUIDField(default=uuid.uuid4, verbose_name="Код подтверждения")
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Создан: ")
def __str__(self):
return f"Confirmation for {self.user.username} - {self.confirmation_code}"
class Meta:
verbose_name = "Подтверждение пользователя"
verbose_name_plural = "Подтверждения пользователей"
class WordPressUserActivityLog(models.Model):
id = models.AutoField(primary_key=True)
user_id = models.IntegerField()
activity_type = models.CharField(max_length=255)
timestamp = models.DateTimeField()
additional_data = models.JSONField(null=True, blank=True)
class Meta:
db_table = 'wpts_user_activity_log' # Название таблицы в базе данных WordPress
managed = False # Django не будет управлять этой таблицей
app_label = 'Users' # Замените на имя вашего приложения
class LocalUserActivityLog(models.Model):
id = models.AutoField(primary_key=True)
user_id = models.IntegerField()
activity_type = models.CharField(max_length=255)
timestamp = models.DateTimeField()
additional_data = models.JSONField(null=True, blank=True)
def __str__(self):
return f"User {self.user_id} - {self.activity_type}"
class UserActivityLog(models.Model):
id = models.BigAutoField(primary_key=True, verbose_name="ID")
user_id = models.BigIntegerField( verbose_name="ID пользователя")
ip = models.CharField(max_length=100, null=True, blank=True, verbose_name="IP адрес")
created = models.DateTimeField(auto_now_add=True, verbose_name="Создан")
timestamp = models.IntegerField(verbose_name="Время")
date_time = models.DateTimeField(verbose_name="Дата")
referred = models.CharField(max_length=255, null=True, blank=True)
agent = models.CharField(max_length=255, null=True, blank=True, verbose_name="Браузер")
platform = models.CharField(max_length=255, null=True, blank=True)
version = models.CharField(max_length=50, null=True, blank=True)
model = models.CharField(max_length=255, null=True, blank=True)
device = models.CharField(max_length=50, null=True, blank=True)
UAString = models.TextField(null=True, blank=True)
location = models.CharField(max_length=255, null=True, blank=True)
page_id = models.BigIntegerField(null=True, blank=True)
url_parameters = models.TextField(null=True, blank=True)
page_title = models.CharField(max_length=255, null=True, blank=True)
type = models.CharField(max_length=50, null=True, blank=True)
last_counter = models.IntegerField(null=True, blank=True)
hits = models.IntegerField(null=True, blank=True)
honeypot = models.BooleanField(null=True, blank=True)
reply = models.BooleanField(null=True, blank=True)
page_url = models.CharField(max_length=255, null=True, blank=True)
class Meta:
db_table = 'user_activity_log' # Название таблицы в локальной базе
verbose_name = 'Журнал активности'
verbose_name_plural = 'Журналы активности'
def __str__(self):
return f"User {self.user_id} - {self.type} - {self.date_time}"
class NotificationSettings(models.Model): class NotificationSettings(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Пользователь") user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Пользователь")
telegram_enabled = models.BooleanField(default=True, verbose_name="Уведомления в Telegram") telegram_enabled = models.BooleanField(default=True, verbose_name="Уведомления в Telegram")