update_label_relationships_logic.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. package label_relationship
  2. import (
  3. "context"
  4. "github.com/suyuan32/simple-admin-common/msg/errormsg"
  5. "regexp"
  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. // 所有操作成功,提交事务
  104. err = tx.Commit()
  105. if err != nil {
  106. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  107. }
  108. err = l.AddLabelRelationships(sopStages, *c, req.LabelIds, organizationId)
  109. if err != nil {
  110. return nil, err
  111. }
  112. return &types.BaseMsgResp{Msg: errormsg.UpdateSuccess}, nil
  113. }
  114. func (l *UpdateLabelRelationshipsLogic) AddLabelRelationships(sopStages []*ent.SopStage, contact ent.Contact, currentLabelIds []uint64, organizationId uint64) (err error) {
  115. // 遍历 sop_stages,找出满足条件的 stage
  116. for _, stage := range sopStages {
  117. if stage.ConditionType == 1 && isLabelIdListMatchFilter(currentLabelIds, stage.ConditionOperator, stage.ConditionList) {
  118. // 开始事务
  119. tx, err := l.svcCtx.DB.Tx(context.Background())
  120. if err != nil {
  121. return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  122. }
  123. // 判断是否有 contact_wxid、source_type、source_id、sub_source_id 相同的记录
  124. _, err = tx.MessageRecords.Query().
  125. Where(
  126. messagerecords.ContactWxid(contact.Wxid),
  127. messagerecords.SourceType(3),
  128. messagerecords.SourceID(stage.ID),
  129. messagerecords.SubSourceID(0),
  130. ).
  131. Only(l.ctx)
  132. if err == nil {
  133. continue
  134. }
  135. // 判断ActionMessage是否为空
  136. sourceType := 3
  137. if stage.ActionMessage != nil {
  138. for i, message := range stage.ActionMessage {
  139. meta := custom_types.Meta{}
  140. if message.Meta != nil {
  141. meta.Filename = message.Meta.Filename
  142. }
  143. _, err = tx.MessageRecords.Create().
  144. SetNotNilBotWxid(&contact.WxWxid).
  145. SetNotNilContactID(&contact.ID).
  146. SetNotNilContactType(&contact.Type).
  147. SetNotNilContactWxid(&contact.Wxid).
  148. SetNotNilContentType(&message.Type).
  149. SetNotNilContent(&message.Content).
  150. SetMeta(meta).
  151. SetNotNilSourceType(&sourceType).
  152. SetNotNilSourceID(&stage.ID).
  153. SetSubSourceID(uint64(i)).
  154. SetOrganizationID(organizationId).
  155. Save(l.ctx)
  156. if err != nil {
  157. _ = tx.Rollback()
  158. return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  159. }
  160. }
  161. }
  162. if stage.ActionForward != nil {
  163. if stage.ActionForward.Wxid != "" {
  164. forwardWxids := splitString(stage.ActionForward.Wxid)
  165. for _, forwardWxid := range forwardWxids {
  166. for i, message := range stage.ActionForward.Action {
  167. meta := custom_types.Meta{}
  168. if message.Meta != nil {
  169. meta.Filename = message.Meta.Filename
  170. }
  171. _, err = tx.MessageRecords.Create().
  172. SetBotWxid(contact.WxWxid).
  173. SetContactID(0).
  174. SetContactType(0).
  175. SetContactWxid(forwardWxid).
  176. SetContentType(message.Type).
  177. SetContent(message.Content).
  178. SetMeta(meta).
  179. SetSourceType(sourceType).
  180. SetSourceID(stage.ID).
  181. SetSubSourceID(contact.ID + uint64(i)).
  182. SetOrganizationID(organizationId).
  183. Save(l.ctx)
  184. if err != nil {
  185. _ = tx.Rollback()
  186. return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  187. }
  188. }
  189. }
  190. }
  191. }
  192. if stage.ActionLabelAdd != nil || stage.ActionLabelDel != nil {
  193. // 获取 addLabelIds 中不在 currentLabelIds 中的标签ID
  194. var newLabelIds []uint64
  195. var remLabelIds []uint64
  196. var finalLabelIds []uint64
  197. // 创建一个映射,用于快速查找 currentLabelIds 中的元素
  198. currentLabelIdSet := make(map[uint64]struct{})
  199. for _, id := range currentLabelIds {
  200. currentLabelIdSet[id] = struct{}{}
  201. }
  202. delLabelIdSet := make(map[uint64]struct{})
  203. for _, id := range stage.ActionLabelDel {
  204. delLabelIdSet[id] = struct{}{}
  205. }
  206. if stage.ActionLabelAdd != nil {
  207. // 遍历 addLabelIds,找出不在 currentLabelIds 中的元素
  208. for _, id := range stage.ActionLabelAdd {
  209. if _, ce := currentLabelIdSet[id]; !ce {
  210. if _, re := delLabelIdSet[id]; !re {
  211. newLabelIds = append(newLabelIds, id)
  212. }
  213. }
  214. }
  215. if len(newLabelIds) > 0 {
  216. // 创建需要新增的标签关系
  217. for _, id := range newLabelIds {
  218. _, err = tx.LabelRelationship.Create().
  219. SetLabelID(id).
  220. SetContactID(contact.ID).
  221. SetOrganizationID(organizationId).
  222. Save(l.ctx)
  223. if err != nil {
  224. _ = tx.Rollback()
  225. return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  226. }
  227. }
  228. }
  229. // 合并 currentLabelIds 和 newLabelIds
  230. currentLabelIds = append(currentLabelIds, newLabelIds...)
  231. }
  232. if stage.ActionLabelDel != nil {
  233. // 遍历 delLabelIds,找出在 currentLabelIds 中的元素
  234. for _, id := range stage.ActionLabelDel {
  235. if _, exists := currentLabelIdSet[id]; exists {
  236. remLabelIds = append(newLabelIds, id)
  237. delete(currentLabelIdSet, id)
  238. }
  239. }
  240. if len(remLabelIds) > 0 {
  241. _, err = tx.LabelRelationship.Delete().Where(labelrelationship.IDIn(remLabelIds...), labelrelationship.ContactIDEQ(contact.ID), labelrelationship.OrganizationIDEQ(organizationId)).Exec(l.ctx)
  242. if err != nil {
  243. //_ = tx.Rollback()
  244. return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  245. }
  246. }
  247. }
  248. // 所有操作成功,提交事务
  249. err = tx.Commit()
  250. if err != nil {
  251. return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  252. }
  253. if len(newLabelIds) == 0 && len(remLabelIds) == 0 {
  254. return nil
  255. }
  256. for id := range currentLabelIdSet {
  257. finalLabelIds = append(finalLabelIds, id)
  258. }
  259. // 递归调用 AddLabelRelationships
  260. err = l.AddLabelRelationships(sopStages, contact, finalLabelIds, organizationId)
  261. if err != nil {
  262. return err
  263. }
  264. return nil
  265. } else {
  266. // 所有操作成功,提交事务
  267. err = tx.Commit()
  268. if err != nil {
  269. return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  270. }
  271. }
  272. }
  273. }
  274. // 所有操作成功,提交事务
  275. //err = tx.Commit()
  276. //if err != nil {
  277. // return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  278. //}
  279. return nil
  280. }
  281. // compareLabelIds compares the new label ids with the current ones and returns the ids to be added and removed
  282. func compareLabelIds(newLabelIds []uint64, currentLabelIds []uint64) (addLabelIds []uint64, removeLabelIds []uint64) {
  283. newLabelIdSet := make(map[uint64]struct{}, len(newLabelIds))
  284. for _, id := range newLabelIds {
  285. newLabelIdSet[id] = struct{}{}
  286. }
  287. for _, id := range currentLabelIds {
  288. if _, ok := newLabelIdSet[id]; ok {
  289. delete(newLabelIdSet, id)
  290. } else {
  291. removeLabelIds = append(removeLabelIds, id)
  292. }
  293. }
  294. for id := range newLabelIdSet {
  295. addLabelIds = append(addLabelIds, id)
  296. }
  297. return
  298. }
  299. func isLabelIdListMatchFilter(labelIdList []uint64, conditionOperator int, conditionList []custom_types.Condition) bool {
  300. labelIdSet := make(map[uint64]struct{})
  301. for _, id := range labelIdList {
  302. labelIdSet[id] = struct{}{}
  303. }
  304. for _, condition := range conditionList {
  305. match := false
  306. for _, id := range condition.LabelIdList {
  307. if _, ok := labelIdSet[id]; ok {
  308. match = true
  309. break
  310. }
  311. }
  312. if condition.Equal == 2 {
  313. match = !match
  314. }
  315. if (conditionOperator == 1 && !match) || (conditionOperator == 2 && match) {
  316. return match
  317. }
  318. }
  319. return conditionOperator == 1
  320. }
  321. func splitString(input string) []string {
  322. // Define the regular expression pattern to match Chinese comma, English comma, and Chinese enumeration comma
  323. pattern := `[,,、]`
  324. re := regexp.MustCompile(pattern)
  325. // Split the input string based on the pattern
  326. return re.Split(input, -1)
  327. }