更新接口

This commit is contained in:
2026-07-17 11:57:10 +08:00
parent 9b788189fd
commit 7ab6958538
3 changed files with 96 additions and 18 deletions
+83
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"io"
"sort"
"strconv"
"strings"
"time"
@@ -162,6 +163,88 @@ func cmsCategoryToMap(row models.CmsArticleCategory) map[string]interface{} {
}
}
// ContentStats GET /backend/contentstats
func (c *BackendArticleController) ContentStats() {
if !cmsEnsureTables(&c.Controller) {
return
}
claims, err := c.cmsClaims()
if err != nil {
c.cmsJSONErr(401, 401, err.Error())
return
}
tid := cmsEffectiveTid(&c.Controller, claims)
if tid == 0 {
c.cmsJSONErr(400, 400, "tid不能为空")
return
}
// 统计已发布且未删除的文章,避免把草稿、下架文章计入内容数据。
var rows []models.CmsArticle
_, err = models.Orm.QueryTable(new(models.CmsArticle)).
Filter("tid", tid).
Filter("status", 2).
Filter("delete_time__isnull", true).
All(&rows)
if err != nil && err != orm.ErrNoRows {
c.cmsJSONErr(500, 500, "获取内容统计失败")
return
}
totalArticles := len(rows)
now := time.Now()
year, month, _ := now.Date()
totalLikes := 0
totalViews := 0
monthArticles := 0
for _, row := range rows {
totalLikes += row.Likes
totalViews += row.Views
if row.PublishTime != nil {
publishYear, publishMonth, _ := row.PublishTime.Date()
if publishYear == year && publishMonth == month {
monthArticles++
}
}
}
// 按阅读量倒序返回热门文章。
sort.SliceStable(rows, func(i, j int) bool {
if rows[i].Views == rows[j].Views {
return rows[i].ID > rows[j].ID
}
return rows[i].Views > rows[j].Views
})
if len(rows) > 5 {
rows = rows[:5]
}
cateIDs := make([]uint64, 0, len(rows))
for _, row := range rows {
if row.CateID > 0 {
cateIDs = append(cateIDs, row.CateID)
}
}
cateNames := models.CmsCategoryNameMap(tid, cateIDs)
hotArticles := make([]map[string]interface{}, 0, len(rows))
for _, row := range rows {
hotArticles = append(hotArticles, cmsArticleToListItem(row, cateNames[row.CateID]))
}
c.Data["json"] = map[string]interface{}{
"code": 200,
"msg": "success",
"data": map[string]interface{}{
"total_articles": totalArticles,
"month_articles": monthArticles,
"total_likes": totalLikes,
"total_views": totalViews,
"hot_articles": hotArticles,
},
}
_ = c.ServeJSON()
}
// List GET /backend/articlesList
func (c *BackendArticleController) List() {
if !cmsEnsureTables(&c.Controller) {