From 526d36bc03cb875f7fddb687640c455a2898ac96 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Thu, 13 Nov 2025 15:27:10 +0300 Subject: [PATCH] fix bug web admin panel and sort list users --- LichessWebView/app.py | 124 ++++++++++++++++++++++------ LichessWebView/templates/index.html | 66 +++++++++------ 2 files changed, 136 insertions(+), 54 deletions(-) diff --git a/LichessWebView/app.py b/LichessWebView/app.py index 2d21522..a1200bc 100644 --- a/LichessWebView/app.py +++ b/LichessWebView/app.py @@ -1,8 +1,6 @@ from flask import Flask, jsonify, render_template from flask_cors import CORS import sqlite3 -import sys -import os from datetime import datetime, date app = Flask(__name__) @@ -11,13 +9,93 @@ CORS(app) # Путь к базе данных бота DB_PATH = "/app/data/lichess_bot.db" -# Add parent directory to path to import message_counters -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'LichessClientTG_bot')) -try: - from message_counters import MessageCounters -except ImportError: - # Fallback if import fails - MessageCounters = None +def get_message_counters_stats(db_path): + """Get message counters statistics directly from database""" + try: + with sqlite3.connect(db_path) as conn: + cursor = conn.cursor() + + # Check if table exists + cursor.execute(''' + SELECT name FROM sqlite_master + WHERE type='table' AND name='message_counters' + ''') + if not cursor.fetchone(): + # Table doesn't exist, return empty stats + return { + 'total_all_time': 0, + 'total_today': 0, + 'by_command': {} + } + + # Reset daily counters if needed + today = date.today() + cursor.execute(''' + SELECT command, last_reset_date FROM message_counters + ''') + + for row in cursor.fetchall(): + cmd, last_reset = row[0], row[1] + if last_reset: + try: + last_reset_date = datetime.strptime(last_reset, '%Y-%m-%d').date() + if last_reset_date < today: + cursor.execute(''' + UPDATE message_counters + SET today_count = 0, last_reset_date = ? + WHERE command = ? + ''', (today.isoformat(), cmd)) + except (ValueError, TypeError): + cursor.execute(''' + UPDATE message_counters + SET today_count = 0, last_reset_date = ? + WHERE command = ? + ''', (today.isoformat(), cmd)) + else: + cursor.execute(''' + UPDATE message_counters + SET last_reset_date = ? + WHERE command = ? + ''', (today.isoformat(), cmd)) + + conn.commit() + + # Get all counters + cursor.execute(''' + SELECT command, total_count, today_count + FROM message_counters + ORDER BY command + ''') + + stats = { + 'by_command': {}, + 'total_all_time': 0, + 'total_today': 0 + } + + for row in cursor.fetchall(): + cmd, total, today = row[0], row[1], row[2] + stats['by_command'][cmd] = { + 'total': total, + 'today': today + } + stats['total_all_time'] += total + stats['total_today'] += today + + return { + 'total_all_time': stats['total_all_time'], + 'total_today': stats['total_today'], + 'by_command': stats['by_command'] + } + except Exception as e: + print(f"Error getting message counters: {e}") + import traceback + print(traceback.format_exc()) + return { + 'total_all_time': 0, + 'total_today': 0, + 'by_command': {} + } @app.route('/') def index(): @@ -45,7 +123,7 @@ def get_users(): FROM telegram_users tu LEFT JOIN user_gamers ug ON tu.user_id = ug.user_id GROUP BY tu.user_id, tu.username, tu.first_name, tu.last_name, tu.created_at - ORDER BY COALESCE(tu.first_name, tu.username, '') + ORDER BY tu.created_at DESC ''') rows = cursor.fetchall() @@ -71,24 +149,16 @@ def get_users(): total_gamers = cursor.fetchone()[0] # Get message counters statistics - message_stats = {} - if MessageCounters: - try: - counters = MessageCounters(db_path=DB_PATH) - message_stats = counters.get_stats_summary() - except Exception as e: - print(f"Error getting message counters: {e}") - message_stats = { - 'total_all_time': 0, - 'total_today': 0, - 'by_command': {} - } - else: - message_stats = { - 'total_all_time': 0, - 'total_today': 0, - 'by_command': {} + message_stats = get_message_counters_stats(DB_PATH) + + # Filter out excluded commands (same as in admin_bot) + excluded_commands = {'lang', 'resetlang', 'start'} + if message_stats.get('by_command'): + filtered_by_command = { + cmd: data for cmd, data in message_stats['by_command'].items() + if cmd not in excluded_commands } + message_stats['by_command'] = filtered_by_command return jsonify({ 'success': True, diff --git a/LichessWebView/templates/index.html b/LichessWebView/templates/index.html index b651e5a..3714192 100644 --- a/LichessWebView/templates/index.html +++ b/LichessWebView/templates/index.html @@ -259,8 +259,16 @@ Сегодня отправлено: 0
-
По командам:
-
+
+
+
За все время:
+
+
+
+
За сегодня:
+
+
+
@@ -312,36 +320,40 @@ document.getElementById('total-messages-all').textContent = data.message_stats.total_all_time || 0; document.getElementById('total-messages-today').textContent = data.message_stats.total_today || 0; - // Render command stats - const commandStatsList = document.getElementById('command-stats-list'); + // Render command stats in two columns + const commandStatsAllTime = document.getElementById('command-stats-all-time'); + const commandStatsToday = document.getElementById('command-stats-today'); + if (data.message_stats.by_command && Object.keys(data.message_stats.by_command).length > 0) { - const commandNames = { - 'addgamer': 'Add Gamer', - 'addtoken': 'Add Token', - 'getgamers': 'Get Gamers', - 'delgamer': 'Del Gamer', - 'today': 'Today', - 'yesterday': 'Yesterday', - 'week': 'Week', - 'setperiod': 'Set Period', - 'periodic_notification': 'Periodic Notifications' - }; - - // Filter out excluded commands + // Filter out excluded commands (already filtered on server, but double-check) const excludedCommands = ['start', 'lang', 'resetlang']; const filteredCommands = Object.entries(data.message_stats.by_command) - .filter(([cmd]) => !excludedCommands.includes(cmd)); + .filter(([cmd]) => !excludedCommands.includes(cmd)) + .sort((a, b) => a[0].localeCompare(b[0])); // Sort alphabetically - commandStatsList.innerHTML = filteredCommands - .sort((a, b) => b[1].total - a[1].total) - .map(([cmd, stats]) => { - const cmdName = commandNames[cmd] || cmd; - return `
- ${cmdName}: ${stats.total} (сегодня: ${stats.today}) -
`; - }).join(''); + if (filteredCommands.length > 0) { + // Render "All time" column + commandStatsAllTime.innerHTML = filteredCommands + .map(([cmd, stats]) => { + return `
+ • ${cmd}: ${stats.total} +
`; + }).join(''); + + // Render "Today" column + commandStatsToday.innerHTML = filteredCommands + .map(([cmd, stats]) => { + return `
+ • ${cmd}: ${stats.today} +
`; + }).join(''); + } else { + commandStatsAllTime.innerHTML = '
Нет данных
'; + commandStatsToday.innerHTML = '
Нет данных
'; + } } else { - commandStatsList.innerHTML = '
Нет данных
'; + commandStatsAllTime.innerHTML = '
Нет данных
'; + commandStatsToday.innerHTML = '
Нет данных
'; } }