作者 yangfu

用户基础管理

package command
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type BatchEnableCommand struct {
OperateInfo *domain.OperateInfo `json:"-"`
UserBaseIds []int64 `cname:"用户id列表" json:"userBaseIds" valid:"Required"`
// 启用状态(启用:1 禁用:2 注销:3)
EnableStatus int `cname:"启用状态(启用:1 禁用:2 注销:3)" json:"enableStatus" valid:"Required"`
}
func (batchEnableCommand *BatchEnableCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
if !(batchEnableCommand.EnableStatus == int(domain.UserStatusEnable) || batchEnableCommand.EnableStatus == int(domain.UserStatusDisable)) {
validation.SetError("CustomValid", "非法启用状态")
}
}
func (batchEnableCommand *BatchEnableCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(batchEnableCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(batchEnableCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package dto
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
"time"
)
type UserBaseDto struct {
// 用户基础数据id
UserBaseId int64 `json:"userBaseId,omitempty"`
// 手机号码
//Account string `json:"phone,omitempty"`
// 最后登录时间
LastLogIn string `json:"lastLogIn"`
// 用户信息 (冗余,数据存在userBase里面)
UserInfo *domain.UserInfo `json:"userInfo,omitempty"`
// 账号状态 1:正常 2.禁用 3:注销
Status int `json:"status,omitempty"`
// 推荐人
Referer string `json:"referer"`
// 关联的用户 (冗余)
// RelatedUsers []int64 `json:"relatedUsers,omitempty"`
// 用户关联的组织
UserOrg []interface{} `json:"userOrg"`
// 创建时间
RegistrationDate string `json:"registrationDate,omitempty"`
}
func (dto *UserBaseDto) LoadDto(userBase *domain.UserBase, relateUsers []*domain.User) error {
dto.UserBaseId = userBase.UserBaseId
//dto.Account = userBase.Account
dto.LastLogIn = ""
dto.UserInfo = userBase.UserInfo
if userBase.Favorite != nil {
if userBase.Favorite.LastLogInAt > 0 {
t := time.Unix(userBase.Favorite.LastLogInAt, 0)
dto.LastLogIn = t.Format("2006-01-02 15:04:05")
}
dto.Referer = userBase.Favorite.Referer
}
dto.Status = userBase.Status
for i := range relateUsers {
dto.UserOrg = append(dto.UserOrg, map[string]interface{}{
"orgId": relateUsers[i].OrganizationId,
"orgName": relateUsers[i].Ext.OrgName,
})
}
dto.RegistrationDate = userBase.CreatedAt.Format("2006-01-02")
return nil
}
... ...
package query
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type ListUserQuery struct {
OperateInfo *domain.OperateInfo `json:"-"`
// 查询偏离量
Offset int `cname:"查询偏离量" json:"offset"`
// 查询限制
Limit int `cname:"查询限制" json:"limit"`
// 用户姓名
UserName string `cname:"用户姓名" json:"userName,omitempty"`
// 在用户列表内
InUserBaseIds []int64 `cname:"用户姓名" json:"inUserBaseIds,omitempty"`
// 所属组织
OrgName string `cname:"所属组织" json:"orgName,omitempty"`
// 关闭查询限制
DisableLimit bool `cname:"关闭查询限制" json:"disableLimit,omitempty"`
// 获取组织
FetchOrgBelong bool `cname:"获取组织" json:"fetchOrgBelong,omitempty"`
}
func (listUserQuery *ListUserQuery) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listUserQuery *ListUserQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listUserQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(listUserQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/userbase/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/userbase/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/userbase/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/utils"
)
type UserBaseService struct {
}
// 返回列表
func (userService *UserBaseService) SearchUser(listUserQuery *query.ListUserQuery) (interface{}, error) {
if err := listUserQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var count int64
var userBases []*domain.UserBase
userBaseRepository, _, _ := factory.FastPgUserBase(transactionContext, 0)
userRepository, _, _ := factory.FastPgUser(transactionContext, 0)
_, users, err := userRepository.Find(map[string]interface{}{
"limit": listUserQuery.Limit,
"offset": listUserQuery.Offset,
"orgName": listUserQuery.OrgName,
"userName": listUserQuery.UserName,
"distinctOnUserBaseId": true,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var result = make([]*dto.UserBaseDto, 0)
if len(users) > 0 {
var userBaseIds []int64
for i := range users {
userBaseIds = append(userBaseIds, users[i].UserBaseId)
}
listUserQuery.InUserBaseIds = userBaseIds
queryOptions := utils.ObjectToMap(listUserQuery)
count, userBases, err = userBaseRepository.Find(queryOptions)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
for i := range userBases {
u := userBases[i]
var relateUsers []*domain.User
if listUserQuery.FetchOrgBelong && len(u.RelatedUsers) > 0 {
for i := range u.RelatedUsers {
relateUser, _ := userRepository.FindOne(map[string]interface{}{"userId": u.RelatedUsers[i]})
if relateUser != nil {
relateUsers = append(relateUsers, relateUser)
}
}
}
userBaseDto := &dto.UserBaseDto{}
userBaseDto.LoadDto(u, relateUsers)
result = append(result, userBaseDto)
}
}
return map[string]interface{}{
"count": count,
"users": result,
}, nil
}
// 批量修改启用状态
func (userService *UserBaseService) BatchEnable(batchEnableCommand *command.BatchEnableCommand) (interface{}, error) {
if err := batchEnableCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
userRepository, _, err := factory.FastPgUserBase(transactionContext, 0)
if err != nil {
return nil, err
}
for i := 0; i < len(batchEnableCommand.UserBaseIds); i++ {
if user, err := userRepository.FindOne(map[string]interface{}{"userBaseId": batchEnableCommand.UserBaseIds[i]}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := user.SetEnableStatus(batchEnableCommand.EnableStatus); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if _, err := userRepository.Save(user); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return struct{}{}, nil
}
func NewUserBaseService(options map[string]interface{}) *UserBaseService {
newUserService := &UserBaseService{}
return newUserService
}
... ...
... ... @@ -275,6 +275,21 @@ func (userBase *UserBase) LastLogIn(t time.Time) error {
return nil
}
func (user *UserBase) SetEnableStatus(status int) error {
userStatus := UserStatus(user.Status)
if userStatus == UserStatusDestroy {
return fmt.Errorf("账号已注销")
}
if user.Status == status {
return nil //fmt.Errorf("重复设置状态")
}
if !(status == int(UserStatusEnable) || status == int(UserStatusDisable)) {
return fmt.Errorf("非法启用状态")
}
user.Status = status
return nil
}
/***** 2.缓存模块 *****/
func (m *UserBase) CacheKeyFunc() string {
... ...
... ... @@ -172,7 +172,10 @@ func (repository *UserBaseRepository) Find(queryOptions map[string]interface{})
var userBaseModels []*models.UserBase
userBases := make([]*domain.UserBase, 0)
query := sqlbuilder.BuildQuery(tx.Model(&userBaseModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOffsetAndLimit(20) //InUserBaseIds
if v, ok := queryOptions["inUserBaseIds"]; ok && len(v.([]int64)) > 0 {
query.Where(`user_base_id in (?)`, pg.In(v))
}
query.SetOrderDirect("user_base_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, userBases, err
... ...
... ... @@ -196,6 +196,11 @@ func (repository *UserRepository) Find(queryOptions map[string]interface{}) (int
var userModels []*models.User
users := make([]*domain.User, 0)
query := sqlbuilder.BuildQuery(tx.Model(&userModels), queryOptions)
if v, ok := queryOptions["distinctOnUserBaseId"]; ok && (v.(bool)) {
query.DistinctOn("user_base_id")
query.Order("user_base_id desc")
}
query.SetWhereByQueryOption("company_id=?", "companyId")
query.SetWhereByQueryOption("organization_id=?", "organizationId")
if v, ok := queryOptions["inOrgIds"]; ok && len(v.([]int64)) > 0 {
... ... @@ -214,6 +219,9 @@ func (repository *UserRepository) Find(queryOptions map[string]interface{}) (int
if v, ok := queryOptions["depName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`ext->>'depName' like '%%%v%%'`, v))
}
if v, ok := queryOptions["orgName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`ext->>'orgName' like '%%%v%%'`, v))
}
if v, ok := queryOptions["userName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`ext->>'userName' like '%%%v%%'`, v))
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/userbase/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/userbase/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/userbase/service"
)
type UserBaseController struct {
beego.BaseController
}
func (controller *UserBaseController) SearchUser() {
userService := service.NewUserBaseService(nil)
listUserQuery := &query.ListUserQuery{}
Must(controller.Unmarshal(listUserQuery))
listUserQuery.OperateInfo = ParseOperateInfo(controller.BaseController)
data, err := userService.SearchUser(listUserQuery)
controller.Response(data, err)
}
func (controller *UserBaseController) BatchEnable() {
userService := service.NewUserBaseService(nil)
batchEnableCommand := &command.BatchEnableCommand{}
controller.Unmarshal(batchEnableCommand)
batchEnableCommand.OperateInfo = ParseOperateInfo(controller.BaseController)
data, err := userService.BatchEnable(batchEnableCommand)
controller.Response(data, err)
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/port/beego/controllers"
)
func init() {
//web.Router("/user/", &controllers.UserController{}, "Post:CreateUser")
//web.Router("/user/:userId", &controllers.UserController{}, "Put:UpdateUser")
//web.Router("/user/:userId", &controllers.UserController{}, "Get:GetUser")
//web.Router("/user/:userId", &controllers.UserController{}, "Delete:RemoveUser")
web.Router("/user-base/search", &controllers.UserBaseController{}, "Post:SearchUser")
//web.Router("/user/:userId/access-menus", &controllers.UserController{}, "Get:GetUserAccessMenus")
//web.Router("/user/:userId/profile", &controllers.UserController{}, "Get:GetUserProfile")
//web.Router("/user/batch-add", &controllers.UserController{}, "Post:BatchAdd")
//web.Router("/user/batch-add2", &controllers.UserController{}, "Post:BatchAdd2")
web.Router("/user-base/batch-enable", &controllers.UserBaseController{}, "Post:BatchEnable")
//web.Router("/user/batch-reset-password", &controllers.UserController{}, "Post:BatchResetPassword")
//web.Router("/user/:userId/base-info", &controllers.UserController{}, "Put:UpdateUsersBase")
//web.Router("/user/cooperator", &controllers.UserController{}, "Post:CreateCooperator")
//web.Router("/user/cooperator/:userId", &controllers.UserController{}, "Put:UpdateCooperator")
}
... ...