作者 yangfu

用户角色修改

@@ -389,6 +389,9 @@ type( @@ -389,6 +389,9 @@ type(
389 } 389 }
390 SystemUserAccountUpdateRequest struct{ 390 SystemUserAccountUpdateRequest struct{
391 Id int64 `path:"id"` 391 Id int64 `path:"id"`
  392 + Name string `json:"name"` // 姓名
  393 + Roles []int64 `json:"roles"` // 权限角色
  394 + Status int `json:"enable"` // 状态 1:启用 2:禁用
392 } 395 }
393 SystemUserAccountUpdateResponse struct{} 396 SystemUserAccountUpdateResponse struct{}
394 397
@@ -2,7 +2,9 @@ package role @@ -2,7 +2,9 @@ package role
2 2
3 import ( 3 import (
4 "context" 4 "context"
  5 + "github.com/samber/lo"
5 "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/domain" 6 "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/domain"
  7 + "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/contextdata"
6 "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/xerr" 8 "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/xerr"
7 9
8 "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/svc" 10 "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/svc"
@@ -27,15 +29,26 @@ func NewSystemGetRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Sys @@ -27,15 +29,26 @@ func NewSystemGetRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Sys
27 29
28 func (l *SystemGetRoleLogic) SystemGetRole(req *types.RoleGetRequest) (resp *types.RoleGetResponse, err error) { 30 func (l *SystemGetRoleLogic) SystemGetRole(req *types.RoleGetRequest) (resp *types.RoleGetResponse, err error) {
29 var ( 31 var (
30 - conn = l.svcCtx.DefaultDBConn()  
31 - role *domain.Role 32 + conn = l.svcCtx.DefaultDBConn()
  33 + role *domain.Role
  34 + users []*domain.User
  35 + userToken = contextdata.GetUserTokenFromCtx(l.ctx)
32 ) 36 )
33 if role, err = l.svcCtx.RoleRepository.FindOne(l.ctx, conn, req.Id); err != nil { 37 if role, err = l.svcCtx.RoleRepository.FindOne(l.ctx, conn, req.Id); err != nil {
34 return nil, xerr.NewErrMsgErr("角色不存在", err) 38 return nil, xerr.NewErrMsgErr("角色不存在", err)
35 } 39 }
  40 + _, users, _ = l.svcCtx.UserRepository.FindByCompanyRoles(l.ctx, conn, userToken.CompanyId, []int64{role.Id}, domain.NewQueryOptions().WithFindOnly())
  41 + typesRole := NewTypesRole(role)
  42 + lo.ForEach(users, func(item *domain.User, index int) {
  43 + typesRole.Users = append(typesRole.Users, types.RoleUser{
  44 + Id: item.Id,
  45 + Name: item.Name,
  46 + })
  47 + })
36 resp = &types.RoleGetResponse{ 48 resp = &types.RoleGetResponse{
37 - Role: NewTypesRole(role), 49 + Role: typesRole,
38 } 50 }
  51 +
39 for _, auth := range domain.Auths { 52 for _, auth := range domain.Auths {
40 resp.AuthList = append(resp.AuthList, types.Auth{ 53 resp.AuthList = append(resp.AuthList, types.Auth{
41 Id: auth.Id, 54 Id: auth.Id,
@@ -92,12 +92,6 @@ func NewTypesRole(item *domain.Role) types.RoleItem { @@ -92,12 +92,6 @@ func NewTypesRole(item *domain.Role) types.RoleItem {
92 role types.RoleItem 92 role types.RoleItem
93 users []types.RoleUser = make([]types.RoleUser, 0) 93 users []types.RoleUser = make([]types.RoleUser, 0)
94 ) 94 )
95 - lo.ForEach(item.Users, func(item domain.User, index int) {  
96 - users = append(users, types.RoleUser{  
97 - Id: item.Id,  
98 - Name: item.Name,  
99 - })  
100 - })  
101 role = types.RoleItem{ 95 role = types.RoleItem{
102 Id: item.Id, 96 Id: item.Id,
103 CompanyId: item.CompanyId, 97 CompanyId: item.CompanyId,
@@ -35,6 +35,7 @@ func (l *SystemSearchRoleLogic) SystemSearchRole(req *types.RoleSearchRequest) ( @@ -35,6 +35,7 @@ func (l *SystemSearchRoleLogic) SystemSearchRole(req *types.RoleSearchRequest) (
35 userToken = contextdata.GetUserTokenFromCtx(l.ctx) 35 userToken = contextdata.GetUserTokenFromCtx(l.ctx)
36 roles []*domain.Role 36 roles []*domain.Role
37 total int64 37 total int64
  38 + users []*domain.User
38 ) 39 )
39 queryOptions := domain.IndexCompanyId(userToken.CompanyId)() 40 queryOptions := domain.IndexCompanyId(userToken.CompanyId)()
40 if req.Page != 0 && req.Size != 0 { 41 if req.Page != 0 && req.Size != 0 {
@@ -57,17 +58,27 @@ func (l *SystemSearchRoleLogic) SystemSearchRole(req *types.RoleSearchRequest) ( @@ -57,17 +58,27 @@ func (l *SystemSearchRoleLogic) SystemSearchRole(req *types.RoleSearchRequest) (
57 }) 58 })
58 return 59 return
59 } 60 }
  61 + roleIds := domain.Values(roles, func(item *domain.Role) int64 {
  62 + return item.Id
  63 + })
  64 + _, users, _ = l.svcCtx.UserRepository.FindByCompanyRoles(l.ctx, conn, userToken.CompanyId, roleIds, domain.NewQueryOptions().WithFindOnly())
60 lo.ForEach(roles, func(item *domain.Role, index int) { 65 lo.ForEach(roles, func(item *domain.Role, index int) {
61 role := NewTypesRole(item) 66 role := NewTypesRole(item)
62 - role.UsersDesc = usersDesc(item) 67 + usersAll := make([]domain.User, 0)
  68 + for _, u := range users {
  69 + if lo.Contains(u.Roles, item.Id) {
  70 + usersAll = append(usersAll, *u)
  71 + }
  72 + }
  73 + role.UsersDesc = usersDesc(usersAll)
63 role.AuthsDesc = authsDesc(item) 74 role.AuthsDesc = authsDesc(item)
64 resp.List = append(resp.List, role) 75 resp.List = append(resp.List, role)
65 }) 76 })
66 return 77 return
67 } 78 }
68 79
69 -func usersDesc(item *domain.Role) string {  
70 - users := lo.Slice(item.Users, 0, 3) 80 +func usersDesc(usersAll []domain.User) string {
  81 + users := lo.Slice(usersAll, 0, 3)
71 var ( 82 var (
72 nameList = make([]string, 0) 83 nameList = make([]string, 0)
73 desc string = " " 84 desc string = " "
@@ -79,7 +90,7 @@ func usersDesc(item *domain.Role) string { @@ -79,7 +90,7 @@ func usersDesc(item *domain.Role) string {
79 return desc 90 return desc
80 } 91 }
81 desc = fmt.Sprintf("%s%s", strings.Join(nameList, "、"), 92 desc = fmt.Sprintf("%s%s", strings.Join(nameList, "、"),
82 - lo.Ternary(len(item.Users) > 3, fmt.Sprintf("...共%d人", len(item.Users)), ""), 93 + lo.Ternary(len(usersAll) > 3, fmt.Sprintf("...共%d人", len(usersAll)), ""),
83 ) 94 )
84 return desc 95 return desc
85 } 96 }
@@ -67,10 +67,20 @@ func (l *SystemUserAccountSaveLogic) SystemUserAccountSave(req *types.SystemUser @@ -67,10 +67,20 @@ func (l *SystemUserAccountSaveLogic) SystemUserAccountSave(req *types.SystemUser
67 AuditStatus: domain.UserAuditStatusPassed, 67 AuditStatus: domain.UserAuditStatusPassed,
68 } 68 }
69 user.WithName(name) 69 user.WithName(name)
  70 + if user, err = l.svcCtx.UserRepository.Insert(ctx, conn, user); err != nil {
  71 + return err
  72 + }
70 for _, roleId := range req.Roles { 73 for _, roleId := range req.Roles {
  74 + if _, err = l.svcCtx.UserRoleRepository.Insert(l.ctx, conn, &domain.UserRole{
  75 + CompanyId: user.CompanyId,
  76 + UserId: user.Id,
  77 + RoleId: roleId,
  78 + }); err != nil {
  79 + return err
  80 + }
71 user.AddRole(roleId) 81 user.AddRole(roleId)
72 } 82 }
73 - if user, err = l.svcCtx.UserRepository.Insert(ctx, conn, user); err != nil { 83 + if user, err = l.svcCtx.UserRepository.UpdateWithVersion(ctx, conn, user); err != nil {
74 return err 84 return err
75 } 85 }
76 return nil 86 return nil
@@ -2,6 +2,11 @@ package user @@ -2,6 +2,11 @@ package user
2 2
3 import ( 3 import (
4 "context" 4 "context"
  5 + "github.com/samber/lo"
  6 + "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/db/transaction"
  7 + "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/domain"
  8 + "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/contextdata"
  9 + "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/xerr"
5 10
6 "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/svc" 11 "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/svc"
7 "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/types" 12 "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/types"
@@ -24,7 +29,49 @@ func NewSystemUserAccountUpdateLogic(ctx context.Context, svcCtx *svc.ServiceCon @@ -24,7 +29,49 @@ func NewSystemUserAccountUpdateLogic(ctx context.Context, svcCtx *svc.ServiceCon
24 } 29 }
25 30
26 func (l *SystemUserAccountUpdateLogic) SystemUserAccountUpdate(req *types.SystemUserAccountUpdateRequest) (resp *types.SystemUserAccountUpdateResponse, err error) { 31 func (l *SystemUserAccountUpdateLogic) SystemUserAccountUpdate(req *types.SystemUserAccountUpdateRequest) (resp *types.SystemUserAccountUpdateResponse, err error) {
27 - // todo: add your logic here and delete this line  
28 - 32 + var (
  33 + userToken = contextdata.GetUserTokenFromCtx(l.ctx)
  34 + user *domain.User
  35 + conn = l.svcCtx.DefaultDBConn()
  36 + )
  37 + if user, err = l.svcCtx.UserRepository.FindOne(l.ctx, conn, req.Id); err != nil {
  38 + return nil, xerr.NewErrMsgErr("用户不存在", err)
  39 + }
  40 + if user.CompanyId != userToken.CompanyId {
  41 + return nil, xerr.NewErrMsgErr("无权限更改", err)
  42 + }
  43 + if req.Name != user.Name {
  44 + user.WithName(req.Name)
  45 + }
  46 + removeList, addList := lo.Difference(user.Roles, req.Roles)
  47 + if len(removeList) > 0 || len(addList) > 0 {
  48 + user.Roles = req.Roles
  49 + }
  50 + user.Enable = req.Status
  51 + if err = transaction.UseTrans(l.ctx, l.svcCtx.DB, func(ctx context.Context, conn transaction.Conn) error {
  52 + if user, err = l.svcCtx.UserRepository.UpdateWithVersion(ctx, conn, user); err != nil {
  53 + return err
  54 + }
  55 + if len(removeList) > 0 || len(addList) > 0 {
  56 + if err = l.svcCtx.UserRoleRepository.DeleteByUser(ctx, conn, user.Id); err != nil {
  57 + return err
  58 + }
  59 + user.Roles = []int64{}
  60 + for _, roleId := range req.Roles {
  61 + if _, err = l.svcCtx.UserRoleRepository.Insert(l.ctx, conn, &domain.UserRole{
  62 + CompanyId: user.CompanyId,
  63 + UserId: user.Id,
  64 + RoleId: roleId,
  65 + }); err != nil {
  66 + return err
  67 + }
  68 + user.AddRole(roleId)
  69 + }
  70 + }
  71 + return nil
  72 + }, true); err != nil {
  73 + return nil, xerr.NewErrMsgErr("更新用户信息失败", err)
  74 + }
  75 + resp = &types.SystemUserAccountUpdateResponse{}
29 return 76 return
30 } 77 }
@@ -39,6 +39,7 @@ type ServiceContext struct { @@ -39,6 +39,7 @@ type ServiceContext struct {
39 UserLoveFlagRepository domain.UserLoveFlagRepository 39 UserLoveFlagRepository domain.UserLoveFlagRepository
40 UserReadArticleRepository domain.UserReadArticleRepository 40 UserReadArticleRepository domain.UserReadArticleRepository
41 UserRepository domain.UserRepository 41 UserRepository domain.UserRepository
  42 + UserRoleRepository domain.UserRoleRepository
42 43
43 ApiAuthService authlib.ApiAuthService 44 ApiAuthService authlib.ApiAuthService
44 SmsService smslib.SMSService 45 SmsService smslib.SMSService
@@ -80,6 +81,7 @@ func NewServiceContext(c config.Config) *ServiceContext { @@ -80,6 +81,7 @@ func NewServiceContext(c config.Config) *ServiceContext {
80 UserRepository: repository.NewUserRepository(cache.NewCachedRepository(mlCache)), 81 UserRepository: repository.NewUserRepository(cache.NewCachedRepository(mlCache)),
81 UserReadArticleRepository: repository.NewUserReadArticleRepository(cache.NewCachedRepository(mlCache)), 82 UserReadArticleRepository: repository.NewUserReadArticleRepository(cache.NewCachedRepository(mlCache)),
82 ArticleTagRepository: repository.NewArticleTagRepository(cache.NewCachedRepository(mlCache)), 83 ArticleTagRepository: repository.NewArticleTagRepository(cache.NewCachedRepository(mlCache)),
  84 + UserRoleRepository: repository.NewUserRoleRepository(cache.NewCachedRepository(mlCache)),
83 } 85 }
84 } 86 }
85 87
@@ -689,7 +689,10 @@ type SystemUserAccountEnableResponse struct { @@ -689,7 +689,10 @@ type SystemUserAccountEnableResponse struct {
689 } 689 }
690 690
691 type SystemUserAccountUpdateRequest struct { 691 type SystemUserAccountUpdateRequest struct {
692 - Id int64 `path:"id"` 692 + Id int64 `path:"id"`
  693 + Name string `json:"name"` // 姓名
  694 + Roles []int64 `json:"roles"` // 权限角色
  695 + Status int `json:"enable"` // 状态 1:启用 2:禁用
693 } 696 }
694 697
695 type SystemUserAccountUpdateResponse struct { 698 type SystemUserAccountUpdateResponse struct {
  1 +
  2 +syntax = "v1"
  3 +
  4 +info(
  5 + title: "xx实例"
  6 + desc: "xx实例"
  7 + author: "author"
  8 + email: "email"
  9 + version: "v1"
  10 +)
  11 +
  12 +@server(
  13 + prefix: user_role/v1
  14 + group: user_role
  15 + jwt: JwtAuth
  16 +)
  17 +service Core {
  18 + @handler getUserRole
  19 + post /user_role/:id (UserRoleGetRequest) returns (UserRoleGetResponse)
  20 + @handler saveUserRole
  21 + post /user_role (UserRoleSaveRequest) returns (UserRoleSaveResponse)
  22 + @handler deleteUserRole
  23 + delete /user_role/:id (UserRoleDeleteRequest) returns (UserRoleDeleteResponse)
  24 + @handler updateUserRole
  25 + put /user_role/:id (UserRoleUpdateRequest) returns (UserRoleUpdateResponse)
  26 + @handler searchUserRole
  27 + post /user_role/search (UserRoleSearchRequest) returns (UserRoleSearchResponse)
  28 +}
  29 +
  30 +type (
  31 + UserRoleGetRequest {
  32 + Id int64 `path:"id"`
  33 + }
  34 + UserRoleGetResponse struct{
  35 + UserRole UserRoleItem `json:"user_role"`
  36 + }
  37 +
  38 + UserRoleSaveRequest struct{
  39 + UserRole UserRoleItem `json:"user_role"`
  40 + }
  41 + UserRoleSaveResponse struct{}
  42 +
  43 + UserRoleDeleteRequest struct{
  44 + Id int64 `path:"id"`
  45 + }
  46 + UserRoleDeleteResponse struct{}
  47 +
  48 + UserRoleUpdateRequest struct{
  49 + Id int64 `path:"id"`
  50 + UserRole UserRoleItem `json:"user_role"`
  51 + }
  52 + UserRoleUpdateResponse struct{}
  53 +
  54 + UserRoleSearchRequest struct{
  55 + Page int `json:"page"`
  56 + Size int `json:"size"`
  57 + }
  58 + UserRoleSearchResponse{
  59 + List []UserRoleItem `json:"list"`
  60 + Total int64 `json:"total"`
  61 + }
  62 + UserRoleItem struct{
  63 +
  64 + }
  65 +)
  1 +
  2 +syntax = "proto3";
  3 +
  4 +option go_package ="./pb";
  5 +
  6 +package pb;
  7 +
  8 +message UserRoleGetReq {
  9 + int64 Id = 1;
  10 +}
  11 +message UserRoleGetResp{
  12 + UserRoleItem User = 1;
  13 +}
  14 +
  15 +message UserRoleSaveReq {
  16 +
  17 +}
  18 +message UserRoleSaveResp{
  19 +
  20 +}
  21 +
  22 +message UserRoleDeleteReq {
  23 + int64 Id = 1;
  24 +}
  25 +message UserRoleDeleteResp{
  26 +
  27 +}
  28 +
  29 +message UserRoleUpdateReq {
  30 + int64 Id = 1;
  31 +}
  32 +message UserRoleUpdateResp{
  33 +
  34 +}
  35 +
  36 +message UserRoleSearchReq {
  37 + int64 PageNumber = 1;
  38 + int64 PageSize = 2;
  39 +}
  40 +message UserRoleSearchResp{
  41 + repeated UserRoleItem List =1;
  42 + int64 Total =2;
  43 +}
  44 +message UserRoleItem {
  45 +
  46 +}
  47 +
  48 +service UserRoleService {
  49 + rpc UserRoleGet(UserRoleGetReq) returns(UserRoleGetResp);
  50 + rpc UserRoleSave(UserRoleSaveReq) returns(UserRoleSaveResp);
  51 + rpc UserRoleDelete(UserRoleDeleteReq) returns(UserRoleDeleteResp);
  52 + rpc UserRoleUpdate(UserRoleUpdateReq) returns(UserRoleUpdateResp);
  53 + rpc UserRoleSearch(UserRoleSearchReq) returns(UserRoleSearchResp);
  54 +}
@@ -16,6 +16,7 @@ func Migrate(db *gorm.DB) { @@ -16,6 +16,7 @@ func Migrate(db *gorm.DB) {
16 &models.UserLoveFlag{}, 16 &models.UserLoveFlag{},
17 &models.UserReadArticle{}, 17 &models.UserReadArticle{},
18 &models.User{}, 18 &models.User{},
  19 + &models.UserRole{},
19 &models.Role{}, 20 &models.Role{},
20 &models.Company{}, 21 &models.Company{},
21 &models.UserFollow{}, 22 &models.UserFollow{},
  1 +package models
  2 +
  3 +import (
  4 + "gorm.io/gorm"
  5 +)
  6 +
  7 +type UserRole struct {
  8 + Id int64 // 唯一标识
  9 + CompanyId int64 // 公司ID
  10 + UserId int64
  11 + RoleId int64
  12 + CreatedAt int64
  13 + UpdatedAt int64
  14 + DeletedAt int64
  15 + Version int
  16 +}
  17 +
  18 +func (m *UserRole) TableName() string {
  19 + return "user_role"
  20 +}
  21 +
  22 +func (m *UserRole) BeforeCreate(tx *gorm.DB) (err error) {
  23 + // m.CreatedAt = time.Now().Unix()
  24 + // m.UpdatedAt = time.Now().Unix()
  25 + return
  26 +}
  27 +
  28 +func (m *UserRole) BeforeUpdate(tx *gorm.DB) (err error) {
  29 + // m.UpdatedAt = time.Now().Unix()
  30 + return
  31 +}
  32 +
  33 +func (m *UserRole) CacheKeyFunc() string {
  34 + return ""
  35 +}
  36 +
  37 +func (m *UserRole) CacheKeyFuncByObject(obj interface{}) string {
  38 + if v, ok := obj.(*UserRole); ok {
  39 + return v.CacheKeyFunc()
  40 + }
  41 + return ""
  42 +}
  43 +
  44 +func (m *UserRole) CachePrimaryKeyFunc() string {
  45 + return ""
  46 +}
@@ -242,6 +242,39 @@ func (repository *UserRepository) FindDepartmentUsers(ctx context.Context, conn @@ -242,6 +242,39 @@ func (repository *UserRepository) FindDepartmentUsers(ctx context.Context, conn
242 return total, dms, nil 242 return total, dms, nil
243 } 243 }
244 244
  245 +func (repository *UserRepository) FindByCompanyRoles(ctx context.Context, conn transaction.Conn, companyId int64, roles []int64, queryOptions map[string]interface{}) (int64, []*domain.User, error) {
  246 + var (
  247 + tx = conn.DB()
  248 + ms []*models.User
  249 + dms = make([]*domain.User, 0)
  250 + total int64
  251 + )
  252 + queryFunc := func() (interface{}, error) {
  253 + tx = tx.Model(&ms).Order("id asc")
  254 + tx.Select("id", "name", "roles")
  255 + tx.Where("company_id = ?", companyId)
  256 + tx.Where("flag = ?", domain.UserAdmin)
  257 + tx.Where("id in (select user_id from user_role where role_id in(?)) ", roles)
  258 + if total, tx = transaction.PaginationAndCount(ctx, tx, queryOptions, &ms); tx.Error != nil {
  259 + return dms, tx.Error
  260 + }
  261 + return dms, nil
  262 + }
  263 +
  264 + if _, err := repository.Query(queryFunc); err != nil {
  265 + return 0, nil, err
  266 + }
  267 +
  268 + for _, item := range ms {
  269 + if dm, err := repository.ModelToDomainModel(item); err != nil {
  270 + return 0, dms, err
  271 + } else {
  272 + dms = append(dms, dm)
  273 + }
  274 + }
  275 + return total, dms, nil
  276 +}
  277 +
245 func (repository *UserRepository) FindCompanyPositions(ctx context.Context, conn transaction.Conn, companyId int64, queryOptions map[string]interface{}) (int64, []*domain.User, error) { 278 func (repository *UserRepository) FindCompanyPositions(ctx context.Context, conn transaction.Conn, companyId int64, queryOptions map[string]interface{}) (int64, []*domain.User, error) {
246 var ( 279 var (
247 tx = conn.DB() 280 tx = conn.DB()
  1 +package repository
  2 +
  3 +import (
  4 + "context"
  5 + "github.com/jinzhu/copier"
  6 + "github.com/pkg/errors"
  7 + "github.com/tiptok/gocomm/pkg/cache"
  8 + "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/db/models"
  9 + "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/db/transaction"
  10 + "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/domain"
  11 + "gorm.io/gorm"
  12 +)
  13 +
  14 +type UserRoleRepository struct {
  15 + *cache.CachedRepository
  16 +}
  17 +
  18 +func (repository *UserRoleRepository) Insert(ctx context.Context, conn transaction.Conn, dm *domain.UserRole) (*domain.UserRole, error) {
  19 + var (
  20 + err error
  21 + m = &models.UserRole{}
  22 + tx = conn.DB()
  23 + )
  24 + if m, err = repository.DomainModelToModel(dm); err != nil {
  25 + return nil, err
  26 + }
  27 + if tx = tx.Model(m).Save(m); tx.Error != nil {
  28 + return nil, tx.Error
  29 + }
  30 + dm.Id = m.Id
  31 + return repository.ModelToDomainModel(m)
  32 +
  33 +}
  34 +
  35 +func (repository *UserRoleRepository) Update(ctx context.Context, conn transaction.Conn, dm *domain.UserRole) (*domain.UserRole, error) {
  36 + var (
  37 + err error
  38 + m *models.UserRole
  39 + tx = conn.DB()
  40 + )
  41 + if m, err = repository.DomainModelToModel(dm); err != nil {
  42 + return nil, err
  43 + }
  44 + queryFunc := func() (interface{}, error) {
  45 + tx = tx.Model(m).Updates(m)
  46 + return nil, tx.Error
  47 + }
  48 + if _, err = repository.Query(queryFunc, m.CacheKeyFunc()); err != nil {
  49 + return nil, err
  50 + }
  51 + return repository.ModelToDomainModel(m)
  52 +}
  53 +
  54 +func (repository *UserRoleRepository) UpdateWithVersion(ctx context.Context, transaction transaction.Conn, dm *domain.UserRole) (*domain.UserRole, error) {
  55 + var (
  56 + err error
  57 + m *models.UserRole
  58 + tx = transaction.DB()
  59 + )
  60 + if m, err = repository.DomainModelToModel(dm); err != nil {
  61 + return nil, err
  62 + }
  63 + oldVersion := dm.Version
  64 + m.Version += 1
  65 + queryFunc := func() (interface{}, error) {
  66 + tx = tx.Model(m).Select("*").Where("id = ?", m.Id).Where("version = ?", oldVersion).Updates(m)
  67 + if tx.RowsAffected == 0 {
  68 + return nil, domain.ErrUpdateFail
  69 + }
  70 + return nil, tx.Error
  71 + }
  72 + if _, err = repository.Query(queryFunc, m.CacheKeyFunc()); err != nil {
  73 + return nil, err
  74 + }
  75 + return repository.ModelToDomainModel(m)
  76 +}
  77 +
  78 +func (repository *UserRoleRepository) Delete(ctx context.Context, conn transaction.Conn, dm *domain.UserRole) (*domain.UserRole, error) {
  79 + var (
  80 + tx = conn.DB()
  81 + m = &models.UserRole{Id: dm.Identify().(int64)}
  82 + )
  83 + queryFunc := func() (interface{}, error) {
  84 + tx = tx.Where("id = ?", m.Id).Delete(m)
  85 + return m, tx.Error
  86 + }
  87 + if _, err := repository.Query(queryFunc, m.CacheKeyFunc()); err != nil {
  88 + return dm, err
  89 + }
  90 + return repository.ModelToDomainModel(m)
  91 +}
  92 +
  93 +func (repository *UserRoleRepository) DeleteByUser(ctx context.Context, conn transaction.Conn, userId int64) error {
  94 + var (
  95 + tx = conn.DB()
  96 + m = &models.UserRole{}
  97 + )
  98 + queryFunc := func() (interface{}, error) {
  99 + tx = tx.Where("user_id = ?", userId).Delete(m)
  100 + return m, tx.Error
  101 + }
  102 + if _, err := repository.Query(queryFunc, m.CacheKeyFunc()); err != nil {
  103 + return err
  104 + }
  105 + return nil
  106 +}
  107 +
  108 +func (repository *UserRoleRepository) FindOne(ctx context.Context, conn transaction.Conn, id int64) (*domain.UserRole, error) {
  109 + var (
  110 + err error
  111 + tx = conn.DB()
  112 + m = new(models.UserRole)
  113 + )
  114 + queryFunc := func() (interface{}, error) {
  115 + tx = tx.Model(m).Where("id = ?", id).First(m)
  116 + if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
  117 + return nil, domain.ErrNotFound
  118 + }
  119 + return m, tx.Error
  120 + }
  121 + cacheModel := new(models.UserRole)
  122 + cacheModel.Id = id
  123 + if err = repository.QueryCache(cacheModel.CacheKeyFunc, m, queryFunc); err != nil {
  124 + return nil, err
  125 + }
  126 + return repository.ModelToDomainModel(m)
  127 +}
  128 +
  129 +func (repository *UserRoleRepository) Find(ctx context.Context, conn transaction.Conn, queryOptions map[string]interface{}) (int64, []*domain.UserRole, error) {
  130 + var (
  131 + tx = conn.DB()
  132 + ms []*models.UserRole
  133 + dms = make([]*domain.UserRole, 0)
  134 + total int64
  135 + )
  136 + queryFunc := func() (interface{}, error) {
  137 + tx = tx.Model(&ms).Order("id desc")
  138 + if total, tx = transaction.PaginationAndCount(ctx, tx, queryOptions, &ms); tx.Error != nil {
  139 + return dms, tx.Error
  140 + }
  141 + return dms, nil
  142 + }
  143 +
  144 + if _, err := repository.Query(queryFunc); err != nil {
  145 + return 0, nil, err
  146 + }
  147 +
  148 + for _, item := range ms {
  149 + if dm, err := repository.ModelToDomainModel(item); err != nil {
  150 + return 0, dms, err
  151 + } else {
  152 + dms = append(dms, dm)
  153 + }
  154 + }
  155 + return total, dms, nil
  156 +}
  157 +
  158 +func (repository *UserRoleRepository) ModelToDomainModel(from *models.UserRole) (*domain.UserRole, error) {
  159 + to := &domain.UserRole{}
  160 + err := copier.Copy(to, from)
  161 + return to, err
  162 +}
  163 +
  164 +func (repository *UserRoleRepository) DomainModelToModel(from *domain.UserRole) (*models.UserRole, error) {
  165 + to := &models.UserRole{}
  166 + err := copier.Copy(to, from)
  167 + return to, err
  168 +}
  169 +
  170 +func NewUserRoleRepository(cache *cache.CachedRepository) domain.UserRoleRepository {
  171 + return &UserRoleRepository{CachedRepository: cache}
  172 +}
@@ -39,6 +39,7 @@ type UserRepository interface { @@ -39,6 +39,7 @@ type UserRepository interface {
39 FindOne(ctx context.Context, conn transaction.Conn, id int64) (*User, error) 39 FindOne(ctx context.Context, conn transaction.Conn, id int64) (*User, error)
40 FindOneByCompanyIdAndPhone(ctx context.Context, conn transaction.Conn, companyId int64, phone string, status []int) (*User, error) 40 FindOneByCompanyIdAndPhone(ctx context.Context, conn transaction.Conn, companyId int64, phone string, status []int) (*User, error)
41 Find(ctx context.Context, conn transaction.Conn, queryOptions map[string]interface{}) (int64, []*User, error) 41 Find(ctx context.Context, conn transaction.Conn, queryOptions map[string]interface{}) (int64, []*User, error)
  42 + FindByCompanyRoles(ctx context.Context, conn transaction.Conn, companyId int64, roles []int64, queryOptions map[string]interface{}) (int64, []*User, error)
42 FindDepartmentUsers(ctx context.Context, conn transaction.Conn, companyId int64, queryOptions map[string]interface{}) (int64, []*User, error) 43 FindDepartmentUsers(ctx context.Context, conn transaction.Conn, companyId int64, queryOptions map[string]interface{}) (int64, []*User, error)
43 FindCompanyPositions(ctx context.Context, conn transaction.Conn, companyId int64, queryOptions map[string]interface{}) (int64, []*User, error) 44 FindCompanyPositions(ctx context.Context, conn transaction.Conn, companyId int64, queryOptions map[string]interface{}) (int64, []*User, error)
44 } 45 }
  1 +package domain
  2 +
  3 +import (
  4 + "context"
  5 + "gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/db/transaction"
  6 +)
  7 +
  8 +type UserRole struct {
  9 + Id int64 // 唯一标识
  10 + CompanyId int64 // 公司ID
  11 + UserId int64
  12 + RoleId int64
  13 + CreatedAt int64
  14 + UpdatedAt int64
  15 + DeletedAt int64
  16 + Version int
  17 +}
  18 +
  19 +type UserRoleRepository interface {
  20 + Insert(ctx context.Context, conn transaction.Conn, dm *UserRole) (*UserRole, error)
  21 + Update(ctx context.Context, conn transaction.Conn, dm *UserRole) (*UserRole, error)
  22 + UpdateWithVersion(ctx context.Context, conn transaction.Conn, dm *UserRole) (*UserRole, error)
  23 + Delete(ctx context.Context, conn transaction.Conn, dm *UserRole) (*UserRole, error)
  24 + DeleteByUser(ctx context.Context, conn transaction.Conn, userId int64) error
  25 + FindOne(ctx context.Context, conn transaction.Conn, id int64) (*UserRole, error)
  26 + Find(ctx context.Context, conn transaction.Conn, queryOptions map[string]interface{}) (int64, []*UserRole, error)
  27 +}
  28 +
  29 +func (m *UserRole) Identify() interface{} {
  30 + if m.Id == 0 {
  31 + return nil
  32 + }
  33 + return m.Id
  34 +}
1 -CREATE TABLE `comment` (  
2 - `id` int(0) NOT NULL COMMENT '唯一标识',  
3 - PRIMARY KEY (`id`) USING BTREE  
4 -) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;  
5 -  
6 CREATE TABLE `department` ( 1 CREATE TABLE `department` (
7 `id` int(0) NOT NULL COMMENT '唯一标识', 2 `id` int(0) NOT NULL COMMENT '唯一标识',
8 PRIMARY KEY (`id`) USING BTREE 3 PRIMARY KEY (`id`) USING BTREE
@@ -18,6 +13,11 @@ CREATE TABLE `user` ( @@ -18,6 +13,11 @@ CREATE TABLE `user` (
18 PRIMARY KEY (`id`) USING BTREE 13 PRIMARY KEY (`id`) USING BTREE
19 ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; 14 ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
20 15
  16 +CREATE TABLE `user_role` (
  17 + `id` int(0) NOT NULL COMMENT '唯一标识',
  18 + PRIMARY KEY (`id`) USING BTREE
  19 +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
  20 +
21 CREATE TABLE `company` ( 21 CREATE TABLE `company` (
22 `id` int(0) NOT NULL COMMENT '唯一标识', 22 `id` int(0) NOT NULL COMMENT '唯一标识',
23 PRIMARY KEY (`id`) USING BTREE 23 PRIMARY KEY (`id`) USING BTREE