package api import ( "licserver/internal/model" "net/http" "time" "github.com/gin-gonic/gin" "gorm.io/gorm" ) type DashboardHandler struct { db *gorm.DB } func NewDashboardHandler(db *gorm.DB) *DashboardHandler { return &DashboardHandler{db: db} } func (h *DashboardHandler) GetStats(c *gin.Context) { var stats struct { TotalDevices int64 `json:"total_devices"` TotalLicenses int64 `json:"total_licenses"` TodayNew int64 `json:"today_new"` OnlineDevices int64 `json:"online_devices"` } // 获取设备总数 h.db.Model(&model.Device{}).Count(&stats.TotalDevices) // 获取授权码总数 h.db.Model(&model.LicenseCode{}).Count(&stats.TotalLicenses) // 获取今日新增设备数 today := time.Now().Format("2006-01-02") h.db.Model(&model.Device{}).Where("DATE(created_at) = ?", today).Count(&stats.TodayNew) // 获取在线设备数(最近30分钟内有活动的设备) thirtyMinutesAgo := time.Now().Add(-30 * time.Minute) h.db.Model(&model.Device{}). Where("last_active_at > ?", thirtyMinutesAgo). Count(&stats.OnlineDevices) c.JSON(http.StatusOK, stats) }