feat: 数据分析
This commit is contained in:
@@ -15,30 +15,55 @@ var InteractionServiceApp = new(InteractionService)
|
||||
|
||||
// AddHistory 添加收听历史
|
||||
func (s *InteractionService) AddHistory(userId string, req radioReq.AddHistory) error {
|
||||
// 先查找是否已存在记录
|
||||
// 1. 获取节目信息以拿到 ChannelId (用于日志冗余方便统计)
|
||||
var program radio.RadioProgram
|
||||
if err := global.DB.Select("id, channel_id").Where("id = ?", req.ProgramId).First(&program).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 2. 写入/更新用户书签 (RadioHistory)
|
||||
var history radio.RadioHistory
|
||||
err := global.DB.Where("user_id = ? AND program_id = ?", userId, req.ProgramId).First(&history).Error
|
||||
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// 不存在,创建新记录
|
||||
history = radio.RadioHistory{
|
||||
UserId: userId,
|
||||
ProgramId: req.ProgramId,
|
||||
Progress: req.Progress,
|
||||
Duration: req.Duration,
|
||||
}
|
||||
return global.DB.Create(&history).Error
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if err := global.DB.Create(&history).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
} else if err == nil {
|
||||
if err := global.DB.Model(&history).Updates(map[string]interface{}{
|
||||
"progress": req.Progress,
|
||||
"duration": req.Duration,
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
|
||||
// 存在,更新进度
|
||||
return global.DB.Model(&history).Updates(map[string]interface{}{
|
||||
"progress": req.Progress,
|
||||
"duration": req.Duration,
|
||||
}).Error
|
||||
// 3. 贪婪学习:如果节目表时长为0,且前端传回了有效时长,则自动补全元数据
|
||||
if req.Duration > 0 && program.Duration == 0 {
|
||||
global.DB.Model(&radio.RadioProgram{}).Where("id = ?", req.ProgramId).Update("duration", req.Duration)
|
||||
}
|
||||
|
||||
// 4. 异步写入不可删除的日志表 (RadioListenLog) 用于趋势统计
|
||||
go func() {
|
||||
listenLog := radio.RadioListenLog{
|
||||
UserId: userId,
|
||||
ProgramId: req.ProgramId,
|
||||
ChannelId: program.ChannelId,
|
||||
Progress: req.Progress,
|
||||
Duration: req.Duration,
|
||||
}
|
||||
global.DB.Create(&listenLog)
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetHistoryList 获取收听历史列表
|
||||
|
||||
Reference in New Issue
Block a user