45 lines
1.1 KiB
Go
45 lines
1.1 KiB
Go
package service
|
|
|
|
import (
|
|
"strings"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
|
|
"nl-pms-api/internal/commonservice"
|
|
"nl-pms-api/internal/model"
|
|
)
|
|
|
|
// ActivityService 日活埋点。
|
|
type ActivityService struct {
|
|
DB *gorm.DB
|
|
}
|
|
|
|
// Ping 记录今日活跃并刷新 users.last_seen_at / last_login_ip。
|
|
func (s *ActivityService) Ping(userID int64, clientIP string) error {
|
|
if userID <= 0 {
|
|
return commonservice.Unauthorized("UNAUTHORIZED")
|
|
}
|
|
now := commonservice.NowRFC()
|
|
today := time.Now().In(time.Local).Format("2006-01-02")
|
|
ip := strings.TrimSpace(clientIP)
|
|
row := model.UserDailyActive{
|
|
UserID: userID,
|
|
ActiveDate: today,
|
|
LastIP: ip,
|
|
LastSeenAt: now,
|
|
}
|
|
if err := s.DB.Clauses(clause.OnConflict{
|
|
Columns: []clause.Column{{Name: "user_id"}, {Name: "active_date"}},
|
|
DoUpdates: clause.AssignmentColumns([]string{"last_ip", "last_seen_at"}),
|
|
}).Create(&row).Error; err != nil {
|
|
return commonservice.Internal("SAVE_FAILED")
|
|
}
|
|
_ = s.DB.Model(&model.User{}).Where("id = ?", userID).Updates(map[string]any{
|
|
"last_seen_at": now,
|
|
"last_login_ip": ip,
|
|
}).Error
|
|
return nil
|
|
}
|