作者 郑周

1.增加角色模型及功能

2.增加角色和用户关系模型及功能
... ... @@ -5,6 +5,7 @@ go 1.16
require (
github.com/Shopify/sarama v1.25.0
github.com/beego/beego/v2 v2.0.5
github.com/bwmarrin/snowflake v0.3.0
github.com/go-pg/pg/v10 v10.10.7
github.com/linmadan/egglib-go v0.0.0-20210827085852-177fa745932d
)
... ...
... ... @@ -6,12 +6,33 @@ import (
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
pgDB "gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/pg"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/repository"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/utils"
)
func CreateTransactionContext(options map[string]interface{}) (application.TransactionContext, error) {
return pg.NewPGTransactionContext(pgDB.DB), nil
}
// StartTransaction 事务创建
func StartTransaction() (application.TransactionContext, error) {
transactionContext, err := 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())
}
return transactionContext, nil
}
// ValidateStartTransaction 事务创建并校验入参
func ValidateStartTransaction(in interface{}) (application.TransactionContext, error) {
if err := utils.ValidateCommand(in); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
return StartTransaction()
}
func CreateCompanyRepository(options map[string]interface{}) domain.CompanyRepository {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
... ... @@ -35,3 +56,19 @@ func CreateDepartmentRepository(options map[string]interface{}) domain.Departmen
}
return repository.NewDepartmentRepository(transactionContext)
}
func CreateRoleRepository(options map[string]interface{}) domain.RoleRepository {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewRoleRepository(transactionContext)
}
func CreateRoleUserRepository(options map[string]interface{}) domain.RoleUserRepository {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewRoleUserRepository(transactionContext)
}
... ...
package adapter
import (
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
)
type RoleContainUser struct {
RoleId int64 `json:"roleId,string"`
UserId int64 `json:"userId,string"`
UserName string `json:"userName"`
UserEmail string `json:"userEmail"`
}
type RoleUserAdapter struct {
domain.Role
Users []*RoleContainUser `json:"users"`
}
... ...
package command
import "github.com/beego/beego/v2/core/validation"
type CreateRoleCommand struct {
CompanyId int64 `cname:"公司ID" json:"companyId"`
Name string `cname:"角色名称" json:"name" valid:"Required"`
Description string `cname:"角色描述" json:"description"`
}
func (in *CreateRoleCommand) Valid(validation *validation.Validation) {
if in.CompanyId == 0 {
validation.SetError("companyId", "公司ID无效")
return
}
if len(in.Name) > 30 {
validation.SetError("name", "角色名称最大长度30个字符")
return
}
}
... ...
package command
import "github.com/beego/beego/v2/core/validation"
type DeleteRoleCommand struct {
CompanyId int64 `cname:"公司ID" json:"companyId"`
Id int64 `cname:"角色ID" json:"id,string" valid:"Required"`
}
func (in *DeleteRoleCommand) Valid(validation *validation.Validation) {
if in.CompanyId == 0 {
validation.SetError("companyId", "公司ID无效")
return
}
}
... ...
package command
import "github.com/beego/beego/v2/core/validation"
// QueryRoleUserCommand 查询角色列表(关联用户)
type QueryRoleUserCommand struct {
CompanyId int64 `cname:"公司ID" json:"companyId"`
PageNumber int `cname:"分页页码" json:"pageNumber" valid:"Required"`
PageSize int `cname:"分页数量" json:"pageSize" valid:"Required"`
}
func (in *QueryRoleUserCommand) Valid(validation *validation.Validation) {
if in.CompanyId == 0 {
validation.SetError("companyId", "公司ID无效")
return
}
}
... ...
package command
import "github.com/beego/beego/v2/core/validation"
type UpdateRoleCommand struct {
CompanyId int64 `cname:"公司ID" json:"companyId"`
Id int64 `cname:"角色ID" json:"id,string" valid:"Required"`
Name string `cname:"角色名称" json:"name" valid:"Required"`
Description string `cname:"角色描述" json:"description"`
}
func (in *UpdateRoleCommand) Valid(validation *validation.Validation) {
if in.CompanyId == 0 {
validation.SetError("companyId", "公司ID无效")
}
if len(in.Name) > 30 {
validation.SetError("name", "角色名称最大长度30个字符")
return
}
}
... ...
package command
import "github.com/beego/beego/v2/core/validation"
// UserRoleCreateCommand 用户加入到该角色中
type UserRoleCreateCommand struct {
CompanyId int64 `cname:"公司ID" json:"companyId"`
RoleId int64 `cname:"角色ID" json:"roleId,string" valid:"Required"`
UserIds []string `cname:"用户ID" json:"userIds"`
}
func (in *UserRoleCreateCommand) Valid(validation *validation.Validation) {
if in.CompanyId == 0 {
validation.SetError("companyId", "公司ID无效")
return
}
if len(in.UserIds) == 0 {
validation.SetError("userIds", "添加的用户不存在")
return
}
}
... ...
package command
import "github.com/beego/beego/v2/core/validation"
// UserRoleDeleteCommand 角色中移除用户
type UserRoleDeleteCommand struct {
CompanyId int64 `cname:"公司ID" json:"companyId"`
RoleId int64 `cname:"角色ID" json:"roleId,string" valid:"Required"`
UserId int64 `cname:"用户ID" json:"userId,string" valid:"Required"`
}
func (in *UserRoleDeleteCommand) Valid(validation *validation.Validation) {
if in.CompanyId == 0 {
validation.SetError("companyId", "公司ID无效")
return
}
}
... ...
package command
import "github.com/beego/beego/v2/core/validation"
// UserRoleQueryCommand 角色中的用户
type UserRoleQueryCommand struct {
CompanyId int64 `cname:"公司ID" json:"companyId"`
RoleId int64 `cname:"角色ID" json:"roleId,string" valid:"Required"`
PageNumber int64 `cname:"分页页码" json:"pageNumber"`
PageSize int64 `cname:"分页数量" json:"pageSize"`
}
func (in *UserRoleQueryCommand) Valid(validation *validation.Validation) {
if in.CompanyId == 0 {
validation.SetError("companyId", "公司ID无效")
return
}
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/role/adapter"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/role/command"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
)
type RoleService struct {
}
func NewRoleService() *RoleService {
newRoleService := &RoleService{}
return newRoleService
}
// Create 创建
func (rs *RoleService) Create(in *command.CreateRoleCommand) (interface{}, error) {
transactionContext, err := factory.ValidateStartTransaction(in)
if err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
roleRepository := factory.CreateRoleRepository(map[string]interface{}{"transactionContext": transactionContext})
// 检测名称重复
count, err := roleRepository.Count(map[string]interface{}{"name": in.Name, "companyId": in.CompanyId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if count > 0 {
return nil, application.ThrowError(application.BUSINESS_ERROR, "角色名称已存在")
}
newRole := &domain.Role{
Id: 0,
Name: in.Name,
Type: domain.RoleTypeCommon,
Description: in.Description,
CompanyId: in.CompanyId,
}
role, err := roleRepository.Insert(newRole)
if 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 role, nil
}
func (rs *RoleService) Update(in *command.UpdateRoleCommand) (interface{}, error) {
transactionContext, err := factory.ValidateStartTransaction(in)
if err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
roleRepository := factory.CreateRoleRepository(map[string]interface{}{"transactionContext": transactionContext})
// 检测名称重复(排除自己)
count, err := roleRepository.Count(map[string]interface{}{"name": in.Name, "companyId": in.CompanyId, "notId": in.Id})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if count > 0 {
return nil, application.ThrowError(application.BUSINESS_ERROR, "角色名称已存在")
}
role, err := roleRepository.FindOne(map[string]interface{}{"id": in.Id})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
role.Name = in.Name
role.Name = in.Description
role, err = roleRepository.Insert(role)
if 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 role, nil
}
func (rs *RoleService) Remove(in *command.DeleteRoleCommand) (interface{}, error) {
transactionContext, err := factory.ValidateStartTransaction(in)
if err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
roleRepository := factory.CreateRoleRepository(map[string]interface{}{"transactionContext": transactionContext})
roleUserRepository := factory.CreateRoleUserRepository(map[string]interface{}{"transactionContext": transactionContext})
role, err := roleRepository.FindOne(map[string]interface{}{"id": in.Id})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if _, err := roleRepository.Remove(role); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
// 获取角色所有关联的用户,并删除
_, roleUsers, err := roleUserRepository.Find(map[string]interface{}{"roleId": in.Id, "companyId": in.CompanyId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
ids := make([]int64, 0)
for i := range roleUsers {
ids = append(ids, roleUsers[i].Id)
}
if len(ids) > 0 {
err := roleUserRepository.BatchDeleteById(ids)
if 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 role, nil
}
func (rs *RoleService) ListForUser(in *command.QueryRoleUserCommand) (interface{}, error) {
transactionContext, err := factory.StartTransaction()
if err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
roleRepository := factory.CreateRoleRepository(map[string]interface{}{"transactionContext": transactionContext})
ruRepository := factory.CreateRoleUserRepository(map[string]interface{}{"transactionContext": transactionContext})
in.PageNumber = 1
in.PageSize = 9999999
_, roles, err := roleRepository.Find(tool_funs.SimpleStructToMap(in))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if len(roles) == 0 {
return nil, application.ThrowError(application.BUSINESS_ERROR, "未找到角色数据")
}
adapterList := make([]*adapter.RoleUserAdapter, 0)
for i := range roles {
v := roles[i]
tempList, err := ruRepository.FindAllContainUser(1, 10, in.CompanyId, v.Id)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
roleUser := &adapter.RoleUserAdapter{}
roleUser.Id = v.Id
roleUser.Name = v.Name
roleUser.Type = v.Type
roleUser.Description = v.Description
roleUser.CompanyId = v.CompanyId
roleUser.Users = tempList
adapterList = append(adapterList, roleUser)
}
return map[string]interface{}{"list": adapterList}, nil
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/role/command"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
"strconv"
)
type RoleUserService struct {
}
func NewRoleUserService() *RoleUserService {
newRoleUserService := &RoleUserService{}
return newRoleUserService
}
// Create 创建
func (rs *RoleUserService) Create(in *command.UserRoleCreateCommand) (interface{}, error) {
transactionContext, err := factory.ValidateStartTransaction(in)
if err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
roleUserRepository := factory.CreateRoleUserRepository(map[string]interface{}{"transactionContext": transactionContext})
// 检测已存在的关联用户
_, rus, err := roleUserRepository.Find(map[string]interface{}{"roleId": in.RoleId, "companyId": in.CompanyId, "userIds": in.UserIds, "limit": 9999999})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
existUserIds := make(map[int64]int64)
for i := range rus {
existUserIds[rus[i].UserId] = rus[i].UserId
}
for i := range in.UserIds {
int64Num, _ := strconv.ParseInt(in.UserIds[i], 10, 64)
// 不存在关联关系时,新增数据
if _, ok := existUserIds[int64Num]; !ok {
newRoleUser := &domain.RoleUser{
Id: 0,
RoleId: in.RoleId,
UserId: int64Num,
CompanyId: in.CompanyId,
}
_, err := roleUserRepository.Insert(newRoleUser)
if 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 nil, nil
}
func (rs *RoleUserService) Remove(in *command.UserRoleDeleteCommand) (interface{}, error) {
transactionContext, err := factory.ValidateStartTransaction(in)
if err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
roleUserRepository := factory.CreateRoleUserRepository(map[string]interface{}{"transactionContext": transactionContext})
// 检测已存在的关联用户
_, rus, err := roleUserRepository.Find(map[string]interface{}{"roleId": in.RoleId, "companyId": in.CompanyId, "userId": in.UserId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if len(rus) == 0 {
return nil, application.ThrowError(application.BUSINESS_ERROR, "数据不存在")
}
if _, err := roleUserRepository.Remove(rus[0]); 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 rus, nil
}
//func (rs *RoleUserService) ListForUser(in *command.UserRoleQueryCommand) (interface{}, error) {
// transactionContext, err := factory.StartTransaction()
// if err != nil {
// return nil, err
// }
// defer func() {
// transactionContext.RollbackTransaction()
// }()
// roleRepository := factory.CreateRoleUserRepository(map[string]interface{}{"transactionContext": transactionContext})
// userRepository := factory.CreateUserRepository(map[string]interface{}{"transactionContext": transactionContext})
//
// in.PageNumber = 1
// in.PageSize = 9999999
//
// conditionMap := tool_funs.SimpleStructToMap(in)
// _, roles, err := roleRepository.Find(conditionMap)
// if err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// }
// if len(roles) == 0 {
// return nil, application.ThrowError(application.BUSINESS_ERROR, "未找到角色数据")
// }
//
// ids := make([]int64, 0)
// for i := range roles {
// ids = append(ids, roles[i].Id)
// }
//
// _, users, err := userRepository.Find(conditionMap)
// if err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// }
//
// //for i := range users {
// // users[i].RoleUserIds
// //}
//
// //if err := transactionContext.CommitTransaction(); err != nil {
// // return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
// //}
// //groupAdapter := &adapter.RoleUserAdapter{}
// //newList := groupAdapter.TransformTree(groups)
// return map[string]interface{}{"list": users}, nil
//}
... ...
... ... @@ -4,7 +4,7 @@ package constant
import "os"
var KAFKA_HOSTS = "127.7.8.1:9094" // 1.116.151.79:9092
var KAFKA_HOSTS = "127.0.0.1:9092" // 1.116.151.79:9092
var KAFKA_GROUP_ID = "performance_dev"
... ...
//go:build local
package constant
var KAFKA_HOSTS = "127.0.0.1:9092" // 1.116.151.79:9092
var KAFKA_GROUP_ID = "performance_dev"
var KAFKA_BUSINESS_ADMIN_TOPIC = "mmm-business-admin-dev"
func init() {
}
package domain
import "time"
const (
RoleTypeCommon int = 0 // 角色类型-后台添加角色
RoleTypeSystem int = 1 // 角色类型-系统预制角色(不可删除、编辑)
)
type Role struct {
Id int64 `json:"id,string"`
Name string `json:"name"`
Type int `json:"type"`
Description string `json:"description"`
CompanyId int64 `json:"companyId,string"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt *time.Time `json:"deletedAt"`
}
type RoleRepository interface {
Insert(role *Role) (*Role, error)
Remove(role *Role) (*Role, error)
FindOne(queryOptions map[string]interface{}) (*Role, error)
Find(queryOptions map[string]interface{}) (int64, []*Role, error)
Count(queryOptions map[string]interface{}) (int64, error)
}
... ...
package domain
import (
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/role/adapter"
"time"
)
type RoleUser struct {
Id int64 `json:"id,string"`
RoleId int64 `json:"roleId,string"`
UserId int64 `json:"userId,string"`
CompanyId int64 `json:"companyId,string"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt *time.Time `json:"deletedAt"`
}
type RoleUserRepository interface {
Insert(role *RoleUser) (*RoleUser, error)
Remove(role *RoleUser) (*RoleUser, error)
FindOne(queryOptions map[string]interface{}) (*RoleUser, error)
Find(queryOptions map[string]interface{}) (int64, []*RoleUser, error)
Count(queryOptions map[string]interface{}) (int64, error)
BatchDeleteById(ids []int64) error
FindAllContainUser(pageSize int, pageNumber int, companyId int64, roleId int64) ([]*adapter.RoleContainUser, error)
}
... ...
... ... @@ -9,6 +9,7 @@ type User struct {
CompanyId int64 // 公司编号
AdminType int // 1普通员工 2 主管理员
Name string // 用户姓名
Email string // 邮箱
Status int // 用户状态(1正常 2禁用)
DepartmentId []int // 用户归属的部门
UpdateAt time.Time // 更新时间
... ...
... ... @@ -2,6 +2,9 @@ package pg
import (
"fmt"
"github.com/go-pg/pg/v10/orm"
"github.com/linmadan/egglib-go/persistent/pg/comment"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/log"
... ... @@ -25,4 +28,26 @@ func init() {
})
}
models := []interface{}{
&models.User{},
&models.Company{},
&models.Department{},
&models.Role{},
}
if !constant.DISABLE_CREATE_TABLE {
for _, model := range models {
err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
Temp: false,
IfNotExists: true,
FKConstraints: true,
})
if err != nil {
panic(err)
}
comment.AddComments(DB, model)
}
//建表索引
}
}
... ...
package models
import "time"
type Role struct {
tableName struct{} `pg:"role" comment:"角色"`
Id int64 `pg:"pk:id" comment:"ID"`
Name string `comment:"角色名称"`
Type int `comment:"角色类型(0角色可删、1系统预置角色不可删)"`
Description string `comment:"角色描述"`
CompanyId int64 `comment:"公司ID"`
CreatedAt time.Time `comment:"创建时间"`
UpdatedAt time.Time `comment:"更新时间"`
DeletedAt *time.Time `comment:"删除时间"`
}
... ...
package models
import "time"
type RoleUser struct {
tableName struct{} `pg:"role_user" comment:"角色用户关系"`
Id int64 `pg:"pk:id" comment:"ID"`
RoleId int64 `comment:"角色ID"`
UserId int64 `comment:"用户ID"`
CompanyId int64 `comment:"公司ID"`
CreatedAt time.Time `comment:"创建时间"`
UpdatedAt time.Time `comment:"更新时间"`
DeletedAt *time.Time `comment:"删除时间"`
}
... ...
... ... @@ -10,6 +10,7 @@ type User struct {
CompanyId int64 // 公司编号
AdminType int // 1普通员工 2 主管理员
Name string // 用户姓名
Email string // 邮箱
Status int // 用户状态(1正常 2禁用)
DepartmentId []int // 用户归属的部门
UpdateAt time.Time // 更新时间
... ...
package repository
import (
"errors"
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/utils"
"time"
)
type RoleRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func NewRoleRepository(transactionContext *pgTransaction.TransactionContext) *RoleRepository {
return &RoleRepository{transactionContext: transactionContext}
}
func (repo *RoleRepository) TransformToDomain(m *models.Role) domain.Role {
return domain.Role{
Id: m.Id,
Name: m.Name,
Type: m.Type,
Description: m.Description,
CompanyId: m.CompanyId,
CreatedAt: m.CreatedAt,
UpdatedAt: m.UpdatedAt,
DeletedAt: m.DeletedAt,
}
}
func (repo *RoleRepository) TransformToModel(d *domain.Role) models.Role {
return models.Role{
Id: d.Id,
Name: d.Name,
Type: d.Type,
Description: d.Description,
CompanyId: d.CompanyId,
CreatedAt: d.CreatedAt,
UpdatedAt: d.UpdatedAt,
DeletedAt: d.DeletedAt,
}
}
func (repo *RoleRepository) nextIdentify() (int64, error) {
return utils.NewSnowflakeId()
}
func (repo *RoleRepository) Insert(d *domain.Role) (*domain.Role, error) {
var isCreate = d.Id == 0
if isCreate {
id, err := repo.nextIdentify()
if err != nil {
return d, err
}
d.Id = id
d.CreatedAt = time.Now()
d.UpdatedAt = d.CreatedAt
} else {
d.UpdatedAt = time.Now()
}
m := repo.TransformToModel(d)
tx := repo.transactionContext.PgTx
var err error
if isCreate {
_, err = tx.Model(&m).Returning("id").Insert()
} else {
_, err = tx.Model(&m).Returning("id").WherePK().Update() // 更新和删除必须增加条件
}
if err != nil {
return nil, err
}
d.Id = m.Id
return d, nil
}
func (repo *RoleRepository) Remove(d *domain.Role) (*domain.Role, error) {
tx := repo.transactionContext.PgTx
nowTime := time.Now()
m := repo.TransformToModel(d)
m.DeletedAt = &nowTime
if _, err := tx.Model(&m).WherePK().Update(); err != nil {
return d, err
}
return d, nil
}
func (repo *RoleRepository) FindOne(queryOptions map[string]interface{}) (*domain.Role, error) {
tx := repo.transactionContext.PgTx
m := new(models.Role)
query := tx.Model(m)
query.Where("deleted_at isnull")
if id, ok := queryOptions["id"]; ok {
query.Where("id=?", id)
}
if err := query.First(); err != nil {
if errors.Is(err, pg.ErrNoRows) {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
u := repo.TransformToDomain(m)
return &u, nil
}
func (repo *RoleRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Role, error) {
tx := repo.transactionContext.PgTx
var m []*models.Role
query := tx.Model(&m).
Where("deleted_at isnull").
Limit(20)
if name, ok := queryOptions["name"]; ok {
query.Where("name = ?", name)
}
if companyId, ok := queryOptions["companyId"]; ok {
query.Where("company_id = ?", companyId)
}
if v, ok := queryOptions["limit"].(int); ok {
query.Limit(v)
}
if v, ok := queryOptions["offset"].(int); ok {
query.Offset(v)
}
count, err := query.SelectAndCount()
if err != nil {
return 0, nil, err
}
var arrays []*domain.Role
for _, v := range m {
d := repo.TransformToDomain(v)
arrays = append(arrays, &d)
}
return int64(count), arrays, nil
}
func (repo *RoleRepository) Count(queryOptions map[string]interface{}) (int64, error) {
tx := repo.transactionContext.PgTx
m := new(models.Role)
query := sqlbuilder.BuildQuery(tx.Model(m), queryOptions)
query.Where("deleted_at isnull")
if id, ok := queryOptions["id"]; ok {
query.Where("id = ?", id)
}
if notId, ok := queryOptions["notId"]; ok {
query.Where("id != ?", notId)
}
if name, ok := queryOptions["name"]; ok {
query.Where("name = ?", name)
}
if companyId, ok := queryOptions["companyId"]; ok {
query.Where("company_id = ?", companyId)
}
count, err := query.Count()
if err != nil {
return 0, err
}
return int64(count), nil
}
... ...
package repository
import (
"errors"
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/role/adapter"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/utils"
"time"
)
type RoleUserRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func NewRoleUserRepository(transactionContext *pgTransaction.TransactionContext) *RoleUserRepository {
return &RoleUserRepository{transactionContext: transactionContext}
}
func (repo *RoleUserRepository) TransformToDomain(m *models.RoleUser) domain.RoleUser {
return domain.RoleUser{
Id: m.Id,
RoleId: m.RoleId,
UserId: m.UserId,
CompanyId: m.CompanyId,
CreatedAt: m.CreatedAt,
UpdatedAt: m.UpdatedAt,
DeletedAt: m.DeletedAt,
}
}
func (repo *RoleUserRepository) TransformToModel(d *domain.RoleUser) models.RoleUser {
return models.RoleUser{
Id: d.Id,
RoleId: d.RoleId,
UserId: d.UserId,
CompanyId: d.CompanyId,
CreatedAt: d.CreatedAt,
UpdatedAt: d.UpdatedAt,
DeletedAt: d.DeletedAt,
}
}
func (repo *RoleUserRepository) nextIdentify() (int64, error) {
return utils.NewSnowflakeId()
}
func (repo *RoleUserRepository) Insert(d *domain.RoleUser) (*domain.RoleUser, error) {
var isCreate = d.Id == 0
if isCreate {
id, err := repo.nextIdentify()
if err != nil {
return d, err
}
d.Id = id
d.CreatedAt = time.Now()
d.UpdatedAt = d.CreatedAt
} else {
d.UpdatedAt = time.Now()
}
m := repo.TransformToModel(d)
tx := repo.transactionContext.PgTx
var err error
if isCreate {
_, err = tx.Model(&m).Returning("id").Insert()
} else {
_, err = tx.Model(&m).Returning("id").WherePK().Update() // 更新和删除必须增加条件
}
if err != nil {
return nil, err
}
d.Id = m.Id
return d, nil
}
func (repo *RoleUserRepository) Remove(d *domain.RoleUser) (*domain.RoleUser, error) {
tx := repo.transactionContext.PgTx
nowTime := time.Now()
m := repo.TransformToModel(d)
m.DeletedAt = &nowTime
// 真删
if _, err := tx.Model(&m).WherePK().Delete(); err != nil {
return d, err
}
return d, nil
}
func (repo *RoleUserRepository) FindOne(queryOptions map[string]interface{}) (*domain.RoleUser, error) {
tx := repo.transactionContext.PgTx
m := new(models.RoleUser)
query := tx.Model(m)
query.Where("deleted_at isnull")
if id, ok := queryOptions["id"]; ok {
query.Where("id=?", id)
}
if err := query.First(); err != nil {
if errors.Is(err, pg.ErrNoRows) {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
u := repo.TransformToDomain(m)
return &u, nil
}
func (repo *RoleUserRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.RoleUser, error) {
tx := repo.transactionContext.PgTx
var m []*models.RoleUser
query := tx.Model(&m).Where("deleted_at isnull").Limit(20)
if roleId, ok := queryOptions["roleId"]; ok {
query.Where("role_id = ?", roleId)
}
if companyId, ok := queryOptions["companyId"]; ok {
query.Where("company_id = ?", companyId)
}
if userId, ok := queryOptions["userId"]; ok {
query.Where("user_id = ?", userId)
}
if userIds, ok := queryOptions["userIds"]; ok {
query.Where("user_id in (?)", userIds)
}
if v, ok := queryOptions["limit"].(int); ok {
query.Limit(v)
}
if v, ok := queryOptions["offset"].(int); ok {
query.Offset(v)
}
count, err := query.SelectAndCount()
if err != nil {
return 0, nil, err
}
var arrays []*domain.RoleUser
for _, v := range m {
d := repo.TransformToDomain(v)
arrays = append(arrays, &d)
}
return int64(count), arrays, nil
}
func (repo *RoleUserRepository) Count(queryOptions map[string]interface{}) (int64, error) {
tx := repo.transactionContext.PgTx
m := new(models.RoleUser)
query := sqlbuilder.BuildQuery(tx.Model(m), queryOptions)
query.Where("deleted_at isnull")
if id, ok := queryOptions["id"]; ok {
query.Where("id = ?", id)
}
if notId, ok := queryOptions["notId"]; ok {
query.Where("id != ?", notId)
}
if name, ok := queryOptions["name"]; ok {
query.Where("name = ?", name)
}
if companyId, ok := queryOptions["companyId"]; ok {
query.Where("company_id = ?", companyId)
}
count, err := query.Count()
if err != nil {
return 0, err
}
return int64(count), nil
}
func (repo *RoleUserRepository) BatchDeleteById(ids []int64) error {
tx := repo.transactionContext.PgTx
_, err := tx.Model(&models.RoleUser{}).Where("id IN (?)", pg.In(ids)).Delete()
return err
}
func (repo *RoleUserRepository) FindAllContainUser(pageSize int, pageNumber int, companyId int64, roleId int64) ([]*adapter.RoleContainUser, error) {
limit := pageSize
offset := limit * (pageNumber - 1)
if offset < 0 {
offset = 0
}
dataSql := ` SELECT
"role_user".role_id,
"role_user".user_id,
"user".name as user_name,
"user".email as user_email,
`
whereFrom := `
FROM "role_user"
LEFT JOIN "user" ON "user".id = "role_user".user_id
WHERE 1=1 AND "role_user".deleted_at ISNULL `
var param []interface{}
if companyId > 0 {
param = append(param, companyId)
whereFrom += ` AND role_user.company_id=? `
}
if roleId >= 0 {
param = append(param, roleId)
whereFrom += ` AND role_user.role_id =? `
}
dataSql += whereFrom
dataSql = fmt.Sprintf("%s limit %d offset %d", dataSql, limit, offset)
tx := repo.transactionContext.PgTx
var dataList = make([]*adapter.RoleContainUser, 0)
_, err := tx.Query(&dataList, dataSql, param...)
return dataList, err
}
... ...
... ... @@ -51,6 +51,7 @@ func (repo *UserRepository) Update(user *domain.User) (*domain.User, error) {
CompanyId: user.CompanyId,
AdminType: user.AdminType,
Name: user.Name,
Email: user.Email,
Status: user.Status,
UpdateAt: user.UpdateAt,
CreateAt: user.CreateAt,
... ... @@ -139,6 +140,7 @@ func (repo *UserRepository) TransformToUserDomain(user *models.User) *domain.Use
CompanyId: user.CompanyId,
AdminType: user.AdminType,
Name: user.Name,
Email: user.Email,
Status: user.Status,
UpdateAt: user.UpdateAt,
CreateAt: user.CreateAt,
... ...
package controllers
import (
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/web/beego"
service "gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/role"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/role/command"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/port/beego/middlewares"
)
type RoleController struct {
beego.BaseController
}
func (controller *RoleController) CreateRole() {
ruService := service.NewRoleService()
in := &command.CreateRoleCommand{}
if err := controller.Unmarshal(in); err != nil {
controller.Response(nil, application.ThrowError(application.ARG_ERROR, err.Error()))
} else {
in.CompanyId = middlewares.GetCompanyId(controller.Ctx)
controller.Response(ruService.Create(in))
}
}
func (controller *RoleController) UpdateRole() {
ruService := service.NewRoleService()
in := &command.UpdateRoleCommand{}
if err := controller.Unmarshal(in); err != nil {
controller.Response(nil, application.ThrowError(application.ARG_ERROR, err.Error()))
} else {
in.CompanyId = middlewares.GetCompanyId(controller.Ctx)
controller.Response(ruService.Update(in))
}
}
func (controller *RoleController) RemoveRole() {
ruService := service.NewRoleService()
in := &command.DeleteRoleCommand{}
if err := controller.Unmarshal(in); err != nil {
controller.Response(nil, application.ThrowError(application.ARG_ERROR, err.Error()))
} else {
in.CompanyId = middlewares.GetCompanyId(controller.Ctx)
controller.Response(ruService.Remove(in))
}
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/web/beego"
service "gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/role"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/role/command"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/port/beego/middlewares"
)
type RoleUserController struct {
beego.BaseController
}
func (controller *RoleUserController) CreateRoleUser() {
ruService := service.NewRoleUserService()
in := &command.UserRoleCreateCommand{}
if err := controller.Unmarshal(in); err != nil {
controller.Response(nil, application.ThrowError(application.ARG_ERROR, err.Error()))
} else {
in.CompanyId = middlewares.GetCompanyId(controller.Ctx)
controller.Response(ruService.Create(in))
}
}
func (controller *RoleUserController) RemoveRoleUser() {
ruService := service.NewRoleUserService()
in := &command.UserRoleDeleteCommand{}
if err := controller.Unmarshal(in); err != nil {
controller.Response(nil, application.ThrowError(application.ARG_ERROR, err.Error()))
} else {
in.CompanyId = middlewares.GetCompanyId(controller.Ctx)
controller.Response(ruService.Remove(in))
}
}
... ...
package middlewares
import (
"github.com/beego/beego/v2/server/web/context"
)
func setUserId(userId int64, ctx *context.Context) {
ctx.Input.SetData("_UserId", userId)
}
func GetUserId(ctx *context.Context) int64 {
userId := ctx.Input.GetData("_UserId")
return userId.(int64)
}
func setCompanyId(companyId int64, ctx *context.Context) {
ctx.Input.SetData("_CompanyId", companyId)
}
func GetCompanyId(ctx *context.Context) int64 {
companyId := ctx.Input.GetData("_CompanyId")
return companyId.(int64)
}
func setCompanyType(companyId int, ctx *context.Context) {
ctx.Input.SetData("_CompanyType", companyId)
}
func GetCompanyType(ctx *context.Context) int {
companyId := ctx.Input.GetData("_CompanyType")
return companyId.(int)
}
func invalidOrExpired(ctx *context.Context) {
resp := map[string]interface{}{
"code": 902,
"msg": "Authorization过期或无效,需要进行重新获取令牌",
}
_ = ctx.Output.JSON(resp, false, false)
}
func CheckToken() func(ctx *context.Context) {
return func(ctx *context.Context) {
tokenStr := ctx.Input.Header("x-mmm-accesstoken")
if tokenStr == "" { //没有带token
invalidOrExpired(ctx)
return
}
//userServe := service.UserService{}
//userTk, err := userServe.ValidLoginToken(tokenStr)
//if err != nil {
// invalidOrExpired(ctx)
// return
//}
//setUserId(userTk.UserId, ctx)
//setCompanyId(userTk.CompanyId, ctx)
//setCompanyType(userTk.CompanyType, ctx)
}
}
... ...
package utils
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
"reflect"
"strings"
)
// ValidateCommand 验证输入参数
func ValidateCommand(commandType interface{}) error {
valid := validation.Validation{}
b, err := valid.Valid(commandType)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(commandType).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
if tag := field.Tag.Get("cname"); len(tag) > 0 {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, tag, -1))
} else {
return fmt.Errorf(validErr.Message)
}
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package utils
import (
"github.com/bwmarrin/snowflake"
)
//生成新ID
var snowFlakeNode *snowflake.Node
func NewSnowflakeId() (int64, error) {
if snowFlakeNode == nil {
node, err := snowflake.NewNode(1)
if err != nil {
return 0, err
}
snowFlakeNode = node
}
// Generate a snowflake ID.
id := snowFlakeNode.Generate()
return id.Int64(), nil
}
... ...