审查视图

pkg/application/summary_evaluation/service/scheduled_v2.go 12.2 KB
1 2 3 4 5 6 7
package service

import (
	"fmt"
	"strconv"
	"time"
tangxvhui authored
8
	"github.com/linmadan/egglib-go/core/application"
9
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/factory"
10
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/notify"
11 12 13 14 15 16 17 18 19 20 21 22 23
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/dao"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/log"
)

// 定时下发周期评估任务
func TaskSendSummaryEvaluationV2() error {
	nowTime := time.Now()
	defer func() {
		str := fmt.Sprintf("下发周期评估耗时%.2f s", time.Since(nowTime).Seconds())
		log.Logger.Info(str)
	}()
	for {
tangxvhui authored
24
		cycleList, err := getPrepareEvaluationCycle()
25 26 27
		if err != nil {
			return err
		}
tangxvhui authored
28
		if len(cycleList) == 0 {
29 30
			break
		}
tangxvhui authored
31 32
		err = sendSummaryEvaluationByCycle(cycleList[0])
		if err != nil {
33 34 35 36 37 38
			return err
		}
	}
	return nil
}
39 40 41 42 43 44
func dayEndTime(t time.Time) time.Time {
	y, m, d := t.Local().Date()
	t2 := time.Date(y, m, d, 23, 59, 59, 0, time.Local)
	return t2
}
tangxvhui authored
45 46
// 获取周期
func getPrepareEvaluationCycle() ([]*domain.EvaluationCycle, error) {
47 48 49 50 51 52 53 54 55 56
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, err
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, err
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
tangxvhui authored
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
	cycleRepo := factory.CreateEvaluationCycleRepository(map[string]interface{}{"transactionContext": transactionContext})
	cycleList, err := cycleRepo.FindCycleEnd(1)
	if err != nil {
		return nil, fmt.Errorf("获取可用的周期数据,%s", err)
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, err
	}
	return cycleList, nil
}

