fix bug web admin panel and sort list users

This commit is contained in:
vrubelroman 2025-11-13 15:27:10 +03:00
parent e645e57f74
commit 526d36bc03
2 changed files with 136 additions and 54 deletions

View file

@ -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,

View file

@ -259,8 +259,16 @@
Сегодня отправлено: <strong id="total-messages-today">0</strong>
</div>
<div id="message-stats-by-command" style="margin-top: 10px; font-size: 12px; color: #666;">
<div style="margin-bottom: 5px;"><strong>По командам:</strong></div>
<div id="command-stats-list"></div>
<div style="display: flex; gap: 20px;">
<div style="flex: 1;">
<div style="margin-bottom: 8px; font-weight: bold;">За все время:</div>
<div id="command-stats-all-time"></div>
</div>
<div style="flex: 1;">
<div style="margin-bottom: 8px; font-weight: bold;">За сегодня:</div>
<div id="command-stats-today"></div>
</div>
</div>
</div>
</div>
@ -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');
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'
};
// Render command stats in two columns
const commandStatsAllTime = document.getElementById('command-stats-all-time');
const commandStatsToday = document.getElementById('command-stats-today');
// Filter out excluded commands
if (data.message_stats.by_command && Object.keys(data.message_stats.by_command).length > 0) {
// 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 `<div style="margin-bottom: 3px;">
${cmdName}: <strong>${stats.total}</strong> (сегодня: <strong>${stats.today}</strong>)
</div>`;
}).join('');
if (filteredCommands.length > 0) {
// Render "All time" column
commandStatsAllTime.innerHTML = filteredCommands
.map(([cmd, stats]) => {
return `<div style="margin-bottom: 3px;">
• ${cmd}: <strong>${stats.total}</strong>
</div>`;
}).join('');
// Render "Today" column
commandStatsToday.innerHTML = filteredCommands
.map(([cmd, stats]) => {
return `<div style="margin-bottom: 3px;">
• ${cmd}: <strong>${stats.today}</strong>
</div>`;
}).join('');
} else {
commandStatsAllTime.innerHTML = '<div style="color: #999;">Нет данных</div>';
commandStatsToday.innerHTML = '<div style="color: #999;">Нет данных</div>';
}
} else {
commandStatsList.innerHTML = '<div style="color: #999;">Нет данных</div>';
commandStatsAllTime.innerHTML = '<div style="color: #999;">Нет данных</div>';
commandStatsToday.innerHTML = '<div style="color: #999;">Нет данных</div>';
}
}