task.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package task
  2. import (
  3. logger "eta/eta_mini_ht_api/common/component/log"
  4. "eta/eta_mini_ht_api/models"
  5. "gorm.io/gorm"
  6. "time"
  7. )
  8. // VerificationStatus is an enumeration for the status field.
  9. type TaskStatus string
  10. const (
  11. StatusPending TaskStatus = "PENDING"
  12. StatusProcess TaskStatus = "PROGRESS"
  13. StatusSuccess TaskStatus = "SUCCESS"
  14. StatusFailed TaskStatus = "FAILED"
  15. )
  16. type Task struct {
  17. ID int `gorm:"primary_key;auto_increment;comment:'主键'"`
  18. TaskType string `gorm:"type:enum('');default:null;comment:'任务类型'"`
  19. Details string `gorm:"type:json;default:null;comment:'任务详情'"`
  20. Status TaskStatus `gorm:"type:enum('PENDING','PROGRESS','SUCCESS','FAILED');not null;comment:'任务状态'"`
  21. CreatedTime time.Time `gorm:"default:null;comment:'创建时间'"`
  22. UpdatedTime time.Time `gorm:"default:null;comment:'更新时间'"`
  23. }
  24. // 在使用前,需要注册 Enum 类型
  25. func (v *Task) BeforeCreate(_ *gorm.DB) (err error) {
  26. v.CreatedTime = time.Now()
  27. if v.Status == "" {
  28. v.Status = StatusPending
  29. }
  30. return
  31. }
  32. func InitTask(task Task) (taskId int, err error) {
  33. err = models.Main().Create(&task).Error
  34. if err != nil {
  35. logger.Error("创建任务记录失败:%v", err)
  36. }
  37. taskId = task.ID
  38. return
  39. }
  40. func UpdateTaskStatusById(taskId int, status TaskStatus) (err error) {
  41. err = updateColumnById(taskId, "status", status)
  42. if err != nil {
  43. logger.Error("修改任务状态失败,id:[%d],状态:%v:%v", taskId, status, err)
  44. }
  45. return
  46. }
  47. func UpdateDetailsAndStatusById(taskId int, status TaskStatus, details string) {
  48. columns := map[string]interface{}{
  49. "details": details,
  50. "status": status,
  51. }
  52. err := updateColumnsById(taskId, columns)
  53. if err != nil {
  54. logger.Error("修改任务失败,id:[%d]:%v", taskId, err)
  55. }
  56. return
  57. }
  58. func updateColumnsById(id int, value interface{}) (err error) {
  59. err = models.Main().Model(&Task{}).Where("id =?", id).UpdateColumns(value).Error
  60. return
  61. }
  62. func updateColumnById(id int, column string, value interface{}) (err error) {
  63. err = models.Main().Model(&Task{}).Where("id =?", id).UpdateColumn(column, value).Error
  64. return
  65. }