diff --git a/backend/internal/router/admin/dashboard.go b/backend/internal/router/admin/dashboard.go index 8b06b34..7b5b126 100644 --- a/backend/internal/router/admin/dashboard.go +++ b/backend/internal/router/admin/dashboard.go @@ -115,27 +115,34 @@ func handleGetDashboard(c *gin.Context) { go func() { defer wg.Done() if len(appIDs) > 0 { - type DeviceCount struct { - DeviceType string - Count int - } - var deviceCounts []DeviceCount - database.DB.Model(&model.UserDevice{}). - Select("device_type, COUNT(*) as count"). - Where("application_id IN ?", appIDs). - Group("device_type"). - Order("count DESC"). - Find(&deviceCounts) + var totalOnline int64 + var totalOffline int64 - provinces := make([]gin.H, 0, len(deviceCounts)) - for _, dc := range deviceCounts { - provinces = append(provinces, gin.H{ - "name": dc.DeviceType, - "count": dc.Count, - "online": 0, - "offline": dc.Count, - }) + var devices []model.UserDevice + database.DB.Where("application_id IN ?", appIDs).Find(&devices) + + for _, device := range devices { + var sessionCount int64 + database.DB.Model(&model.DeviceSession{}). + Where("device_id = ? AND last_heartbeat > ?", device.ID, time.Now().Add(-5*time.Minute)). + Count(&sessionCount) + + if sessionCount > 0 { + totalOnline++ + } else { + totalOffline++ + } } + + provinces := []gin.H{ + { + "name": "China", + "count": totalOnline + totalOffline, + "online": totalOnline, + "offline": totalOffline, + }, + } + mu.Lock() userDistribution["provinces"] = provinces mu.Unlock()