作者 郑周

1. 通讯录结构调整

... ... @@ -27,18 +27,20 @@ func main() {
func startNodeTask() {
go func() {
nodeTaskService := serviceTask.NewNodeTaskService()
var duration time.Duration
if constant.Env == "prd" {
duration = time.Minute * 5
} else {
duration = time.Minute * 1
}
timer := time.NewTimer(duration)
for {
var duration time.Duration
if constant.Env == "prd" {
duration = time.Minute * 5
} else {
duration = time.Minute * 1
}
timer := time.NewTimer(duration)
<-timer.C
if err := nodeTaskService.SendEvaluationNode(); err != nil {
log.Logger.Error(err.Error())
}
timer.Reset(duration) // 重置定时
}
}()
}
... ...
... ... @@ -31,3 +31,20 @@ func TestFontToken(t *testing.T) {
}
fmt.Println(userAuth.CreateAccessToken())
}
func TestOtherAccountToken(t *testing.T) {
domain.JWTExpiresSecond = 3600 * 24 * 365
userAuth := &domain.UserAuth{
UserId: 3422174102828544,
CompanyId: 8,
Phone: "17708397664",
PlatformId: 28,
Name: "杨欢",
AdminType: 1,
}
tk, _ := userAuth.CreateAccessToken()
t.Log(tk)
//fmt.Println(userAuth.CreateAccessToken())
}
... ...
package adapter
type DepartmentAdapter struct {
Id int64 `comment:"部门ID" json:"id"`
Name string `comment:"部门名称" json:"name"`
CompanyId int64 `comment:"公司ID" json:"companyId"`
ParentId int64 `comment:"父级ID" json:"parentId"`
Departments []*DepartmentAdapter `comment:"子部门" json:"departments"`
UserTotal int `comment:"部门用户总数量(包含子部门)" json:"userTotal"`
}
... ...
package command
import "github.com/beego/beego/v2/core/validation"
// QueryDepartmentCommand 查询公司的所有部门和人数
type QueryDepartmentCommand struct {
CompanyId int64 `cname:"公司ID" json:"companyId"`
}
func (in *QueryDepartmentCommand) Valid(*validation.Validation) {
}
... ...
package department
import (
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/department/adapter"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/department/command"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/factory"
)
type SDepartmentService struct{}
func NewDepartmentService() *SDepartmentService {
newService := &SDepartmentService{}
return newService
}
func (ds *SDepartmentService) ListAndCount(in *command.QueryDepartmentCommand) (interface{}, error) {
transactionContext, err := factory.ValidateStartTransaction(in)
if err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
departmentRepository := factory.CreateDepartmentRepository(map[string]interface{}{"transactionContext": transactionContext})
userRepository := factory.CreateUserRepository(map[string]interface{}{"transactionContext": transactionContext})
companyRepository := factory.CreateCompanyRepository(map[string]interface{}{"transactionContext": transactionContext})
departments, err := departmentRepository.FindAll(in.CompanyId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
adapters := make([]*adapter.DepartmentAdapter, 0)
mapDep := map[int64]*adapter.DepartmentAdapter{}
mapDepNum := map[int64]int{}
// 已经按等级Level升序排序, 1级> 2级> ...
for i := range departments {
apt := &adapter.DepartmentAdapter{
Id: departments[i].Id,
Name: departments[i].Name,
CompanyId: departments[i].CompanyId,
ParentId: departments[i].ParentId,
Departments: make([]*adapter.DepartmentAdapter, 0),
}
mapDep[apt.Id] = apt
// 一级节点
if apt.ParentId == 0 {
adapters = append(adapters, apt)
} else {
// 上级节点若存在,加到上级的子节点
if parent, ok := mapDep[apt.ParentId]; ok {
parent.Departments = append(parent.Departments, apt)
}
}
// 所有部门ID
mapDepNum[apt.Id] = 0
}
// 获取公司信息
company, err := companyRepository.FindOne(map[string]interface{}{"id": in.CompanyId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
// 获取所有用户
userCount, users, err := userRepository.Find(map[string]interface{}{"companyId": in.CompanyId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
for i := range users {
v := users[i]
// 注.如果用户部门下挂到公司下,顶级公司数量暂时使用所有用户数量(userCount)
for _, depId := range v.DepartmentId {
if count, ok := mapDepNum[int64(depId)]; ok {
mapDepNum[int64(depId)] = count + 1 // 部门数量 + 1
}
}
}
// 计算部门下的用户总数量
ds.calculateChildTotal(mapDepNum, adapters)
// 创建顶级部门(公司)
top := make([]*adapter.DepartmentAdapter, 0)
top = append(top, &adapter.DepartmentAdapter{
Id: 0,
Name: company.Name,
CompanyId: company.Id,
ParentId: 0,
Departments: adapters,
UserTotal: userCount, // 公司下的所有用户
})
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{"list": top}, nil
}
// 计算子部门总量
func (ds *SDepartmentService) calculateChildTotal(mapDepNum map[int64]int, departments []*adapter.DepartmentAdapter) int {
var total = 0
for i := range departments {
// 子部门总数量
var childTotal = ds.calculateChildTotal(mapDepNum, departments[i].Departments)
// 当前部门数量
if count, ok := mapDepNum[departments[i].Id]; ok {
childTotal += count
}
// 更新部门数量
departments[i].UserTotal = childTotal
total += childTotal
}
return total
}
... ...
... ... @@ -4,3 +4,10 @@ type ListUserQuery struct {
CompanyId int64 `json:"companyId"` // 公司ID
Name string `json:"name"` // 用户姓名
}
type ListByDepartmentQuery struct {
CompanyId int64 `cname:"公司ID" json:"companyId"`
DepartmentId int64 `cname:"部门ID" json:"departmentId"`
PageNumber int64 `cname:"分页页码" json:"pageNumber" valid:"Required"`
PageSize int64 `cname:"分页数量" json:"pageSize" valid:"Required"`
}
... ...
... ... @@ -10,7 +10,7 @@ import (
type UserService struct{}
func (service *UserService) ListUsers(listUserQuery *query.ListUserQuery) (interface{}, error) {
func (us *UserService) ListUsers(listUserQuery *query.ListUserQuery) (interface{}, error) {
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -21,9 +21,7 @@ func (service *UserService) ListUsers(listUserQuery *query.ListUserQuery) (inter
defer func() {
_ = transactionContext.RollbackTransaction()
}()
userRepo := factory.CreateUserRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
userRepo := factory.CreateUserRepository(map[string]interface{}{"transactionContext": transactionContext})
count, list, err := userRepo.Find(map[string]interface{}{
"companyId": listUserQuery.CompanyId,
"name": listUserQuery.Name,
... ... @@ -37,3 +35,27 @@ func (service *UserService) ListUsers(listUserQuery *query.ListUserQuery) (inter
}
return tool_funs.SimpleWrapGridMap(int64(count), list), nil
}
func (us *UserService) ListByDepartment(in *query.ListByDepartmentQuery) (interface{}, error) {
transactionContext, err := factory.ValidateStartTransaction(in)
if err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
userRepo := factory.CreateUserRepository(map[string]interface{}{"transactionContext": transactionContext})
inMap := tool_funs.SimpleStructToMap(in)
if in.DepartmentId == 0 {
delete(inMap, "departmentId") // 删除部门ID字段
}
count, list, err := userRepo.Find(inMap)
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 tool_funs.SimpleWrapGridMap(int64(count), list), nil
}
... ...
... ... @@ -21,4 +21,5 @@ type DepartmentRepository interface {
Remove(ids []int64) error
FindOne(queryOptions map[string]interface{}) (*Department, error)
Find(queryOptions map[string]interface{}) (int, []*Department, error)
FindAll(companyId int64) ([]*Department, error)
}
... ...
... ... @@ -12,8 +12,9 @@ type User struct {
Email string `json:"email"` // 邮箱
Status int `json:"status"` // 用户状态(1正常 2禁用)
DepartmentId []int `json:"departmentId"` // 用户归属的部门
PositionId []int `json:"PositionId"` //用户职位
EntryTime string `json:"entryTime"` //入职日期
PositionId []int `json:"PositionId"` // 用户职位
EntryTime string `json:"entryTime"` // 入职日期
ParentId int64 `json:"parentId"` // 上级ID
UpdatedAt time.Time `json:"updatedAt"` // 更新时间
DeletedAt *time.Time `json:"deletedAt"`
CreatedAt time.Time `json:"createdAt"`
... ...
... ... @@ -15,6 +15,7 @@ type User struct {
DepartmentId []int // 用户归属的部门
PositionId []int // 用户职位
EntryTime string //入职日期
ParentId int64 `pg:",use_zero"` // 上级ID
CreatedAt time.Time // 创建时间
UpdatedAt time.Time // 更新时间
DeletedAt *time.Time `pg:",soft_delete"` // 删除时间
... ...
... ... @@ -117,6 +117,27 @@ func (repo *DepartmentRepository) Find(queryOptions map[string]interface{}) (int
return cnt, resultList, nil
}
func (repo *DepartmentRepository) FindAll(companyId int64) ([]*domain.Department, error) {
tx := repo.transactionContext.PgTx
var departmentModels []models.Department
query := tx.Model(&departmentModels).Where("deleted_at isnull") // 不为空
if companyId > 0 {
query.Where("company_id=?", companyId)
}
query.Order("level ASC") // 按等级升序
err := query.Select()
if err != nil {
return nil, err
}
var list []*domain.Department
for i := range departmentModels {
result := repo.TransformToCompanyDomain(&departmentModels[i])
list = append(list, result)
}
return list, nil
}
func (repo *DepartmentRepository) TransformToCompanyDomain(u *models.Department) *domain.Department {
return &domain.Department{
Id: u.Id,
... ...
... ... @@ -34,6 +34,7 @@ func (repo *UserRepository) Insert(user *domain.User) (*domain.User, error) {
DepartmentId: user.DepartmentId,
PositionId: user.PositionId,
EntryTime: user.EntryTime,
ParentId: user.ParentId,
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
DeletedAt: user.DeletedAt,
... ... @@ -60,6 +61,7 @@ func (repo *UserRepository) Update(user *domain.User) (*domain.User, error) {
DepartmentId: user.DepartmentId,
PositionId: user.PositionId,
EntryTime: user.EntryTime,
ParentId: user.ParentId,
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
DeletedAt: user.DeletedAt,
... ... @@ -103,7 +105,7 @@ func (repo *UserRepository) FindOne(queryOptions map[string]interface{}) (*domai
func (repo *UserRepository) Find(queryOptions map[string]interface{}) (int, []*domain.User, error) {
tx := repo.transactionContext.PgTx
userModel := []models.User{}
query := tx.Model(&userModel)
query := tx.Model(&userModel).Where("deleted_at isnull")
if v, ok := queryOptions["id"]; ok {
query.Where("id=?", v)
}
... ... @@ -122,14 +124,27 @@ func (repo *UserRepository) Find(queryOptions map[string]interface{}) (int, []*d
if v, ok := queryOptions["status"]; ok {
query.Where("status=?", v)
}
if v, ok := queryOptions["departmentId"]; ok {
query.Where(`department_id @>'[?]'`, v)
}
if v, ok := queryOptions["name"].(string); ok && len(v) > 0 {
query.Where("name like ?", fmt.Sprintf("%%%v%%", v))
}
if v, ok := queryOptions["offset"]; ok {
query.Offset(v.(int))
if value, ok := v.(int); ok {
query.Offset(value)
} else if value, ok := v.(int64); ok {
query.Offset(int(value))
}
//query.Offset(v.(int))
}
if v, ok := queryOptions["limit"]; ok {
query.Limit(v.(int))
if value, ok := v.(int); ok {
query.Limit(value)
} else if value, ok := v.(int64); ok {
query.Limit(int(value))
}
//query.Limit(v.(int))
}
cnt, err := query.SelectAndCount()
if err != nil {
... ... @@ -156,6 +171,7 @@ func (repo *UserRepository) TransformToUserDomain(user *models.User) *domain.Use
DepartmentId: user.DepartmentId,
PositionId: user.PositionId,
EntryTime: user.EntryTime,
ParentId: user.ParentId,
UpdatedAt: user.UpdatedAt,
DeletedAt: user.DeletedAt,
CreatedAt: user.CreatedAt,
... ...
package controllers
import (
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/department"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/department/command"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/port/beego/middlewares"
)
type DepartmentController struct {
beego.BaseController
}
func (controller *DepartmentController) ListAndCount() {
dService := department.NewDepartmentService()
in := &command.QueryDepartmentCommand{}
if err := controller.Unmarshal(in); err != nil {
controller.Response(nil, application.ThrowError(application.ARG_ERROR, err.Error()))
} else {
ua := middlewares.GetUser(controller.Ctx)
in.CompanyId = ua.CompanyId
controller.Response(dService.ListAndCount(in))
}
}
... ...
... ... @@ -413,6 +413,9 @@ func (c *StaffAssessController) QueryMemberPerformanceIndicator() {
if user := middlewares.GetUser(c.Ctx); user != nil {
in.CompanyId = int(user.CompanyId)
in.OperatorId = int(user.UserId)
//in.CompanyId = int(8) // 杨欢测试数据 周期ID=1612638113870385152 公司ID=8 用户ID=3422174102828544
//in.OperatorId = int(3422174102828544)
}
c.Response(srv.QueryMemberPerformanceIndicator(in))
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/user"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/user/query"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/port/beego/middlewares"
)
type UserController struct {
... ... @@ -20,3 +22,14 @@ func (controller *UserController) ListUsers() {
resp, err := (&user.UserService{}).ListUsers(listUserQuery)
controller.Response(resp, err)
}
func (controller *UserController) ListByDepartment() {
in := &query.ListByDepartmentQuery{}
if err := controller.Unmarshal(in); err != nil {
controller.Response(nil, application.ThrowError(application.ARG_ERROR, err.Error()))
} else {
ua := middlewares.GetUser(controller.Ctx)
in.CompanyId = ua.CompanyId
controller.Response((&user.UserService{}).ListByDepartment(in))
}
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"github.com/linmadan/egglib-go/web/beego/filters"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/port/beego/controllers"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/port/beego/middlewares"
)
func init() {
ns := web.NewNamespace("/v1/department",
web.NSBefore(filters.AllowCors(), middlewares.CheckAdminToken()),
web.NSRouter("/list-count", &controllers.DepartmentController{}, "Post:ListAndCount"),
)
web.AddNamespace(ns)
}
... ...
... ... @@ -11,6 +11,7 @@ func init() {
ns := web.NewNamespace("/v1/users",
web.NSBefore(filters.AllowCors(), middlewares.CheckAdminToken()),
web.NSRouter("/search", &controllers.UserController{}, "Post:ListUsers"),
web.NSRouter("/list-dep", &controllers.UserController{}, "Post:ListByDepartment"),
)
web.AddNamespace(ns)
}
... ...
ALTER TABLE "public"."user" ADD COLUMN "parent_id" int8 DEFAULT 0;
COMMENT ON COLUMN "public"."user"."parent_id" IS '上级ID';
\ No newline at end of file
... ...