Files
ai_wht_B/ver_2512121646/statistics_routes.py

342 lines
12 KiB
Python
Raw Normal View History

2026-01-06 14:18:39 +08:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
数据统计接口
"""
from flask import Blueprint, request, jsonify
import logging
from datetime import datetime
from auth_utils import require_auth, AuthUtils
from database_config import get_db_manager, format_datetime_fields
logger = logging.getLogger('article_server')
# 创建蓝图
statistics_bp = Blueprint('statistics', __name__, url_prefix='/api/statistics')
@statistics_bp.route('/records', methods=['GET'])
@require_auth
def get_publish_records():
"""获取发布记录列表"""
try:
current_user = AuthUtils.get_current_user()
enterprise_id = current_user.get('enterprise_id')
if not enterprise_id:
return jsonify({
'code': 400,
'message': '无法获取企业ID',
'data': None
}), 400
# 获取查询参数
page = int(request.args.get('page', 1))
page_size = int(request.args.get('pageSize', 20))
keyword = request.args.get('keyword', '').strip()
product_id = request.args.get('product_id', '').strip()
employee_id = request.args.get('employee_id', '').strip()
start_date = request.args.get('start_date', '').strip()
end_date = request.args.get('end_date', '').strip()
# 构建查询条件
where_conditions = ["r.enterprise_id = %s"]
params = [enterprise_id]
if keyword:
where_conditions.append("(a.title LIKE %s OR u.real_name LIKE %s OR p.name LIKE %s)")
keyword_pattern = f"%{keyword}%"
params.extend([keyword_pattern, keyword_pattern, keyword_pattern])
if product_id:
where_conditions.append("r.product_id = %s")
params.append(product_id)
if employee_id:
where_conditions.append("r.created_user_id = %s")
params.append(employee_id)
if start_date:
where_conditions.append("r.publish_time >= %s")
params.append(start_date)
if end_date:
where_conditions.append("r.publish_time <= %s")
params.append(f"{end_date} 23:59:59")
where_clause = " AND ".join(where_conditions)
# 计算偏移量
offset = (page - 1) * page_size
db_manager = get_db_manager()
# 查询总数
count_sql = f"""
SELECT COUNT(*) as total
FROM ai_article_published_records r
WHERE {where_clause}
"""
count_result = db_manager.execute_query(count_sql, params)
total = count_result[0]['total']
# 查询发布记录列表
sql = f"""
SELECT r.id, r.publish_time, r.created_user_id, r.product_id, r.article_id,
r.publish_link, r.topic,
u.real_name as employee_name,
p.name as product_name,
a.title
FROM ai_article_published_records r
LEFT JOIN ai_users u ON r.created_user_id = u.id
LEFT JOIN ai_products p ON r.product_id = p.id
LEFT JOIN ai_articles a ON r.article_id = a.id
WHERE {where_clause}
ORDER BY r.publish_time DESC
LIMIT %s OFFSET %s
"""
params.extend([page_size, offset])
records = db_manager.execute_query(sql, params)
# 格式化日期时间字段
records = format_datetime_fields(records)
logger.info(f"获取发布记录列表成功,总数: {total}")
return jsonify({
'code': 200,
'message': 'success',
'data': {
'total': total,
'list': records
},
'timestamp': int(datetime.now().timestamp() * 1000)
})
except Exception as e:
logger.error(f"[获取发布记录] 处理请求时发生错误: {str(e)}", exc_info=True)
return jsonify({
'code': 500,
'message': '服务器内部错误',
'data': None
}), 500
@statistics_bp.route('/overview', methods=['GET'])
@require_auth
def get_statistics_overview():
"""获取统计概览"""
try:
current_user = AuthUtils.get_current_user()
enterprise_id = current_user.get('enterprise_id')
if not enterprise_id:
return jsonify({
'code': 400,
'message': '无法获取企业ID',
'data': None
}), 400
db_manager = get_db_manager()
# 查询总发布数
total_sql = "SELECT COUNT(*) as total FROM ai_article_published_records WHERE enterprise_id = %s"
total_result = db_manager.execute_query(total_sql, (enterprise_id,))
total = total_result[0]['total'] if total_result else 0
# 查询今日发布数
today_sql = """
SELECT COUNT(*) as today_count
FROM ai_article_published_records
WHERE enterprise_id = %s AND DATE(publish_time) = CURDATE()
"""
today_result = db_manager.execute_query(today_sql, (enterprise_id,))
today = today_result[0]['today_count'] if today_result else 0
# 查询本周发布数
week_sql = """
SELECT COUNT(*) as week_count
FROM ai_article_published_records
WHERE enterprise_id = %s AND YEARWEEK(publish_time, 1) = YEARWEEK(CURDATE(), 1)
"""
week_result = db_manager.execute_query(week_sql, (enterprise_id,))
this_week = week_result[0]['week_count'] if week_result else 0
# 查询本月发布数
month_sql = """
SELECT COUNT(*) as month_count
FROM ai_article_published_records
WHERE enterprise_id = %s AND YEAR(publish_time) = YEAR(CURDATE())
AND MONTH(publish_time) = MONTH(CURDATE())
"""
month_result = db_manager.execute_query(month_sql, (enterprise_id,))
this_month = month_result[0]['month_count'] if month_result else 0
# 查询参与员工数
employee_sql = """
SELECT COUNT(DISTINCT created_user_id) as employee_count
FROM ai_article_published_records
WHERE enterprise_id = %s
"""
employee_result = db_manager.execute_query(employee_sql, (enterprise_id,))
employees = employee_result[0]['employee_count'] if employee_result else 0
logger.info("获取统计概览成功")
return jsonify({
'code': 200,
'message': 'success',
'data': {
'total': total,
'today': today,
'thisWeek': this_week,
'thisMonth': this_month,
'employees': employees
},
'timestamp': int(datetime.now().timestamp() * 1000)
})
except Exception as e:
logger.error(f"[获取统计概览] 处理请求时发生错误: {str(e)}", exc_info=True)
return jsonify({
'code': 500,
'message': '服务器内部错误',
'data': None
}), 500
@statistics_bp.route('/by-product', methods=['GET'])
@require_auth
def get_statistics_by_product():
"""按产品统计"""
try:
current_user = AuthUtils.get_current_user()
enterprise_id = current_user.get('enterprise_id')
if not enterprise_id:
return jsonify({
'code': 400,
'message': '无法获取企业ID',
'data': None
}), 400
# 获取查询参数
start_date = request.args.get('start_date', '').strip()
end_date = request.args.get('end_date', '').strip()
db_manager = get_db_manager()
# 构建查询条件
where_conditions = ["r.enterprise_id = %s"]
params = [enterprise_id]
if start_date:
where_conditions.append("r.publish_time >= %s")
params.append(start_date)
if end_date:
where_conditions.append("r.publish_time <= %s")
params.append(f"{end_date} 23:59:59")
where_clause = " AND ".join(where_conditions)
# 查询按产品统计
sql = f"""
SELECT r.product_id, p.name as product_name,
COUNT(*) as count,
ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM ai_article_published_records WHERE {where_clause}), 0) as percentage
FROM ai_article_published_records r
LEFT JOIN ai_products p ON r.product_id = p.id
WHERE {where_clause}
GROUP BY r.product_id, p.name
ORDER BY count DESC
"""
result = db_manager.execute_query(sql, params * 2)
logger.info("按产品统计成功")
return jsonify({
'code': 200,
'message': 'success',
'data': {
'list': result
},
'timestamp': int(datetime.now().timestamp() * 1000)
})
except Exception as e:
logger.error(f"[按产品统计] 处理请求时发生错误: {str(e)}", exc_info=True)
return jsonify({
'code': 500,
'message': '服务器内部错误',
'data': None
}), 500
@statistics_bp.route('/employee-rank', methods=['GET'])
@require_auth
def get_employee_rank():
"""员工发布排行"""
try:
current_user = AuthUtils.get_current_user()
enterprise_id = current_user.get('enterprise_id')
if not enterprise_id:
return jsonify({
'code': 400,
'message': '无法获取企业ID',
'data': None
}), 400
# 获取查询参数
limit = int(request.args.get('limit', 10))
start_date = request.args.get('start_date', '').strip()
end_date = request.args.get('end_date', '').strip()
db_manager = get_db_manager()
# 构建查询条件
where_conditions = ["r.enterprise_id = %s"]
params = [enterprise_id]
if start_date:
where_conditions.append("r.publish_time >= %s")
params.append(start_date)
if end_date:
where_conditions.append("r.publish_time <= %s")
params.append(f"{end_date} 23:59:59")
where_clause = " AND ".join(where_conditions)
# 查询员工排行
sql = f"""
SELECT r.created_user_id as employee_id, u.real_name as employee_name,
COUNT(*) as count,
ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) as `rank`
FROM ai_article_published_records r
LEFT JOIN ai_users u ON r.created_user_id = u.id
WHERE {where_clause}
GROUP BY r.created_user_id, u.real_name
ORDER BY count DESC
LIMIT %s
"""
params.append(limit)
result = db_manager.execute_query(sql, params)
logger.info("获取员工排行成功")
return jsonify({
'code': 200,
'message': 'success',
'data': {
'list': result
},
'timestamp': int(datetime.now().timestamp() * 1000)
})
except Exception as e:
logger.error(f"[员工排行] 处理请求时发生错误: {str(e)}", exc_info=True)
return jsonify({
'code': 500,
'message': '服务器内部错误',
'data': None
}), 500