tag.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package service
  2. import (
  3. "github.com/lejianwen/rustdesk-api/v2/global"
  4. "github.com/lejianwen/rustdesk-api/v2/model"
  5. "gorm.io/gorm"
  6. )
  7. type TagService struct {
  8. }
  9. func (s *TagService) Info(id uint) *model.Tag {
  10. p := &model.Tag{}
  11. global.DB.Where("id = ?", id).First(p)
  12. return p
  13. }
  14. func (s *TagService) InfoByUserIdAndNameAndCollectionId(userid uint, name string, cid uint) *model.Tag {
  15. p := &model.Tag{}
  16. global.DB.Where("user_id = ? and name = ? and collection_id = ?", userid, name, cid).First(p)
  17. return p
  18. }
  19. func (s *TagService) ListByUserId(userId uint) (res *model.TagList) {
  20. res = s.List(1, 1000, func(tx *gorm.DB) {
  21. tx.Where("user_id = ?", userId)
  22. })
  23. return
  24. }
  25. func (s *TagService) ListByUserIdAndCollectionId(userId, cid uint) (res *model.TagList) {
  26. res = s.List(1, 1000, func(tx *gorm.DB) {
  27. tx.Where("user_id = ? and collection_id = ?", userId, cid)
  28. tx.Order("name asc")
  29. })
  30. return
  31. }
  32. func (s *TagService) UpdateTags(userId uint, tags map[string]uint) {
  33. tx := global.DB.Begin()
  34. //先查询所有tag
  35. var allTags []*model.Tag
  36. tx.Where("user_id = ?", userId).Find(&allTags)
  37. for _, t := range allTags {
  38. if _, ok := tags[t.Name]; !ok {
  39. //删除
  40. tx.Delete(t)
  41. } else {
  42. if tags[t.Name] != t.Color {
  43. //更新
  44. t.Color = tags[t.Name]
  45. tx.Save(t)
  46. }
  47. //移除
  48. delete(tags, t.Name)
  49. }
  50. }
  51. //新增
  52. for tag, color := range tags {
  53. t := &model.Tag{}
  54. t.Name = tag
  55. t.Color = color
  56. t.UserId = userId
  57. tx.Create(t)
  58. }
  59. tx.Commit()
  60. }
  61. // InfoById 根据用户id取用户信息
  62. func (s *TagService) InfoById(id uint) *model.Tag {
  63. u := &model.Tag{}
  64. global.DB.Where("id = ?", id).First(u)
  65. return u
  66. }
  67. func (s *TagService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *model.TagList) {
  68. res = &model.TagList{}
  69. res.Page = int64(page)
  70. res.PageSize = int64(pageSize)
  71. tx := global.DB.Model(&model.Tag{})
  72. if where != nil {
  73. where(tx)
  74. }
  75. tx.Count(&res.Total)
  76. tx.Scopes(Paginate(page, pageSize))
  77. tx.Find(&res.Tags)
  78. return
  79. }
  80. // Create 创建
  81. func (s *TagService) Create(u *model.Tag) error {
  82. res := global.DB.Create(u).Error
  83. return res
  84. }
  85. func (s *TagService) Delete(u *model.Tag) error {
  86. return global.DB.Delete(u).Error
  87. }
  88. // Update 更新
  89. func (s *TagService) Update(u *model.Tag) error {
  90. return global.DB.Model(u).Select("*").Omit("created_at").Updates(u).Error
  91. }