71 lines
2.0 KiB
Go
71 lines
2.0 KiB
Go
package repository
|
|
|
|
import (
|
|
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// FindAuditLogOptions 定义了查询审计日志的选项
|
|
type FindAuditLogOptions struct {
|
|
UserID *uint // 根据用户ID过滤
|
|
ActionType string // 根据操作类型过滤
|
|
Page int // 页码
|
|
PageSize int // 每页大小
|
|
}
|
|
|
|
// UserActionLogRepository 定义了与用户操作日志相关的数据库操作接口
|
|
type UserActionLogRepository interface {
|
|
Create(log *models.UserActionLog) error
|
|
List(options FindAuditLogOptions) ([]*models.UserActionLog, int64, error)
|
|
}
|
|
|
|
// gormUserActionLogRepository 是 UserActionLogRepository 的 GORM 实现
|
|
type gormUserActionLogRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
// NewGormUserActionLogRepository 创建一个新的 UserActionLogRepository GORM 实现实例
|
|
func NewGormUserActionLogRepository(db *gorm.DB) UserActionLogRepository {
|
|
return &gormUserActionLogRepository{db: db}
|
|
}
|
|
|
|
// Create 创建一条新的用户操作日志记录
|
|
func (r *gormUserActionLogRepository) Create(log *models.UserActionLog) error {
|
|
return r.db.Create(log).Error
|
|
}
|
|
|
|
// List 根据选项查询用户操作日志,并返回总数
|
|
func (r *gormUserActionLogRepository) List(options FindAuditLogOptions) ([]*models.UserActionLog, int64, error) {
|
|
var logs []*models.UserActionLog
|
|
var total int64
|
|
|
|
query := r.db.Model(&models.UserActionLog{})
|
|
|
|
if options.UserID != nil {
|
|
query = query.Where("user_id = ?", *options.UserID)
|
|
}
|
|
if options.ActionType != "" {
|
|
query = query.Where("action_type = ?", options.ActionType)
|
|
}
|
|
|
|
// 统计总数
|
|
if err := query.Count(&total).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
// 分页查询
|
|
if options.Page > 0 && options.PageSize > 0 {
|
|
offset := (options.Page - 1) * options.PageSize
|
|
query = query.Offset(offset).Limit(options.PageSize)
|
|
}
|
|
|
|
// 默认按创建时间倒序
|
|
query = query.Order("created_at DESC")
|
|
|
|
if err := query.Find(&logs).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
return logs, total, nil
|
|
}
|