Files
0451meishi/backend/internal/handlers/admin_rankings.go
2026-01-15 11:37:22 +08:00

82 lines
2.3 KiB
Go

package handlers
import (
"net/http"
"strconv"
"strings"
"0451meishiditu/backend/internal/resp"
"github.com/gin-gonic/gin"
)
func (h *Handlers) AdminStoreRanking(c *gin.Context) {
by := strings.TrimSpace(c.Query("by")) // hotness/likes/search/reviews
page, pageSize := parsePage(c.Query("page"), c.Query("page_size"))
if by == "" {
by = "hotness"
}
order := "store_metrics.score desc"
switch by {
case "likes":
order = "store_metrics.likes_count desc"
case "search":
order = "store_metrics.search_count desc"
case "reviews":
order = "store_metrics.reviews_count desc"
}
type row struct {
StoreID uint `json:"store_id"`
Name string `json:"name"`
CategoryID uint `json:"category_id"`
Status string `json:"status"`
LikesCount int64 `json:"likes_count"`
SearchCount int64 `json:"search_count"`
ReviewsCount int64 `json:"reviews_count"`
Score float64 `json:"score"`
}
var total int64
_ = h.db.Table("store_metrics").
Joins("left join stores on stores.id = store_metrics.store_id").
Where("stores.deleted_at is null").
Count(&total).Error
var out []row
if err := h.db.Table("store_metrics").
Select("stores.id as store_id, stores.name, stores.category_id, stores.status, store_metrics.likes_count, store_metrics.search_count, store_metrics.reviews_count, store_metrics.score").
Joins("left join stores on stores.id = store_metrics.store_id").
Where("stores.deleted_at is null").
Order(order + ", stores.id desc").
Limit(pageSize).
Offset((page - 1) * pageSize).
Scan(&out).Error; err != nil {
resp.Fail(c, http.StatusInternalServerError, "db error")
return
}
resp.OKMeta(c, out, gin.H{
"page": page,
"page_size": pageSize,
"total": total,
"total_page": calcTotalPage(total, pageSize),
})
}
func (h *Handlers) AdminRecalcStoreScore(c *gin.Context) {
limit, _ := strconv.Atoi(c.Query("limit"))
if limit <= 0 || limit > 5000 {
limit = 5000
}
// score = likes*2 + search*1 + reviews*3
err := h.db.Exec("update store_metrics set score = likes_count*2 + search_count*1 + reviews_count*3, updated_at = now() limit ?", limit).Error
if err != nil {
resp.Fail(c, http.StatusInternalServerError, "recalc failed")
return
}
resp.OK(c, gin.H{"updated": true})
}