dashboard.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. """
  2. Dashboard API endpoints.
  3. Provides endpoints for:
  4. - GET /api/dashboard/stats - Get dashboard statistics
  5. Requirements: 7.2
  6. """
  7. from flask import jsonify
  8. from app.api import api_bp
  9. from app.models import Task, Report
  10. from app.services import login_required, get_current_user_from_context
  11. from app import db
  12. @api_bp.route('/dashboard/stats', methods=['GET'])
  13. @login_required
  14. def get_dashboard_stats():
  15. """
  16. Get dashboard statistics including task counts and recent reports.
  17. Returns:
  18. JSON with task statistics and recent reports
  19. Requirements:
  20. - 7.2: Show task status summary and recent reports
  21. """
  22. current_user = get_current_user_from_context()
  23. # Build base query based on user role
  24. if current_user.role in ['admin', 'power_user']:
  25. task_query = Task.query
  26. else:
  27. # Regular users can only see their own tasks
  28. task_query = Task.query.filter_by(created_by=current_user.id)
  29. # Get task counts by status
  30. total_tasks = task_query.count()
  31. pending_tasks = task_query.filter_by(status='pending').count()
  32. running_tasks = task_query.filter_by(status='running').count()
  33. completed_tasks = task_query.filter_by(status='completed').count()
  34. failed_tasks = task_query.filter_by(status='failed').count()
  35. # Get recent reports (last 5)
  36. if current_user.role in ['admin', 'power_user']:
  37. recent_reports_query = db.session.query(Report).join(Task)
  38. else:
  39. recent_reports_query = db.session.query(Report).join(Task).filter(
  40. Task.created_by == current_user.id
  41. )
  42. recent_reports = recent_reports_query.order_by(
  43. Report.created_at.desc()
  44. ).limit(5).all()
  45. # Get total reports count
  46. total_reports = recent_reports_query.count()
  47. return jsonify({
  48. 'tasks': {
  49. 'total': total_tasks,
  50. 'pending': pending_tasks,
  51. 'running': running_tasks,
  52. 'completed': completed_tasks,
  53. 'failed': failed_tasks
  54. },
  55. 'reports': {
  56. 'total': total_reports,
  57. 'recent': [report.to_dict() for report in recent_reports]
  58. }
  59. }), 200