create_template.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package data_import
  2. import (
  3. "adm-management/errors"
  4. "adm-management/model"
  5. v1 "adm-management/pb/v1"
  6. "context"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "encoding/json"
  11. "fmt"
  12. "git.getensh.com/common/gopkgsv2/database"
  13. "git.getensh.com/common/gopkgsv2/logger"
  14. "go.uber.org/zap"
  15. "google.golang.org/grpc/status"
  16. "gorm.io/gorm"
  17. )
  18. func CreateTemplate(ctx context.Context, req *v1.CreateTemplateRequest) (reply *v1.CreateTemplateReply, err error) {
  19. reply = &v1.CreateTemplateReply{}
  20. defer func() {
  21. if r := recover(); r != nil {
  22. err = fmt.Errorf("%+v", r)
  23. e := &status.Status{}
  24. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  25. logger.Error("err",
  26. zap.String("system_err", err.Error()),
  27. zap.Stack("stacktrace"))
  28. }
  29. }
  30. }()
  31. if len(req.TemplateName) < 1 || len(req.Request) < 1 || len(req.TaskName) < 1 {
  32. return reply, errors.ParamsError
  33. }
  34. db := database.DB()
  35. // 遍历任务名改为任务id
  36. var taskIds string
  37. var ids []string
  38. for _, i := range req.TaskName {
  39. tasks, err := model.NewTaskList().Get(db.Where("task_name = ?", i))
  40. if err != nil && err != gorm.ErrRecordNotFound {
  41. return nil, err
  42. }
  43. if err == gorm.ErrRecordNotFound {
  44. fmt.Println("not found")
  45. return nil, err
  46. }
  47. ids = append(ids, strconv.Itoa(int(tasks.TaskId)))
  48. }
  49. taskIds = strings.Join(ids, ",")
  50. requests := strings.Join(req.Request, ",")
  51. createAt := time.Now().Unix()
  52. var count int
  53. err = db.Raw("SELECT count(*) FROM t_adm_data_template where request = ? and task_ids = ? ", requests, taskIds).Find(&count).Error
  54. if count > 0 {
  55. return reply, errors.TemplateAlreadyExists
  56. }
  57. err = db.Exec("INSERT INTO t_adm_data_template(`template_name`, `request`, `task_ids`, `created_at`, `updated_at`) VALUES(?,?,?,?,?)", req.TemplateName, requests, taskIds, createAt, createAt).Error
  58. if err != nil {
  59. if err == gorm.ErrRecordNotFound {
  60. return reply, nil
  61. }
  62. return reply, errors.SystemError
  63. }
  64. return reply, err
  65. }