87 lines
2.3 KiB
Go
87 lines
2.3 KiB
Go
package handlers
|
||
|
||
import (
|
||
"github.com/gin-gonic/gin"
|
||
"github.com/niangaodev/art-code/config"
|
||
"github.com/niangaodev/art-code/repositories"
|
||
"github.com/niangaodev/art-code/utils"
|
||
)
|
||
|
||
// GetDashboardStats 获取仪表盘统计数据
|
||
func GetDashboardStats(c *gin.Context) {
|
||
startDate := c.Query("startDate")
|
||
endDate := c.Query("endDate")
|
||
|
||
// 1. 获取博文增长趋势
|
||
postsTrend, err := repositories.GetNewPostsTrend(startDate, endDate)
|
||
if err != nil {
|
||
postsTrend = []repositories.TrendData{} // Fallback empty
|
||
}
|
||
|
||
// 2. 获取访客UV (根据IP)
|
||
uvTrend, err := repositories.GetDailyUV(startDate, endDate)
|
||
if err != nil {
|
||
uvTrend = []repositories.UVTrendData{}
|
||
}
|
||
|
||
// 3. 用户画像-地域分布
|
||
userRegions, err := repositories.GetUserRegions(startDate, endDate)
|
||
if err != nil {
|
||
userRegions = []struct {
|
||
Region string
|
||
Count int
|
||
}{}
|
||
}
|
||
|
||
// 4. 热门文章 Top 5
|
||
// 优先使用访问日志统计,如果没有则回退到posts表的read_count
|
||
topPosts, err := repositories.GetTopArticlesByAccess(5)
|
||
if err != nil || len(topPosts) == 0 {
|
||
// Fallback to post.read_count
|
||
dbPosts, err := repositories.GetTopPosts(5)
|
||
if err == nil {
|
||
// Convert models.Post to the struct structure
|
||
// Create a temporary structure slice
|
||
topPosts = make([]struct {
|
||
ArticleID int `json:"article_id"`
|
||
Title string `json:"title"`
|
||
Count int `json:"count"`
|
||
}, 0)
|
||
for _, p := range dbPosts {
|
||
topPosts = append(topPosts, struct {
|
||
ArticleID int `json:"article_id"`
|
||
Title string `json:"title"`
|
||
Count int `json:"count"`
|
||
}{
|
||
ArticleID: int(p.ID),
|
||
Title: p.Title,
|
||
Count: int(p.ReadCount),
|
||
})
|
||
}
|
||
}
|
||
}
|
||
|
||
// 5. 合作咨询总数
|
||
var inquiryCount int
|
||
config.DB.QueryRow("SELECT COUNT(*) FROM inquiries").Scan(&inquiryCount)
|
||
|
||
// 6. 作品总数
|
||
var workCount int
|
||
// 假设 works 表存在,如果没有则返回 0
|
||
config.DB.QueryRow("SELECT COUNT(*) FROM works").Scan(&workCount)
|
||
|
||
// 7. 文章总数
|
||
var postCount int
|
||
config.DB.QueryRow("SELECT COUNT(*) FROM posts").Scan(&postCount)
|
||
|
||
utils.Success(c, gin.H{
|
||
"postsTrend": postsTrend,
|
||
"uvTrend": uvTrend,
|
||
"userRegions": userRegions,
|
||
"topPosts": topPosts,
|
||
"inquiryCount": inquiryCount,
|
||
"posts": postCount,
|
||
"works": workCount,
|
||
})
|
||
}
|