log_opt.go 8.0 KB
package log_opt

import (
	"fmt"
	"github.com/linmadan/egglib-go/core/application"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/factory"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/log"
	"strconv"
	"time"
)

func CreateTask(u *domain.UserAuth, task domain.Task) error {
	transactionContext, err := factory.StartTransaction()
	if err != nil {
		return err
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
		if err := recover(); err != nil {
			log.Logger.Error(application.ThrowError(application.BUSINESS_ERROR, fmt.Sprintf("创建任务日志异常:%s", err)).Error())
		}
	}()
	logOptRepo := factory.CreateLogOptRepository(map[string]interface{}{"transactionContext": transactionContext})

	logOpt := createdLogOpt(u, strconv.Itoa(task.Id))
	logOpt.OptMethod = domain.CREATE
	logOpt.OptField = "创建了任务"
	logOpt.OptValue = task.Alias

	_, err = logOptRepo.Insert(logOpt)
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	return nil
}

func UpdateTask(u *domain.UserAuth,
	srcTask *domain.Task,
	newTask *domain.Task,
	srcStage []*domain.TaskStage,
	newStage []*domain.TaskStage,
) error {
	transactionContext, err := factory.StartTransaction()
	if err != nil {
		return err
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
		if err := recover(); err != nil {
			log.Logger.Error(application.ThrowError(application.BUSINESS_ERROR, fmt.Sprintf("更新任务日志异常:%s", err)).Error())
		}
	}()
	logOptRepo := factory.CreateLogOptRepository(map[string]interface{}{"transactionContext": transactionContext})

	var logArray = compareTask(u, srcTask, newTask)
	var logArray2 = compareStage(u, newTask.Id, srcStage, newStage)
	logArray = append(logArray, logArray2...)
	if len(logArray) == 0 {
		return nil
	}
	for _, v := range logArray {
		_, err = logOptRepo.Insert(v)
		if err != nil {
			return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
		}
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	return nil
}

func compareTask(u *domain.UserAuth, srcTask *domain.Task, newTask *domain.Task) []*domain.LogOpt {
	var taskId = strconv.Itoa(newTask.Id)
	logArray := make([]*domain.LogOpt, 0)
	if srcTask.Alias != newTask.Alias {
		logOpt := createdLogOpt(u, taskId)
		logOpt.OptField = "修改了任务名称"
		logOpt.OptValue = newTask.Alias
		logArray = append(logArray, logOpt)
	}

	if srcTask.EndTime != newTask.EndTime {
		logOpt := createdLogOpt(u, taskId)
		logOpt.OptField = "修改了任务截止时间"
		if newTask.EndTime == 0 {
			logOpt.OptValue = "未设置时间"
		} else {
			logOpt.OptValue = time.Unix(newTask.EndTime, 0).Local().Format("2006-01-02")
			//logOpt.OptValue = time.Unix(newTask.EndTime, 0).Local().Format("2006-01-02 15:04:05")
		}
		logArray = append(logArray, logOpt)
	}

	if srcTask.UseEndTime != newTask.UseEndTime {
		logOpt := createdLogOpt(u, taskId)
		logOpt.OptField = "修改了任务截止时间应用到日评中"
		if newTask.UseEndTime == 0 {
			logOpt.OptValue = "不应用"
		} else {
			logOpt.OptValue = "应用"
		}
		logArray = append(logArray, logOpt)
	}

	if srcTask.LevelName != newTask.LevelName {
		logOpt := createdLogOpt(u, taskId)
		logOpt.OptField = "修改了任务类型"
		logOpt.OptValue = newTask.LevelName
		logArray = append(logArray, logOpt)
	}

	if srcTask.SortBy != newTask.SortBy {
		logOpt := createdLogOpt(u, taskId)
		logOpt.OptField = "修改了任务优先级"
		logOpt.OptValue = newTask.SortBy.Named()
		logArray = append(logArray, logOpt)
	}

	if srcTask.AssistFlagMax != newTask.AssistFlagMax {
		logOpt := createdLogOpt(u, taskId)
		logOpt.OptField = "修改了上级辅导时间"
		logOpt.OptValue = strconv.Itoa(newTask.AssistFlagMax) + "天"
		logArray = append(logArray, logOpt)
	}

	// 新的任务相关方
	uidNewMap := map[int]int{}
	for _, id := range newTask.RelatedUser {
		uidNewMap[id] = id
	}
	// 被移除的任务相关方
	removedIds := make([]int, 0)
	for _, id := range srcTask.RelatedUser {
		if _, ok := uidNewMap[id]; ok {
			delete(uidNewMap, id) // 删除后,剩余的都是新增的
		} else {
			removedIds = append(removedIds, id)
		}
	}

	// 变动的任务相关方
	changeIds := make([]int, 0)
	for _, v := range removedIds {
		changeIds = append(changeIds, v)
	}
	for _, v := range uidNewMap {
		changeIds = append(changeIds, v)
	}
	userMap, _ := getUserMap(changeIds)

	for _, v := range removedIds {
		logOpt := createdLogOpt(u, taskId)
		logOpt.OptMethod = domain.DELETE
		logOpt.OptField = "移除了任务相关方"
		if v, ok := userMap[v]; ok {
			logOpt.OptValue = v.Name
		}
		logArray = append(logArray, logOpt)
	}

	for _, v := range uidNewMap {
		logOpt := createdLogOpt(u, taskId)
		logOpt.OptMethod = domain.CREATE
		logOpt.OptField = "添加了任务相关方"
		if v, ok := userMap[v]; ok {
			logOpt.OptValue = v.Name
		}
		logArray = append(logArray, logOpt)
	}

	return logArray
}

func compareStage(u *domain.UserAuth, id int, srcStage []*domain.TaskStage, newStage []*domain.TaskStage) []*domain.LogOpt {
	taskId := strconv.Itoa(id)
	logArray := make([]*domain.LogOpt, 0)
	srcMap := map[int]*domain.TaskStage{}
	for i := range srcStage {
		it := srcStage[i]
		srcMap[it.Id] = it
	}

	for i := range newStage {
		it := newStage[i]
		if it.DeletedAt != nil {
			logOpt := createdLogOpt(u, taskId)
			logOpt.OptMethod = domain.DELETE
			logOpt.OptField = "删除了里程碑"
			logOpt.OptValue = it.Name
			logArray = append(logArray, logOpt)
			continue
		}

		// 新旧比对
		if v, ok := srcMap[it.Id]; ok {
			if it.Name != v.Name {
				logOpt := createdLogOpt(u, taskId)
				logOpt.OptField = "修改了里程碑名称"
				logOpt.OptValue = it.Name
				logArray = append(logArray, logOpt)
			}
			if it.PlanCompletedAt != v.PlanCompletedAt {
				logOpt := createdLogOpt(u, taskId)
				logOpt.OptField = "修改了里程碑" + it.Name + "的计划完成时间"
				if it.PlanCompletedAt == 0 {
					logOpt.OptValue = "未设置时间"
				} else {
					logOpt.OptValue = time.Unix(it.PlanCompletedAt, 0).Local().Format("2006-01-02")
					//logOpt.OptValue = time.Unix(it.PlanCompletedAt, 0).Local().Format("2006-01-02 15:04:05")
				}
				logArray = append(logArray, logOpt)
			}
		} else {
			logOpt := createdLogOpt(u, taskId)
			logOpt.OptMethod = domain.CREATE
			logOpt.OptField = "创建了里程碑"
			logOpt.OptValue = it.Name
			logArray = append(logArray, logOpt)
		}
	}

	return logArray
}

func getUserMap(ids []int) (map[int]*domain.User, error) {
	userMap := map[int]*domain.User{}
	if len(ids) == 0 {
		return userMap, nil
	}

	transactionContext, err := factory.StartTransaction()
	if err != nil {
		return userMap, err
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()

	userRepo := factory.CreateUserRepository(map[string]interface{}{"transactionContext": transactionContext})
	_, users, err := userRepo.Find(map[string]interface{}{"ids": ids, "limit": len(ids)})
	if err != nil {
		return userMap, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}

	for i := range users {
		user := users[i]
		userMap[int(user.Id)] = user
	}
	return userMap, nil
}

func createdLogOpt(u *domain.UserAuth, taskId string) *domain.LogOpt {
	var createdAt = time.Now()
	var updatedAt = createdAt
	operator := domain.StaffDesc{
		UserId:      int(u.UserId),
		CompanyName: u.CompanyName,
		Account:     u.Phone,
		UserName:    u.Name,
	}
	return &domain.LogOpt{
		Id:          0,
		CompanyId:   int(u.CompanyId),
		Operator:    operator,
		OptMethod:   domain.UPDATE,
		OptTargetId: taskId,
		OptField:    "",
		OptValue:    "",
		CreatedAt:   createdAt,
		UpdatedAt:   updatedAt,
	}
}