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.
90 lines
2.0 KiB
90 lines
2.0 KiB
package user
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/youruser/base/internal/svc"
|
|
"github.com/youruser/base/internal/types"
|
|
"github.com/youruser/base/model"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type UpdateUserLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
// 更新用户信息
|
|
func NewUpdateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserLogic {
|
|
return &UpdateUserLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *UpdateUserLogic) UpdateUser(req *types.UpdateUserRequest) (resp *types.UserInfo, err error) {
|
|
// 检查用户是否存在
|
|
user, err := model.FindOne(l.ctx, l.svcCtx.DB, req.Id)
|
|
if err != nil {
|
|
if err == model.ErrNotFound {
|
|
return nil, fmt.Errorf("用户不存在")
|
|
}
|
|
return nil, fmt.Errorf("查询用户失败: %v", err)
|
|
}
|
|
|
|
// 更新字段
|
|
if req.Username != "" {
|
|
user.Username = req.Username
|
|
}
|
|
if req.Email != "" {
|
|
// 检查邮箱是否被其他用户使用
|
|
existing, err := model.FindOneByEmail(l.ctx, l.svcCtx.DB, req.Email)
|
|
if err == nil && existing.Id != req.Id {
|
|
return nil, fmt.Errorf("邮箱已被使用")
|
|
}
|
|
user.Email = req.Email
|
|
}
|
|
if req.Phone != "" {
|
|
user.Phone = req.Phone
|
|
}
|
|
if req.Status > 0 {
|
|
user.Status = int64(req.Status)
|
|
}
|
|
if req.Role != "" {
|
|
user.Role = req.Role
|
|
}
|
|
if req.Remark != "" {
|
|
user.Remark = req.Remark
|
|
}
|
|
|
|
// 更新数据库
|
|
err = model.Update(l.ctx, l.svcCtx.DB, user)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("更新用户失败: %v", err)
|
|
}
|
|
|
|
// 重新查询获取更新后的数据
|
|
user, err = model.FindOne(l.ctx, l.svcCtx.DB, req.Id)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("查询用户失败: %v", err)
|
|
}
|
|
|
|
resp = &types.UserInfo{
|
|
Id: user.Id,
|
|
Username: user.Username,
|
|
Email: user.Email,
|
|
Phone: user.Phone,
|
|
Role: user.Role,
|
|
Source: user.Source,
|
|
Remark: user.Remark,
|
|
Status: int(user.Status),
|
|
CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"),
|
|
UpdatedAt: user.UpdatedAt.Format("2006-01-02 15:04:05"),
|
|
}
|
|
|
|
return resp, nil
|
|
}
|
|
|