update_label_relationships_logic.go 8.2 KB

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