You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
2.1 KiB
80 lines
2.1 KiB
package service
|
|
|
|
import (
|
|
"time"
|
|
|
|
"laic-backend/common"
|
|
"laic-backend/logger"
|
|
"laic-backend/model"
|
|
"laic-backend/tool"
|
|
"laic-backend/vo"
|
|
)
|
|
|
|
type OperationLogService struct{}
|
|
|
|
var DefaultOperationLogService = &OperationLogService{}
|
|
|
|
// BootstrapOperationLog 确保基础运行时表存在(历史库未跑 DDL 时兜底)。
|
|
func BootstrapOperationLog() {
|
|
if err := common.DB.AutoMigrate(&model.OperationLog{}, &model.LiveViewerLease{}); err != nil {
|
|
logger.ERROR("迁移基础运行时表失败", err)
|
|
}
|
|
}
|
|
|
|
// Record 写入一条操作日志
|
|
func (s *OperationLogService) Record(userID int64, userName, module, action, detail, result, ip string) {
|
|
if userID == 0 {
|
|
return
|
|
}
|
|
id, err := tool.NextID()
|
|
if err != nil {
|
|
logger.ERROR("生成操作日志 ID 失败", err)
|
|
return
|
|
}
|
|
log := &model.OperationLog{
|
|
ID: id,
|
|
UserID: userID,
|
|
UserName: userName,
|
|
Module: module,
|
|
Action: action,
|
|
Detail: detail,
|
|
Result: result,
|
|
IP: ip,
|
|
CreatedAt: time.Now(),
|
|
}
|
|
if err := common.DB.Create(log).Error; err != nil {
|
|
logger.ERROR("写入操作日志失败", err)
|
|
}
|
|
}
|
|
|
|
// GetPage 操作日志分页(admin 全量,user 仅本人)
|
|
func (s *OperationLogService) GetPage(req *vo.OperationLogPageReq) (*common.PageResponse[model.OperationLog], *common.BusiError) {
|
|
db := common.DB.Model(&model.OperationLog{})
|
|
if req.UserID > 0 {
|
|
db = db.Where("user_id = ?", req.UserID)
|
|
}
|
|
if req.Module != "" {
|
|
db = db.Where("module = ?", req.Module)
|
|
}
|
|
if req.Action != "" {
|
|
db = db.Where("action = ?", req.Action)
|
|
}
|
|
if req.Result != "" {
|
|
db = db.Where("result = ?", req.Result)
|
|
}
|
|
if req.Keyword != "" {
|
|
kw := "%" + req.Keyword + "%"
|
|
db = db.Where("module LIKE ? OR action LIKE ? OR detail LIKE ?", kw, kw, kw)
|
|
}
|
|
var total int64
|
|
if err := db.Count(&total).Error; err != nil {
|
|
logger.ERROR("统计操作日志失败", err)
|
|
return nil, common.ErrInternal
|
|
}
|
|
var list []model.OperationLog
|
|
if err := db.Scopes(req.Paginate).Order("id DESC").Find(&list).Error; err != nil {
|
|
logger.ERROR("查询操作日志失败", err)
|
|
return nil, common.ErrInternal
|
|
}
|
|
return common.Page(req.Pagination, total, list), nil
|
|
}
|
|
|