From 87f3d0a36c298e1ec6650d4df3b73df20c90b717 Mon Sep 17 00:00:00 2001 From: Maxim Date: Thu, 11 Dec 2025 19:58:49 +0300 Subject: [PATCH] first commit --- .claude/settings.local.json | 13 + .gitignore | 217 ++++++++++++++++ eng_bot_metrics/__init__.py | 0 eng_bot_metrics/asgi.py | 16 ++ eng_bot_metrics/settings.py | 118 +++++++++ eng_bot_metrics/urls.py | 23 ++ eng_bot_metrics/wsgi.py | 16 ++ manage.py | 22 ++ metrics/__init__.py | 0 metrics/admin.py | 10 + metrics/apps.py | 5 + metrics/migrations/0001_initial.py | 30 +++ metrics/migrations/__init__.py | 0 metrics/models.py | 22 ++ metrics/templates/metrics/dashboard.html | 306 +++++++++++++++++++++++ metrics/tests.py | 3 + metrics/urls.py | 10 + metrics/views.py | 115 +++++++++ 18 files changed, 926 insertions(+) create mode 100644 .claude/settings.local.json create mode 100644 .gitignore create mode 100644 eng_bot_metrics/__init__.py create mode 100644 eng_bot_metrics/asgi.py create mode 100644 eng_bot_metrics/settings.py create mode 100644 eng_bot_metrics/urls.py create mode 100644 eng_bot_metrics/wsgi.py create mode 100755 manage.py create mode 100644 metrics/__init__.py create mode 100644 metrics/admin.py create mode 100644 metrics/apps.py create mode 100644 metrics/migrations/0001_initial.py create mode 100644 metrics/migrations/__init__.py create mode 100644 metrics/models.py create mode 100644 metrics/templates/metrics/dashboard.html create mode 100644 metrics/tests.py create mode 100644 metrics/urls.py create mode 100644 metrics/views.py diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..d7f72a7 --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,13 @@ +{ + "permissions": { + "allow": [ + "Bash(python3 -m django:*)", + "Bash(pip3 install:*)", + "Bash(python3:*)", + "Bash(source venv/bin/activate)", + "Bash(pip install:*)", + "Bash(django-admin startproject:*)", + "Bash(python manage.py:*)" + ] + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f5f774b --- /dev/null +++ b/.gitignore @@ -0,0 +1,217 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[codz] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +# Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +# poetry.lock +# poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +# pdm.lock +# pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +# pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# Redis +*.rdb +*.aof +*.pid + +# RabbitMQ +mnesia/ +rabbitmq/ +rabbitmq-data/ + +# ActiveMQ +activemq-data/ + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +# .idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore +# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, +# you could uncomment the following to ignore the entire vscode folder +# .vscode/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ + +# Streamlit +.streamlit/secrets.toml +404: Not Found \ No newline at end of file diff --git a/eng_bot_metrics/__init__.py b/eng_bot_metrics/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/eng_bot_metrics/asgi.py b/eng_bot_metrics/asgi.py new file mode 100644 index 0000000..584aa32 --- /dev/null +++ b/eng_bot_metrics/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for eng_bot_metrics project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/6.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'eng_bot_metrics.settings') + +application = get_asgi_application() diff --git a/eng_bot_metrics/settings.py b/eng_bot_metrics/settings.py new file mode 100644 index 0000000..b5dacb5 --- /dev/null +++ b/eng_bot_metrics/settings.py @@ -0,0 +1,118 @@ +""" +Django settings for eng_bot_metrics project. + +Generated by 'django-admin startproject' using Django 6.0. + +For more information on this file, see +https://docs.djangoproject.com/en/6.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/6.0/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/6.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-det_&7$u2z3q9v_29srpv@@i8lvr$mckq_z_pqltnj%brn)x%(' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ['*'] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'metrics', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'eng_bot_metrics.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'eng_bot_metrics.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/6.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/6.0/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/6.0/topics/i18n/ + +LANGUAGE_CODE = 'ru-ru' + +TIME_ZONE = 'Europe/Moscow' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/6.0/howto/static-files/ + +STATIC_URL = 'static/' diff --git a/eng_bot_metrics/urls.py b/eng_bot_metrics/urls.py new file mode 100644 index 0000000..1c2f034 --- /dev/null +++ b/eng_bot_metrics/urls.py @@ -0,0 +1,23 @@ +""" +URL configuration for eng_bot_metrics project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/6.0/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path, include + +urlpatterns = [ + path('admin/', admin.site.urls), + path('', include('metrics.urls')), +] diff --git a/eng_bot_metrics/wsgi.py b/eng_bot_metrics/wsgi.py new file mode 100644 index 0000000..ca16d92 --- /dev/null +++ b/eng_bot_metrics/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for eng_bot_metrics project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/6.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'eng_bot_metrics.settings') + +application = get_wsgi_application() diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..6edb6b7 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'eng_bot_metrics.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/metrics/__init__.py b/metrics/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/metrics/admin.py b/metrics/admin.py new file mode 100644 index 0000000..f0af1da --- /dev/null +++ b/metrics/admin.py @@ -0,0 +1,10 @@ +from django.contrib import admin +from .models import ClickEvent + + +@admin.register(ClickEvent) +class ClickEventAdmin(admin.ModelAdmin): + list_display = ['event_type', 'ip_address', 'created_at'] + list_filter = ['event_type', 'created_at'] + search_fields = ['ip_address'] + readonly_fields = ['created_at'] diff --git a/metrics/apps.py b/metrics/apps.py new file mode 100644 index 0000000..1e777e4 --- /dev/null +++ b/metrics/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class MetricsConfig(AppConfig): + name = 'metrics' diff --git a/metrics/migrations/0001_initial.py b/metrics/migrations/0001_initial.py new file mode 100644 index 0000000..6f0012e --- /dev/null +++ b/metrics/migrations/0001_initial.py @@ -0,0 +1,30 @@ +# Generated by Django 6.0 on 2025-12-11 15:46 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='ClickEvent', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('event_type', models.CharField(choices=[('bot', 'Переход в бота'), ('channel', 'Переход в TG канал')], max_length=20)), + ('ip_address', models.GenericIPAddressField(blank=True, null=True)), + ('user_agent', models.TextField(blank=True)), + ('referrer', models.URLField(blank=True, null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ], + options={ + 'verbose_name': 'Клик', + 'verbose_name_plural': 'Клики', + 'ordering': ['-created_at'], + }, + ), + ] diff --git a/metrics/migrations/__init__.py b/metrics/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/metrics/models.py b/metrics/models.py new file mode 100644 index 0000000..6c359b8 --- /dev/null +++ b/metrics/models.py @@ -0,0 +1,22 @@ +from django.db import models + + +class ClickEvent(models.Model): + EVENT_TYPES = [ + ('bot', 'Переход в бота'), + ('channel', 'Переход в TG канал'), + ] + + event_type = models.CharField(max_length=20, choices=EVENT_TYPES) + ip_address = models.GenericIPAddressField(null=True, blank=True) + user_agent = models.TextField(blank=True) + referrer = models.URLField(blank=True, null=True) + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + verbose_name = 'Клик' + verbose_name_plural = 'Клики' + ordering = ['-created_at'] + + def __str__(self): + return f"{self.get_event_type_display()} - {self.created_at}" diff --git a/metrics/templates/metrics/dashboard.html b/metrics/templates/metrics/dashboard.html new file mode 100644 index 0000000..a6223b7 --- /dev/null +++ b/metrics/templates/metrics/dashboard.html @@ -0,0 +1,306 @@ + + + + + + Метрики - English Bot + + + + +
+

English Bot - Метрики

+ +
+
+

Всего переходов в бота

+
{{ total_bot }}
+
+
+

Всего переходов в канал

+
{{ total_channel }}
+
+
+

В бота сегодня

+
{{ today_bot }}
+
+
+

В канал сегодня

+
{{ today_channel }}
+
+
+

В бота за неделю

+
{{ week_bot }}
+
+
+

В канал за неделю

+
{{ week_channel }}
+
+
+ +
+

Статистика за 30 дней

+ +
+ +
+

Последние события

+ + + + + + + + + + {% for event in recent_events %} + + + + + + {% empty %} + + + + {% endfor %} + +
ТипIP адресДата и время
+ + {{ event.get_event_type_display }} + + {{ event.ip_address|default:"-" }}{{ event.created_at|date:"d.m.Y H:i:s" }}
Нет данных
+
+
+ + + + diff --git a/metrics/tests.py b/metrics/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/metrics/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/metrics/urls.py b/metrics/urls.py new file mode 100644 index 0000000..0287578 --- /dev/null +++ b/metrics/urls.py @@ -0,0 +1,10 @@ +from django.urls import path +from . import views + +app_name = 'metrics' + +urlpatterns = [ + path('api/track/bot/', views.track_bot_click, name='track_bot'), + path('api/track/channel/', views.track_channel_click, name='track_channel'), + path('', views.dashboard, name='dashboard'), +] diff --git a/metrics/views.py b/metrics/views.py new file mode 100644 index 0000000..5de14f9 --- /dev/null +++ b/metrics/views.py @@ -0,0 +1,115 @@ +from django.shortcuts import render +from django.http import JsonResponse +from django.views.decorators.csrf import csrf_exempt +from django.views.decorators.http import require_http_methods +from django.db.models import Count +from django.db.models.functions import TruncDate +from django.utils import timezone +from datetime import timedelta +import json + +from .models import ClickEvent + + +def get_client_ip(request): + x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') + if x_forwarded_for: + ip = x_forwarded_for.split(',')[0].strip() + else: + ip = request.META.get('REMOTE_ADDR') + return ip + + +@csrf_exempt +@require_http_methods(["POST"]) +def track_bot_click(request): + """Трекинг перехода в бота""" + ClickEvent.objects.create( + event_type='bot', + ip_address=get_client_ip(request), + user_agent=request.META.get('HTTP_USER_AGENT', ''), + referrer=request.META.get('HTTP_REFERER'), + ) + return JsonResponse({'status': 'ok', 'event': 'bot'}) + + +@csrf_exempt +@require_http_methods(["POST"]) +def track_channel_click(request): + """Трекинг перехода в TG канал""" + ClickEvent.objects.create( + event_type='channel', + ip_address=get_client_ip(request), + user_agent=request.META.get('HTTP_USER_AGENT', ''), + referrer=request.META.get('HTTP_REFERER'), + ) + return JsonResponse({'status': 'ok', 'event': 'channel'}) + + +def dashboard(request): + """Страница статистики""" + today = timezone.now().date() + week_ago = today - timedelta(days=7) + month_ago = today - timedelta(days=30) + + # Общая статистика + total_bot = ClickEvent.objects.filter(event_type='bot').count() + total_channel = ClickEvent.objects.filter(event_type='channel').count() + + # Статистика за сегодня + today_bot = ClickEvent.objects.filter( + event_type='bot', + created_at__date=today + ).count() + today_channel = ClickEvent.objects.filter( + event_type='channel', + created_at__date=today + ).count() + + # Статистика за неделю + week_bot = ClickEvent.objects.filter( + event_type='bot', + created_at__date__gte=week_ago + ).count() + week_channel = ClickEvent.objects.filter( + event_type='channel', + created_at__date__gte=week_ago + ).count() + + # Данные для графика (последние 30 дней) + bot_by_day = ClickEvent.objects.filter( + event_type='bot', + created_at__date__gte=month_ago + ).annotate(date=TruncDate('created_at')).values('date').annotate( + count=Count('id') + ).order_by('date') + + channel_by_day = ClickEvent.objects.filter( + event_type='channel', + created_at__date__gte=month_ago + ).annotate(date=TruncDate('created_at')).values('date').annotate( + count=Count('id') + ).order_by('date') + + # Последние события + recent_events = ClickEvent.objects.all()[:20] + + context = { + 'total_bot': total_bot, + 'total_channel': total_channel, + 'today_bot': today_bot, + 'today_channel': today_channel, + 'week_bot': week_bot, + 'week_channel': week_channel, + 'bot_by_day': json.dumps([ + {'date': item['date'].isoformat(), 'count': item['count']} + for item in bot_by_day + ]), + 'channel_by_day': json.dumps([ + {'date': item['date'].isoformat(), 'count': item['count']} + for item in channel_by_day + ]), + 'recent_events': recent_events, + } + + return render(request, 'metrics/dashboard.html', context)