package repositories import ( "Quincy_admin/schemas" "fmt" "time" "github.com/jmoiron/sqlx" ) type UserRepository struct { db *sqlx.DB } func NewUserRepository(db *sqlx.DB) *UserRepository { return &UserRepository{db: db} } // Create 创建用户 func (r *UserRepository) Create(user *schemas.CreateUser) error { query := ` INSERT INTO admin_user ( rolecode, sessioncode, username, password, nickname, email, avatar, status, register_time, last_login_time ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ` now := time.Now() _, err := r.db.Exec(query, user.RoleCode, user.SessionCode, user.Username, user.Password, user.Nickname, user.Email, user.Avatar, user.Status, now, now) if err != nil { return err } user.RegisterTime = schemas.NewCustomTime(&now) user.LastLoginTime = schemas.NewCustomTime(&now) return nil } // IsUserCodeExists 检查用户编码是否已存在 func (r *UserRepository) IsUserCodeExists(scode string) (int, error) { var count int query := `SELECT COUNT(*) FROM admin_user WHERE sessioncode = ?` err := r.db.Get(&count, query, scode) return count, err } // IsEmailExists 检查邮箱是否已存在 func (r *UserRepository) IsEmailExists(email string) (int, error) { var count int query := `SELECT COUNT(*) FROM admin_user WHERE email = ?` err := r.db.Get(&count, query, email) return count, err } // IsUsernameExists 检查用户名是否已存在 func (r *UserRepository) IsUsernameExists(username string) (int, error) { var count int query := `SELECT COUNT(*) FROM admin_user WHERE username = ?` err := r.db.Get(&count, query, username) return count, err } // UpdateLastLoginTime 更新用户最后登录时间 func (r *UserRepository) UpdateLastLoginTime(scode string, loginTime time.Time) error { query := `UPDATE admin_user SET last_login_time = ? WHERE sessioncode = ?` _, err := r.db.Exec(query, loginTime, scode) return err } // FindByID 通过用户ID查找用户 func (r *UserRepository) FindByID(scode string) (*schemas.UserInfo, error) { query := ` SELECT tb1.id, COALESCE(tb2.role_id, 0) AS rolecode, tb1.sessioncode, tb1.username, tb1.password, tb1.nickname, tb1.email, tb1.avatar, tb1.status, tb1.register_time, tb1.last_login_time FROM admin_user tb1 LEFT JOIN admin_user_role tb2 ON tb1.id = tb2.user_id WHERE sessioncode = ? AND tb1.STATUS != 0 ORDER BY tb1.id LIMIT 1; ` user := &schemas.UserInfo{} err := r.db.Get(user, query, scode) if err != nil { return nil, err } return user, nil } // FindByUsername 通过用户名查找用户 func (r *UserRepository) FindByUsername(username string) (*schemas.UserInfo, error) { query := ` SELECT tb1.id, tb1.sessioncode, COALESCE(tb2.role_id, 0) AS rolecode, tb1.username, tb1.password, tb1.nickname, tb1.email, tb1.avatar, tb1.status, tb1.register_time, tb1.last_login_time FROM admin_user tb1 LEFT JOIN admin_user_role tb2 ON tb1.id = tb2.user_id WHERE username = ? ORDER BY tb1.id DESC LIMIT 1; ` user := &schemas.UserInfo{} err := r.db.Get(user, query, username) if err != nil { return nil, err } return user, nil } // Update 更新用户 func (r *UserRepository) Update(user *schemas.UpdateUser) (int, error) { // 检查 sessioncode 是否为空 if user.ID == 0 { return 0, fmt.Errorf("用户编码不能为空") } // 构建动态更新语句 setClause := "" args := map[string]interface{}{ "id": user.ID, } if user.Password != "" && len(user.Password) > 0 { setClause += "password=:password, " args["password"] = user.Password } if user.Nickname != "" { setClause += "nickname=:nickname, " args["nickname"] = user.Nickname } if user.Email != "" { setClause += "email=:email, " args["email"] = user.Email } if user.Avatar != "" { setClause += "avatar=:avatar, " args["avatar"] = user.Avatar } // 如果没有要更新的字段,直接返回 if setClause == "" { return user.ID, nil } // 构建完整查询语句 query := "UPDATE admin_user SET " + setClause[:len(setClause)-2] + " WHERE id=:id" _, err := r.db.NamedExec(query, args) if err != nil { return user.ID, err } return user.ID, nil } // UpdateStatus 禁用用户 func (r *UserRepository) UpdateStatus(id int, status int) error { query := ` UPDATE admin_user SET status = ? WHERE id = ? ` _, err := r.db.Exec(query, status, id) if err != nil { return err } return nil } // UpdateRoleStatus 启用/禁用角色 func (r *UserRepository) UpdateRoleStatus(id int, status int) error { query := ` UPDATE admin_role SET status = ? WHERE id = ? ` _, err := r.db.Exec(query, status, id) if err != nil { return err } return nil } // GetUserList 用户列表 func (r *UserRepository) GetUserList(req *schemas.UserListRequest) ([]*schemas.UserInfo, int64, error) { offset := (req.PageIndex - 1) * req.PageSize // 查询总数 countQuery := `SELECT COUNT(*) FROM admin_user WHERE (nickname LIKE ? OR ? = '') AND (? IS NULL OR register_time >= ?) AND (? IS NULL OR register_time < ?)` var total int64 err := r.db.QueryRow(countQuery, "%"+req.NickName+"%", req.NickName, req.StartDate, req.StartDate, req.EndDate, req.EndDate).Scan(&total) if err != nil { return nil, 0, err } // 查询列表 - 使用sqlx的Select方法直接映射到结构体切片 query := ` SELECT tb1.id as id, COALESCE(tb3.id, 0) AS rolecode, COALESCE(tb3.name, '') AS rolename, tb1.sessioncode as sessioncode, tb1.username as username, tb1.password as password, tb1.nickname as nickname, tb1.email as email, tb1.avatar as avatar, tb1.status as status, tb1.register_time as register_time, tb1.last_login_time as last_login_time FROM admin_user tb1 LEFT JOIN admin_user_role tb2 ON tb1.id = tb2.user_id LEFT JOIN admin_role tb3 ON tb2.role_id = tb3.id WHERE (tb1.nickname LIKE ? OR ? = '') AND (? IS NULL OR tb1.register_time >= ?) AND (? IS NULL OR tb1.register_time < ?) ORDER BY id LIMIT ? OFFSET ? ` var users []*schemas.UserInfo err = r.db.Select(&users, query, "%"+req.NickName+"%", req.NickName, req.StartDate, req.StartDate, req.EndDate, req.EndDate, req.PageSize, offset) if err != nil { return nil, 0, err } return users, total, nil } // GetRoleList 角色列表 func (r *UserRepository) GetRoleList(req *schemas.RoleListRequest) ([]*schemas.RoleResponseList, int64, error) { offset := (req.PageIndex - 1) * req.PageSize // 查询总数 countQuery := `SELECT COUNT(*) FROM admin_role WHERE (? IS NULL OR create_time >= ?) AND (? IS NULL OR create_time < ?)` var total int64 err := r.db.QueryRow(countQuery, req.StartDate, req.StartDate, req.EndDate, req.EndDate).Scan(&total) if err != nil { return nil, 0, err } // 查询列表 - 使用sqlx的Select方法直接映射到结构体切片 query := ` SELECT id, name, description, status, create_time FROM admin_role WHERE (? IS NULL OR create_time >= ?) AND (? IS NULL OR create_time < ?) ORDER BY id LIMIT ? OFFSET ? ` var items []*schemas.RoleResponseList err = r.db.Select(&items, query, req.StartDate, req.StartDate, req.EndDate, req.EndDate, req.PageSize, offset) if err != nil { return nil, 0, err } return items, total, nil } // RecordLoginLog 记录登录日志 func (r *UserRepository) RecordLoginLog(log *schemas.LoginLog) error { query := ` INSERT INTO admin_login_logs ( user_id, username, ip_address, location, user_agent, login_time, status, failure_reason, create_time ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ` now := time.Now() _, err := r.db.Exec(query, log.UserID, log.Username, log.IPAddress, log.Location, log.UserAgent, log.LoginTime, log.Status, log.FailureReason, now, ) if err != nil { return err } return nil } // GetLoginLogList 获取登录日志列表 func (r *UserRepository) GetLoginLogList(req *schemas.LoginLogListRequest) ([]*schemas.LoginLog, int64, error) { offset := (req.PageIndex - 1) * req.PageSize // 查询总数 countQuery := ` SELECT COUNT(*) FROM admin_login_logs WHERE isdel = 0 AND (? IS NULL OR create_time >= ?) AND (? IS NULL OR create_time < ?) ` var total int64 err := r.db.QueryRow(countQuery, req.StartDate.Time, req.StartDate.Time, req.EndDate.Time, req.EndDate.Time).Scan(&total) if err != nil { return nil, 0, err } query := ` SELECT tb1.id, tb1.username, tb1.user_id, tb1.ip_address, tb1.user_agent, tb1.status, tb1.failure_reason, tb1.login_time FROM admin_login_logs tb1 WHERE tb1.isdel = 0 AND (? IS NULL OR tb1.create_time >= ?) AND (? IS NULL OR tb1.create_time < ?) ORDER BY id DESC LIMIT ? OFFSET ? ` var items []*schemas.LoginLog err = r.db.Select(&items, query, req.StartDate.Time, req.StartDate.Time, req.EndDate.Time, req.EndDate.Time, req.PageSize, offset) if err != nil { return nil, 0, err } return items, total, nil } // AssignRoleExists 检查用户是否已分配角色 func (r *UserRepository) AssignRoleExists(userIdValue int) (bool, error) { var count int query := `SELECT COUNT(1) FROM admin_user_role WHERE user_id = ?` err := r.db.Get(&count, query, userIdValue) if err != nil { return false, err } return count > 0, nil } // AssignRole 角色分配 func (r *UserRepository) AssignRole(userIdValue int, roleIdValue int) error { query := ` INSERT INTO admin_user_role (user_id, role_id) VALUES (?, ?) ` _, err := r.db.Exec(query, userIdValue, roleIdValue) if err != nil { return err } return nil } // UpdateAssignRole 更新角色分配 func (r *UserRepository) UpdateAssignRole(userIdValue int, roleIdValue int) error { query := ` UPDATE admin_user_role SET Role_id = ? WHERE user_id = ? ` _, err := r.db.Exec(query, roleIdValue, userIdValue) if err != nil { return err } return nil } // CreateRole 创建角色 func (r *UserRepository) CreateRole(req *schemas.CreateRole) error { query := ` INSERT INTO admin_role (name, description) VALUES (?, ?) ` _, err := r.db.Exec(query, req.Name, req.Description) if err != nil { return err } return nil } // UpdateRole 更新角色 func (r *UserRepository) UpdateRole(req *schemas.CreateRole) error { query := ` UPDATE admin_role SET name = ?, description = ? WHERE id = ? ` _, err := r.db.Exec(query, req.Name, req.Description, req.ID) if err != nil { return err } return nil }