batch_update_label_relationships_logic.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. package label_relationship
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/suyuan32/simple-admin-common/msg/errormsg"
  6. "wechat-api/ent"
  7. "wechat-api/ent/contact"
  8. "wechat-api/ent/custom_types"
  9. "wechat-api/ent/labelrelationship"
  10. "wechat-api/ent/messagerecords"
  11. "wechat-api/ent/soptask"
  12. "wechat-api/internal/svc"
  13. "wechat-api/internal/types"
  14. "wechat-api/internal/utils/dberrorhandler"
  15. "github.com/zeromicro/go-zero/core/logx"
  16. )
  17. type BatchUpdateLabelRelationshipsLogic struct {
  18. logx.Logger
  19. ctx context.Context
  20. svcCtx *svc.ServiceContext
  21. }
  22. func NewBatchUpdateLabelRelationshipsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BatchUpdateLabelRelationshipsLogic {
  23. return &BatchUpdateLabelRelationshipsLogic{
  24. Logger: logx.WithContext(ctx),
  25. ctx: ctx,
  26. svcCtx: svcCtx}
  27. }
  28. func (l *BatchUpdateLabelRelationshipsLogic) BatchUpdateLabelRelationships(req *types.BatchLabelRelationshipsInfo) (resp *types.BaseMsgResp, err error) {
  29. organizationId := l.ctx.Value("organizationId").(uint64)
  30. // 遍历所有联系人
  31. for _, contactId := range req.ContactIds {
  32. // 开始事务
  33. tx, err := l.svcCtx.DB.Tx(context.Background())
  34. if err != nil {
  35. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  36. }
  37. // 获取联系人信息
  38. c, err := tx.Contact.Query().Where(contact.ID(contactId), contact.OrganizationIDEQ(organizationId)).Only(l.ctx)
  39. // 获取联系人当前已关联的标签
  40. currentLabelRelationships, err := tx.LabelRelationship.Query().Where(labelrelationship.ContactID(contactId)).All(l.ctx)
  41. if err != nil {
  42. _ = tx.Rollback()
  43. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  44. }
  45. // 提取当前标签ID
  46. var currentLabelIds []uint64
  47. for _, relationship := range currentLabelRelationships {
  48. currentLabelIds = append(currentLabelIds, relationship.LabelID)
  49. }
  50. // 对比新旧标签ID,找出需要新增和移除的标签
  51. changeLabelIds, finalLabelIds := compareLabelIdsForIncrement(req.LabelIds, currentLabelIds, req.UpdateType)
  52. // 如果 req.UpdateType 为空,或 req.UpdateType 的值为 “all” 时
  53. if req.UpdateType == -1 {
  54. // 删除需要移除的标签关系
  55. for _, id := range changeLabelIds {
  56. _, err := tx.LabelRelationship.
  57. Delete().
  58. Where(
  59. labelrelationship.ContactID(contactId),
  60. labelrelationship.LabelID(id),
  61. ).
  62. Exec(l.ctx)
  63. if err != nil {
  64. _ = tx.Rollback()
  65. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  66. }
  67. }
  68. } else {
  69. // 创建需要新增的标签关系
  70. for _, id := range changeLabelIds {
  71. _, _ = tx.LabelRelationship.Create().
  72. SetLabelID(id).
  73. SetContactID(contactId).
  74. SetOrganizationID(organizationId).
  75. Save(l.ctx)
  76. //if err != nil {
  77. // return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  78. //}
  79. }
  80. }
  81. // 获取所有 status 为 3 且 bot_wxid_list 包含 c.wx_wxid 的 sop_task
  82. sopTasks, err := tx.SopTask.Query().Where(soptask.Status(3), soptask.OrganizationIDEQ(organizationId)).All(l.ctx)
  83. if err != nil {
  84. _ = tx.Rollback()
  85. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  86. }
  87. var filteredSopTasks []*ent.SopTask
  88. for _, task := range sopTasks {
  89. for _, botWxid := range task.BotWxidList {
  90. if botWxid == c.WxWxid {
  91. filteredSopTasks = append(filteredSopTasks, task)
  92. break
  93. }
  94. }
  95. }
  96. // 获取所有 filteredSopTasks 的 sop_stages
  97. var sopStages []*ent.SopStage
  98. for _, task := range filteredSopTasks {
  99. stages, err := task.QueryTaskStages().All(l.ctx)
  100. if err != nil {
  101. _ = tx.Rollback()
  102. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  103. }
  104. sopStages = append(sopStages, stages...)
  105. }
  106. err = AddLabelRelationships(tx, sopStages, *c, finalLabelIds, organizationId, l.ctx, l.Logger)
  107. if err != nil {
  108. _ = tx.Rollback()
  109. return nil, err
  110. }
  111. // 所有操作成功,提交事务
  112. err = tx.Commit()
  113. if err != nil {
  114. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  115. }
  116. }
  117. return &types.BaseMsgResp{Msg: errormsg.UpdateSuccess}, nil
  118. }
  119. func AddLabelRelationships(tx *ent.Tx, sopStages []*ent.SopStage, contact ent.Contact, currentLabelIds []uint64, organizationId uint64, ctx context.Context, logger logx.Logger) (err error) {
  120. for _, stage := range sopStages {
  121. if stage.ConditionType == 1 && isLabelIdListMatchFilter(currentLabelIds, stage.ConditionOperator, stage.ConditionList) {
  122. // 判断是否有 contact_wxid、source_type、source_id、sub_source_id 相同的记录
  123. _, err = tx.MessageRecords.Query().
  124. Where(
  125. messagerecords.ContactWxid(contact.Wxid),
  126. messagerecords.SourceType(3),
  127. messagerecords.SourceID(stage.ID),
  128. messagerecords.SubSourceID(0),
  129. ).
  130. Only(ctx)
  131. if err == nil {
  132. continue
  133. }
  134. // 判断ActionMessage是否为空
  135. sourceType := 3
  136. if stage.ActionMessage != nil {
  137. for i, message := range stage.ActionMessage {
  138. meta := custom_types.Meta{}
  139. if message.Meta != nil {
  140. meta.Filename = message.Meta.Filename
  141. }
  142. _, _ = tx.MessageRecords.Create().
  143. SetNotNilBotWxid(&contact.WxWxid).
  144. SetNotNilContactID(&contact.ID).
  145. SetNotNilContactType(&contact.Type).
  146. SetNotNilContactWxid(&contact.Wxid).
  147. SetNotNilContentType(&message.Type).
  148. SetNotNilContent(&message.Content).
  149. SetMeta(meta).
  150. SetNotNilSourceType(&sourceType).
  151. SetNotNilSourceID(&stage.ID).
  152. SetSubSourceID(uint64(i)).
  153. SetOrganizationID(organizationId).
  154. Save(ctx)
  155. //if err != nil {
  156. // return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  157. //}
  158. }
  159. }
  160. if stage.ActionLabel != nil {
  161. fmt.Printf("---------------stage.ActionLabel----------------: %+v\n\n", stage.ActionLabel)
  162. // 获取 addLabelIds 中不在 currentLabelIds 中的标签ID
  163. var newLabelIds []uint64
  164. // 创建一个映射,用于快速查找 currentLabelIds 中的元素
  165. currentLabelIdSet := make(map[uint64]struct{})
  166. for _, id := range currentLabelIds {
  167. currentLabelIdSet[id] = struct{}{}
  168. }
  169. // 遍历 addLabelIds,找出不在 currentLabelIds 中的元素
  170. for _, id := range stage.ActionLabel {
  171. if _, exists := currentLabelIdSet[id]; !exists {
  172. newLabelIds = append(newLabelIds, id)
  173. }
  174. }
  175. if len(newLabelIds) == 0 {
  176. return nil
  177. }
  178. // 创建需要新增的标签关系
  179. fmt.Printf("---------------newLabelIds----------------: %+v\n\n", newLabelIds)
  180. for _, id := range newLabelIds {
  181. _, err = tx.LabelRelationship.Create().
  182. SetLabelID(id).
  183. SetContactID(contact.ID).
  184. SetOrganizationID(organizationId).
  185. Save(ctx)
  186. if err != nil {
  187. fmt.Printf("---------------err----------------: %+v\n\n", err)
  188. }
  189. }
  190. // 合并 currentLabelIds 和 newLabelIds
  191. currentLabelIds = append(currentLabelIds, newLabelIds...)
  192. // 递归调用 AddLabelRelationships
  193. _ = AddLabelRelationships(tx, sopStages, contact, currentLabelIds, organizationId, ctx, logger)
  194. return
  195. }
  196. }
  197. }
  198. // 所有操作成功,提交事务
  199. //err = tx.Commit()
  200. //if err != nil {
  201. // return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  202. //}
  203. return nil
  204. }
  205. // compareLabelIds compares the new label ids with the current ones and returns the ids to be added and removed
  206. func compareLabelIdsForIncrement(newLabelIds []uint64, currentLabelIds []uint64, updateType int) (changeLabelIds []uint64, finalLabelIds []uint64) {
  207. currentLabelIdsSet := make(map[uint64]struct{}, len(currentLabelIds))
  208. for _, id := range currentLabelIds {
  209. currentLabelIdsSet[id] = struct{}{}
  210. }
  211. for _, id := range newLabelIds {
  212. if updateType == 1 {
  213. if _, ok := currentLabelIdsSet[id]; ok {
  214. delete(currentLabelIdsSet, id)
  215. } else {
  216. changeLabelIds = append(changeLabelIds, id)
  217. finalLabelIds = append(finalLabelIds, id)
  218. }
  219. } else {
  220. if _, ok := currentLabelIdsSet[id]; ok {
  221. delete(currentLabelIdsSet, id)
  222. changeLabelIds = append(changeLabelIds, id)
  223. }
  224. }
  225. }
  226. for id := range currentLabelIdsSet {
  227. finalLabelIds = append(finalLabelIds, id)
  228. }
  229. return
  230. }