// 按周期下发 综合评估任务
func sendSummaryEvaluationByCycle(cycleParam *domain.EvaluationCycle) error {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return err
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return err
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
81 82 83 84 85
	projectRepo := factory.CreateEvaluationProjectRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	// 获取项目数据总数
	_, projectList, err := projectRepo.Find(map[string]interface{}{
tangxvhui authored
86
		"cycleId":      cycleParam.Id,
87 88
		"summaryState": domain.ProjectSummaryStateNo,
		"state":        domain.ProjectStateEnable,
tangxvhui authored
89
		"limit":        500,
90 91
	}, "template")
	if err != nil {
tangxvhui authored
92 93
		return fmt.Errorf("获取可用的项目数据,%s", err)
	}
94 95 96 97
	permissionData, err := getPermission(cycleParam.CompanyId)
	if err != nil {
		return fmt.Errorf("获取公司的周期评估设置项,%s", err)
	}
tangxvhui authored
98 99 100
	var newEvaluationList []domain.SummaryEvaluation
	newPublisher := summaryEvaluationPublisher{}
	for _, val := range projectList {
101
		evaluationList, err := newPublisher.sendSummaryEvaluationV2(transactionContext, val, cycleParam, *permissionData)
tangxvhui authored
102 103 104 105 106 107 108 109 110 111
		if err != nil {
			return fmt.Errorf("按项目下发综合评估任务数据,%s", err)
		}
		newEvaluationList = append(newEvaluationList, evaluationList...)
	}
	// 回填周期的状态
	cycleDao := dao.NewEvaluationCycleDao(map[string]interface{}{"transactionContext": transactionContext})
	err = cycleDao.UpdateSummaryState(cycleParam.Id, domain.ProjectSummaryStateYes)
	if err != nil {
		return fmt.Errorf("保存项目周期状态%s", err)
112 113
	}
	if err := transactionContext.CommitTransaction(); err != nil {
tangxvhui authored
114
		return err
115
	}
tangxvhui authored
116 117 118 119 120
	err = sendSmsEvalation(newEvaluationList)
	if err != nil {
		return fmt.Errorf("设置短信消息%s", err)
	}
	return nil
121 122
}
123 124 125 126 127 128 129 130 131 132
// // 添加待发送的短信通知
func sendSmsEvalation(param []domain.SummaryEvaluation) error {
	for i := range param {
		if param[i].Types == domain.EvaluationSelf {
			notify.AddNotifySummaryEvaluation(&param[i])
		}
	}
	return nil
}
133 134 135 136 137 138
// 下发周期综合评估
type summaryEvaluationPublisher struct {
	userCache   map[int64]*domain.User
	departCache map[int]*domain.Department
}
tangxvhui authored
139 140
func (se *summaryEvaluationPublisher) sendSummaryEvaluationV2(
	transactionContext application.TransactionContext,
141 142 143
	projectParam *domain.EvaluationProject,
	cycleData *domain.EvaluationCycle,
	permissioData domain.Permission,
tangxvhui authored
144
) ([]domain.SummaryEvaluation, error) {
145 146 147 148 149 150 151 152
	userRepo := factory.CreateUserRepository(map[string]interface{}{"transactionContext": transactionContext})
	departmentRepo := factory.CreateDepartmentRepository(map[string]interface{}{"transactionContext": transactionContext})
	evaluationItemRepo := factory.CreateEvaluationItemUsedRepository(map[string]interface{}{"transactionContext": transactionContext})
	_, evaluationItemList, err := evaluationItemRepo.Find(map[string]interface{}{
		"evaluationProjectId": projectParam.Id,
		"nodeType":            int(domain.LinkNodeSelfAssessment),
	})
	if err != nil {
tangxvhui authored
153
		return nil, err
154 155
	}
	if len(evaluationItemList) == 0 {
tangxvhui authored
156
		return nil, nil
157 158 159 160 161 162 163 164 165 166 167 168 169 170
	}
	nodeId := evaluationItemList[0].NodeId
	executor360Map := map[int64]*domain.User{}
	hrbpExist := false
	for _, v := range evaluationItemList {
		nodeId = v.NodeId
		if v.EvaluatorId < 0 {
			hrbpExist = true
		}
		if v.EvaluatorId <= 0 {
			continue
		}
		user360, err := se.getUserData(userRepo, int64(v.EvaluatorId))
		if err != nil {
tangxvhui authored
171
			return nil, fmt.Errorf("获取360用户%s", err)
172 173 174 175
		}
		executor360Map[user360.Id] = user360
	}
	if cycleData.TimeEnd == nil {
tangxvhui authored
176
		return nil, fmt.Errorf("周期%d:%s 结束时间错误", cycleData.Id, cycleData.Name)
177
	}
178
179
	//自评的时间范围
180 181
	beginTimeSelf := *cycleData.TimeEnd //
	beginDay := dayEndTime(beginTimeSelf)
tangxvhui authored
182
	//修改 周期结束时间那天的第二天开始计算
郑周 authored
183 184
	endTimeSelf := beginDay.Add(time.Duration(permissioData.CycleDeadline.AssessmentSelf.Hour) * time.Hour).
		Add(time.Duration(permissioData.CycleDeadline.AssessmentSelf.Minute) * time.Minute)
185 186
	//人资、360评估的时间范围
	beginTime360 := endTimeSelf
郑周 authored
187 188
	endTime360 := beginDay.Add(time.Duration(permissioData.CycleDeadline.AssessmentAll.Hour) * time.Hour).
		Add(time.Duration(permissioData.CycleDeadline.AssessmentAll.Minute) * time.Minute)
189 190
	//人资评估的时间范围
	beginTimeHr := endTimeSelf
郑周 authored
191 192
	endTimeHr := beginDay.Add(time.Duration(permissioData.CycleDeadline.AssessmentHr.Hour) * time.Hour).
		Add(time.Duration(permissioData.CycleDeadline.AssessmentHr.Minute) * time.Minute)
193
194
	//上级评估的是时间范围
195
	beginTimeSuper := endTimeHr
郑周 authored
196 197
	endTimeSuper := beginDay.Add(time.Duration(permissioData.CycleDeadline.AssessmentSuperior.Hour) * time.Hour).
		Add(time.Duration(permissioData.CycleDeadline.AssessmentSuperior.Minute) * time.Minute)
198 199 200

	//考核结果的时间范围
	beginTimeFinish := endTimeSuper
郑周 authored
201 202
	endTimeFinish := beginDay.Add(time.Duration(permissioData.CycleDeadline.ViewMyPerf.Hour) * time.Hour).
		Add(time.Duration(permissioData.CycleDeadline.ViewMyPerf.Minute) * time.Minute)
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
	// 创建周期评估任务
	var newEvaluationList []domain.SummaryEvaluation
	evaluationTemp := domain.SummaryEvaluation{
		Id:                    0,
		CompanyId:             int(projectParam.CompanyId),
		EvaluationProjectId:   int(projectParam.Id),
		EvaluationProjectName: projectParam.Name,
		CycleId:               cycleData.Id,
		CycleName:             cycleData.Name,
		NodeId:                nodeId,
		TargetUser:            domain.StaffDesc{},         //待填充
		TargetDepartment:      []domain.StaffDepartment{}, //待填充
		Executor:              domain.StaffDesc{},
		Types:                 0, //待填充
		Status:                domain.EvaluationUncompleted,
		CheckResult:           domain.EvaluationCheckUncompleted,
		BeginTime:             time.Time{}, //待填充
		EndTime:               time.Time{}, //待填充
		TotalScore:            "",
		CreatedAt:             time.Now(),
		UpdatedAt:             time.Now(),
		DeletedAt:             nil,
	}

	for _, val := range projectParam.Recipients {
		targetUserId, _ := strconv.ParseInt(val, 10, 64)
		if targetUserId == 0 {
			continue
		}
		targetUser, err := se.getUserData(userRepo, targetUserId)
		if err != nil {
tangxvhui authored
234
			return nil, fmt.Errorf("获取员工数据%s", err)
235 236 237 238 239 240
		}
		if targetUser == nil {
			continue
		}
		targetUserDepartment, err := se.getDepartmentData(departmentRepo, targetUser.DepartmentId)
		if err != nil {
tangxvhui authored
241
			return nil, fmt.Errorf("获取员工的部门数据%s", err)
242 243
		}
		evaluationTemp.TargetDepartment = []domain.StaffDepartment{}
tangxvhui authored
244
245 246 247 248 249 250 251 252 253 254 255 256 257
		for _, d := range targetUserDepartment {
			evaluationTemp.TargetDepartment = append(evaluationTemp.TargetDepartment, domain.StaffDepartment{
				DepartmentId:   int(d.Id),
				DepartmentName: d.Name,
			})
		}
		evaluationTemp.TargetUser = domain.StaffDesc{
			UserId:   int(targetUser.Id),
			Account:  targetUser.Account,
			UserName: targetUser.Name,
		}
		//处理自评
		{
tangxvhui authored
258
			evaluationTemp.Types = domain.EvaluationSelf
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
			evaluationTemp.Executor = domain.StaffDesc{
				UserId:   int(targetUser.Id),
				Account:  targetUser.Account,
				UserName: targetUser.Name,
			}
			evaluationTemp.BeginTime = beginTimeSelf
			evaluationTemp.EndTime = endTimeSelf
			newEvaluationList = append(newEvaluationList, evaluationTemp)
		}
		//处理360评估
		{
			for _, val2 := range executor360Map {
				evaluationTemp.BeginTime = beginTime360
				evaluationTemp.EndTime = endTime360
				evaluationTemp.Executor = domain.StaffDesc{
					UserId:   int(val2.Id),
					Account:  val2.Account,
					UserName: val2.Name,
				}
				evaluationTemp.Types = domain.Evaluation360
				//确定人资评估
				newEvaluationList = append(newEvaluationList, evaluationTemp)
			}
		}
		//处理人资评估
		{
			if hrbpExist {
				//处理人资评估
287 288
				evaluationTemp.BeginTime = beginTimeHr
				evaluationTemp.EndTime = endTimeHr
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
				evaluationTemp.Executor = domain.StaffDesc{}
				evaluationTemp.Types = domain.EvaluationHrbp
				newEvaluationList = append(newEvaluationList, evaluationTemp)
			}
		}
		//处理上级评估
		{
			superUser, _ := se.getUserData(userRepo, targetUser.ParentId)
			if superUser != nil {
				evaluationTemp.Types = domain.EvaluationSuper
				evaluationTemp.Executor = domain.StaffDesc{
					UserId:   int(superUser.Id),
					Account:  superUser.Account,
					UserName: superUser.Name,
				}
				evaluationTemp.BeginTime = beginTimeSuper
				evaluationTemp.EndTime = endTimeSuper
				//确定上级评估
				newEvaluationList = append(newEvaluationList, evaluationTemp)
			}
		}
		//综合考评结果
		{
			evaluationTemp.Types = domain.EvaluationFinish
			evaluationTemp.Executor = domain.StaffDesc{}
314 315
			evaluationTemp.BeginTime = beginTimeFinish
			evaluationTemp.EndTime = endTimeFinish
316 317 318 319 320 321 322
			newEvaluationList = append(newEvaluationList, evaluationTemp)
		}
	}
	summaryEvaluationRepo := factory.CreateSummaryEvaluationRepository(map[string]interface{}{"transactionContext": transactionContext})
	for i := range newEvaluationList {
		err = summaryEvaluationRepo.Save(&newEvaluationList[i])
		if err != nil {
tangxvhui authored
323
			return nil, fmt.Errorf("保存周期综合评估%s", err)
324 325 326 327 328 329
		}
	}
	//回填项目的状态
	projectDao := dao.NewEvaluationProjectDao(map[string]interface{}{"transactionContext": transactionContext})
	err = projectDao.UpdateSummaryState(projectParam.Id, domain.ProjectSummaryStateYes)
	if err != nil {
tangxvhui authored
330
		return nil, fmt.Errorf("保存项目状态%s", err)
331
	}
tangxvhui authored
332
	return newEvaluationList, nil
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
}

// 获取用户数据
func (se *summaryEvaluationPublisher) getUserData(userRepo domain.UserRepository, userId int64) (*domain.User, error) {
	if userId == 0 {
		return nil, nil
	}
	var userData *domain.User
	if val, ok := se.userCache[userId]; ok {
		userData = val
	} else {
		_, userList, err := userRepo.Find(map[string]interface{}{"id": userId})
		if err != nil {
			return nil, err
		}
		if len(userList) == 0 {
			return nil, nil
		}
		userData = userList[0]
	}
	return userData, nil
}

// 获取部门数据
func (se *summaryEvaluationPublisher) getDepartmentData(departmentRepo domain.DepartmentRepository, departmentIds []int) ([]*domain.Department, error) {
	departmentList := []*domain.Department{}
	for _, departmentId := range departmentIds {
		if val, ok := se.departCache[departmentId]; ok {
			departmentList = append(departmentList, val)
		} else {
			_, departments, err := departmentRepo.Find(map[string]interface{}{"id": departmentId})
			if err != nil {
				return nil, err
			}
			if len(departmentList) == 0 {
				continue
			}
			departmentList = append(departmentList, departments[0])
		}
	}
	return departmentList, nil
}