Skip to main content

Overview

The Analytics Summary functions provide comprehensive metrics and KPIs for analyzing user engagement, performance, and risk across the Dashboard Dilemas platform. These functions support filtering by date range, client, game, and user area.

get_analytics_summary()

Retrieves a comprehensive summary of analytics metrics including user engagement, session statistics, and risk indicators.

Function Signature

function get_analytics_summary($filters = [])

Parameters

filters
array
default:"[]"
Optional array of filter criteria

Returns

totalUsers
int
Total number of users in the system (unfiltered by date)
activeUsers
int
Number of users who have played sessions in the filtered period
totalSessions
int
Total number of game sessions in the filtered period
avgScore
float
Average score across all sessions (percentage, 0-100)
avgTime
int
Average session duration in seconds
engagementScore
int
Engagement percentage: (activeUsers / totalUsers) * 100
riskIndex
int
Percentage of sessions with score below 60% (failing threshold)
knowledgeLift
int
Knowledge improvement metric (currently static at 12)

Example Usage

// Get overall analytics summary
$summary = get_analytics_summary();
echo "Active Users: " . $summary['activeUsers'];
echo "Average Score: " . $summary['avgScore'] . "%";

Response Example

{
  "totalUsers": 250,
  "activeUsers": 187,
  "totalSessions": 542,
  "avgScore": 78.5,
  "avgTime": 420,
  "engagementScore": 75,
  "riskIndex": 12,
  "knowledgeLift": 12
}

Performance Notes

This function uses caching with a 15-minute TTL (900 seconds) to improve performance. The cache is invalidated when filter parameters change.

get_performance_by_area()

Retrieves performance metrics grouped by user areas/departments.

Function Signature

function get_performance_by_area($filters = [])

Parameters

filters
array
default:"[]"
Same filter options as get_analytics_summary()

Returns

Array of area performance objects:
area
string
Name of the area/department
active_users
int
Number of distinct users in this area
avg_score
float
Average score for this area (percentage, 0-100)
sessions
int
Total sessions played by users in this area

Example Usage

$filters = [
    'start_date' => '2024-01-01',
    'end_date' => '2024-01-31',
    'client' => 'Acme Corp'
];

$areaPerformance = get_performance_by_area($filters);

foreach ($areaPerformance as $area) {
    echo "{$area['area']}: {$area['avg_score']}% avg, {$area['active_users']} users\n";
}

Response Example

[
  {
    "area": "Sales",
    "active_users": 45,
    "avg_score": 82.3,
    "sessions": 156
  },
  {
    "area": "Marketing",
    "active_users": 38,
    "avg_score": 76.8,
    "sessions": 124
  },
  {
    "area": "Engineering",
    "active_users": 52,
    "avg_score": 88.1,
    "sessions": 201
  }
]

get_hourly_distribution()

Returns session count distribution by hour of day.

Function Signature

function get_hourly_distribution($filters = [])

Parameters

filters
array
default:"[]"
Same filter options as get_analytics_summary()

Returns

Associative array with hour (0-23) as keys and session count as values.

Example Usage

$hourlyData = get_hourly_distribution(['client' => 'Acme Corp']);

// Find peak hour
$peakHour = array_keys($hourlyData, max($hourlyData))[0];
echo "Peak activity at {$peakHour}:00 with {$hourlyData[$peakHour]} sessions";

Response Example

{
  "9": 42,
  "10": 67,
  "11": 58,
  "14": 71,
  "15": 89,
  "16": 65
}

get_game_performance()

Retrieves detailed performance metrics for all games.

Function Signature

function get_game_performance($filters = [])

Parameters

filters
array
default:"[]"
Same filter options as get_analytics_summary()

Returns

Array of game performance objects:
name
string
Game/dilemma title
sessions
int
Total number of sessions for this game
avg_score
float
Average score (percentage, 0-100)
total_points
int
Sum of all points earned across sessions
avg_duration
int
Average session duration in seconds
pass_rate
float
Percentage of sessions with score >= 60%

Example Usage

$gamePerf = get_game_performance(['start_date' => '2024-01-01']);

// Sort by pass rate
usort($gamePerf, fn($a, $b) => $b['pass_rate'] - $a['pass_rate']);

// Show top 5 games
foreach (array_slice($gamePerf, 0, 5) as $game) {
    echo "{$game['name']}: {$game['pass_rate']}% pass rate\n";
}

Response Example

[
  {
    "name": "Ethical Leadership Scenarios",
    "sessions": 234,
    "avg_score": 82.5,
    "total_points": 19305,
    "avg_duration": 380,
    "pass_rate": 87.2
  },
  {
    "name": "Workplace Conflicts",
    "sessions": 198,
    "avg_score": 74.3,
    "total_points": 14711,
    "avg_duration": 425,
    "pass_rate": 78.8
  }
]

Additional Analytics Functions

get_activity_over_time()

Returns daily session counts for trend analysis.
function get_activity_over_time($filters = [])
Returns: Associative array with dates as keys and session counts as values.

get_category_distribution()

Returns session distribution by game category/type.
function get_category_distribution($filters = [])
Returns: Associative array with category names as keys and session counts as values.

get_weekday_distribution()

Returns session distribution by day of week.
function get_weekday_distribution($filters = [])
Returns: Associative array with weekday names as keys and session counts as values.

get_score_distribution()

Returns session counts grouped by score ranges.
function get_score_distribution($filters = [])
Returns: Associative array with score ranges (e.g., “0-200”, “201-400”) as keys.

get_top_users_engagement()

Returns top users by total score and session count.
function get_top_users_engagement($limit = 5, $filters = [])
limit
int
default:"5"
Number of top users to return
Returns: Array of user objects with display_name, sessions, and total_score.

get_top_risk_questions()

Identifies questions with highest failure rates.
function get_top_risk_questions($limit = 5, $filters = [])
limit
int
default:"5"
Number of risky questions to return
Returns: Array of question objects with text, category, total_answers, fail_count, and avg_score.

Filter Helper Function

get_analytics_query_parts()

Internal helper that builds SQL WHERE clauses and parameters from filters.
function get_analytics_query_parts($filters)
This function is used internally by all analytics functions to ensure consistent filtering logic.
This is an internal function and should not be called directly from application code.

Implementation Notes

Score Calculation

Scores are normalized to percentages (0-100) based on each game’s maximum possible score:
  • For “Angel vs Demonio” games: questions_count * 3
  • For standard games: Sum of question scores
  • Default fallback: 100 points

Risk Threshold

Sessions with scores below 60% are considered “at risk” and contribute to the risk index.

Performance Optimization

  • get_analytics_summary() uses a 15-minute cache
  • All queries use prepared statements with parameterized values
  • Complex aggregations are handled in single SQL queries where possible
  • LEFT JOINs are preferred over correlated subqueries

Error Handling

All analytics functions return safe defaults on error:
  • Empty arrays for list functions
  • Zero values for count/metric functions
  • Functions catch PDOException and log errors while returning gracefully

Build docs developers (and LLMs) love