109 lines
2.5 KiB
Go
109 lines
2.5 KiB
Go
package repositories
|
|
|
|
import (
|
|
"log"
|
|
// "time"
|
|
|
|
"github.com/niangaodev/art-code/config"
|
|
"github.com/niangaodev/art-code/models"
|
|
)
|
|
|
|
// CreateUserAccessLog 创建用户访问日志
|
|
func CreateUserAccessLog(logEntry *models.UserAccessLog) error {
|
|
query := `
|
|
INSERT INTO user_access_logs (user_id, user_ip, user_location, article_id, access_time)
|
|
VALUES (?, ?, ?, ?, NOW())
|
|
`
|
|
_, err := config.DB.Exec(query, logEntry.UserID, logEntry.UserIP, logEntry.UserLocation, logEntry.ArticleID)
|
|
if err != nil {
|
|
log.Printf("Error creating user access log: %v", err)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// AccessStats 访问统计数据结构
|
|
type AccessStats struct {
|
|
Date string `json:"date"`
|
|
Count int `json:"count"`
|
|
}
|
|
|
|
// GetArticleAccessTrend 获取文章访问趋势
|
|
func GetArticleAccessTrend(startDate, endDate string) ([]AccessStats, error) {
|
|
query := `
|
|
SELECT DATE_FORMAT(access_time, '%Y-%m-%d') as date, COUNT(*) as count
|
|
FROM user_access_logs
|
|
WHERE 1=1
|
|
`
|
|
args := []interface{}{}
|
|
|
|
if startDate != "" {
|
|
query += " AND access_time >= ?"
|
|
args = append(args, startDate)
|
|
}
|
|
if endDate != "" {
|
|
query += " AND access_time <= ?"
|
|
args = append(args, endDate+" 23:59:59")
|
|
}
|
|
|
|
query += `
|
|
GROUP BY date
|
|
ORDER BY date ASC
|
|
`
|
|
|
|
rows, err := config.DB.Query(query, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var results []AccessStats
|
|
for rows.Next() {
|
|
var s AccessStats
|
|
if err := rows.Scan(&s.Date, &s.Count); err != nil {
|
|
return nil, err
|
|
}
|
|
results = append(results, s)
|
|
}
|
|
return results, nil
|
|
}
|
|
|
|
// GetTopArticlesByAccess 获取访问量最高的文章
|
|
func GetTopArticlesByAccess(limit int) ([]struct {
|
|
ArticleID int `json:"article_id"`
|
|
Title string `json:"title"`
|
|
Count int `json:"count"`
|
|
}, error) {
|
|
query := `
|
|
SELECT l.article_id, p.title, COUNT(*) as count
|
|
FROM user_access_logs l
|
|
JOIN posts p ON l.article_id = p.id
|
|
GROUP BY l.article_id, p.title
|
|
ORDER BY count DESC
|
|
LIMIT ?
|
|
`
|
|
rows, err := config.DB.Query(query, limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var results []struct {
|
|
ArticleID int `json:"article_id"`
|
|
Title string `json:"title"`
|
|
Count int `json:"count"`
|
|
}
|
|
for rows.Next() {
|
|
var r struct {
|
|
ArticleID int `json:"article_id"`
|
|
Title string `json:"title"`
|
|
Count int `json:"count"`
|
|
}
|
|
if err := rows.Scan(&r.ArticleID, &r.Title, &r.Count); err != nil {
|
|
return nil, err
|
|
}
|
|
results = append(results, r)
|
|
}
|
|
return results, nil
|
|
}
|