Files
LicenseManger/internal/api/dashboard.go
2024-11-14 22:55:43 +08:00

46 lines
1.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)
}