127 lines
4.1 KiB
Python
127 lines
4.1 KiB
Python
from flask import Blueprint, jsonify
|
||
from datetime import datetime, timedelta
|
||
from ..db import get_db_connection, release_db_connection
|
||
from ..middleware import token_required
|
||
|
||
dashboard_blueprint = Blueprint('dashboard', __name__)
|
||
|
||
@dashboard_blueprint.route('/dashboard/stats', methods=['GET'])
|
||
@token_required
|
||
def get_stats(current_user_id):
|
||
"""
|
||
Получить общую статистику для дашборда
|
||
---
|
||
tags:
|
||
- Dashboard
|
||
security:
|
||
- APIKeyHeader: []
|
||
responses:
|
||
200:
|
||
description: Объект со статистикой и трендами
|
||
"""
|
||
conn = get_db_connection()
|
||
cur = conn.cursor()
|
||
|
||
# 1. Total cases
|
||
cur.execute("SELECT COUNT(*) FROM cases WHERE user_id = %s", (current_user_id,))
|
||
total_cases = cur.fetchone()[0]
|
||
|
||
# 2. Cases by status
|
||
cur.execute("SELECT status, COUNT(*) FROM cases WHERE user_id = %s GROUP BY status", (current_user_id,))
|
||
status_rows = cur.fetchall()
|
||
cases_by_status = {row[0]: row[1] for row in status_rows}
|
||
|
||
# 3. Total active integrations
|
||
cur.execute("SELECT COUNT(*) FROM credentials WHERE user_id = %s", (current_user_id,))
|
||
total_integrations = cur.fetchone()[0]
|
||
|
||
# 4. List of connected platforms
|
||
cur.execute("SELECT platform FROM credentials WHERE user_id = %s", (current_user_id,))
|
||
platforms = [row[0] for row in cur.fetchall()]
|
||
|
||
# 5. Recent activity (last 5 cases)
|
||
cur.execute("SELECT id, platform, violator_article, status, created_at FROM cases WHERE user_id = %s ORDER BY created_at DESC LIMIT 5", (current_user_id,))
|
||
recent_rows = cur.fetchall()
|
||
recent_activity = [
|
||
{
|
||
"id": r[0],
|
||
"platform": r[1],
|
||
"article": r[2],
|
||
"status": r[3],
|
||
"date": r[4].isoformat() if r[4] else None
|
||
} for r in recent_rows
|
||
]
|
||
|
||
# 6. Trend data (last 7 days)
|
||
trend = []
|
||
for i in range(6, -1, -1):
|
||
day = (datetime.utcnow() - timedelta(days=i)).date()
|
||
cur.execute("SELECT COUNT(*) FROM cases WHERE user_id = %s AND created_at::date = %s", (current_user_id, day))
|
||
count = cur.fetchone()[0]
|
||
trend.append({
|
||
"date": day.strftime('%d.%m'),
|
||
"count": count
|
||
})
|
||
|
||
# 5. Multi-account stores summary
|
||
cur.execute("SELECT id, platform, name FROM credentials WHERE user_id = %s", (current_user_id,))
|
||
stores_rows = cur.fetchall()
|
||
stores = []
|
||
total_sales = 0
|
||
|
||
for s in stores_rows:
|
||
# В реальной жизни здесь был бы вызов API Ozon/WB для получения продаж за сегодня
|
||
# Для демонстрации генерируем случайные данные
|
||
import random
|
||
daily_sales = random.randint(5000, 50000)
|
||
total_sales += daily_sales
|
||
stores.append({
|
||
"id": s[0],
|
||
"platform": s[1],
|
||
"name": s[2],
|
||
"status": "active",
|
||
"daily_sales": daily_sales
|
||
})
|
||
|
||
release_db_connection(conn)
|
||
|
||
return jsonify({
|
||
"total_cases": total_cases,
|
||
"cases_by_status": cases_by_status,
|
||
"total_integrations": total_integrations,
|
||
"total_sales": total_sales,
|
||
"platforms": platforms,
|
||
"recent_activity": recent_activity,
|
||
"trend": trend,
|
||
"stores": stores
|
||
})
|
||
|
||
@dashboard_blueprint.route('/dashboard/logs', methods=['GET'])
|
||
@token_required
|
||
def get_logs(current_user_id):
|
||
"""
|
||
Получить лог аудита действий пользователя
|
||
---
|
||
tags:
|
||
- Dashboard
|
||
security:
|
||
- APIKeyHeader: []
|
||
responses:
|
||
200:
|
||
description: Список действий из лога
|
||
"""
|
||
conn = get_db_connection()
|
||
cur = conn.cursor()
|
||
cur.execute("SELECT action, details, created_at FROM audit_log WHERE user_id = %s ORDER BY created_at DESC LIMIT 20", (current_user_id,))
|
||
rows = cur.fetchall()
|
||
release_db_connection(conn)
|
||
|
||
logs = [
|
||
{
|
||
"action": r[0],
|
||
"details": r[1],
|
||
"date": r[2].isoformat() if r[2] else None
|
||
} for r in rows
|
||
]
|
||
return jsonify(logs)
|