publish_sop_task_logic.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. package sop_task
  2. import (
  3. "context"
  4. "errors"
  5. "github.com/suyuan32/simple-admin-common/msg/errormsg"
  6. "regexp"
  7. "wechat-api/ent"
  8. "wechat-api/ent/contact"
  9. "wechat-api/ent/custom_types"
  10. "wechat-api/ent/labelrelationship"
  11. "wechat-api/ent/messagerecords"
  12. "wechat-api/ent/predicate"
  13. "wechat-api/ent/sopstage"
  14. "wechat-api/ent/soptask"
  15. "wechat-api/internal/utils/dberrorhandler"
  16. "wechat-api/internal/svc"
  17. "wechat-api/internal/types"
  18. "github.com/zeromicro/go-zero/core/logx"
  19. )
  20. type PublishSopTaskLogic struct {
  21. logx.Logger
  22. ctx context.Context
  23. svcCtx *svc.ServiceContext
  24. }
  25. func NewPublishSopTaskLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PublishSopTaskLogic {
  26. return &PublishSopTaskLogic{
  27. Logger: logx.WithContext(ctx),
  28. ctx: ctx,
  29. svcCtx: svcCtx}
  30. }
  31. func (l *PublishSopTaskLogic) PublishSopTask(req *types.IDReq) (resp *types.BaseMsgResp, err error) {
  32. organizationId := l.ctx.Value("organizationId").(uint64)
  33. // 开始事务
  34. //tx, err := l.svcCtx.DB.Tx(context.Background())
  35. //if err != nil {
  36. // return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  37. //}
  38. // 根据 id 查询 sop_task
  39. sopTask, err := l.svcCtx.DB.SopTask.Query().
  40. Where(
  41. soptask.ID(req.Id),
  42. soptask.Status(1),
  43. soptask.OrganizationIDEQ(organizationId),
  44. ).
  45. WithTaskStages().
  46. Only(l.ctx)
  47. if err != nil {
  48. //_ = tx.Rollback()
  49. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  50. }
  51. // 判断 sop_task 是否存在
  52. if sopTask != nil {
  53. if sopTask.BotWxidList == nil {
  54. return nil, errors.New(errormsg.ValidationError)
  55. }
  56. // 查询任务的所有 sop_stages
  57. err = l.svcCtx.DB.SopTask.UpdateOneID(req.Id).
  58. SetStatus(3).
  59. Exec(l.ctx)
  60. if err != nil {
  61. //_ = tx.Rollback()
  62. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  63. }
  64. sopStages, err := l.svcCtx.DB.SopStage.Query().
  65. Where(sopstage.HasSopTaskWith(soptask.OrganizationIDEQ(organizationId), soptask.StatusEQ(3), soptask.DeletedAtIsNil()), sopstage.DeletedAtIsNil()).
  66. All(l.ctx)
  67. if err != nil {
  68. //_ = tx.Rollback()
  69. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  70. }
  71. stageMap := make(map[uint64]*ent.SopStage)
  72. for _, stage := range sopStages {
  73. stageMap[stage.ID] = stage
  74. }
  75. // 遍历 stage
  76. for _, stage := range sopTask.Edges.TaskStages {
  77. if stage.ConditionType == 1 {
  78. // 构造查询条件
  79. var predicates []predicate.Contact
  80. for _, condition := range stage.ConditionList {
  81. subPredicate := contact.HasContactRelationshipsWith(
  82. labelrelationship.LabelIDIn(condition.LabelIdList...),
  83. labelrelationship.DeletedAtIsNil())
  84. labelrelationship.OrganizationIDEQ(organizationId)
  85. if condition.Equal == 2 {
  86. subPredicate = contact.Not(subPredicate)
  87. }
  88. predicates = append(predicates, subPredicate)
  89. }
  90. // 查询满足条件的联系人
  91. var contacts []*ent.Contact
  92. var err error
  93. sourceType := 3
  94. if stage.ConditionOperator == 1 {
  95. contacts, err = l.svcCtx.DB.Contact.Query().Where(contact.And(predicates...)).All(l.ctx)
  96. } else {
  97. contacts, err = l.svcCtx.DB.Contact.Query().Where(contact.Or(predicates...)).All(l.ctx)
  98. }
  99. if err != nil {
  100. //_ = tx.Rollback()
  101. return nil, err
  102. }
  103. // 遍历 contacts
  104. for _, c := range contacts {
  105. // 判断联系人所属微信是否包含在任务当中
  106. if sopTask.BotWxidList == nil || (sopTask.BotWxidList != nil && valueInArray(c.WxWxid, sopTask.BotWxidList)) {
  107. if stage.ActionMessage != nil {
  108. for i, message := range stage.ActionMessage {
  109. meta := custom_types.Meta{}
  110. if message.Meta != nil {
  111. meta.Filename = message.Meta.Filename
  112. }
  113. _, _ = l.svcCtx.DB.MessageRecords.Create().
  114. SetNotNilBotWxid(&c.WxWxid).
  115. SetNotNilContactID(&c.ID).
  116. SetNotNilContactType(&c.Type).
  117. SetNotNilContactWxid(&c.Wxid).
  118. SetNotNilContentType(&message.Type).
  119. SetNotNilContent(&message.Content).
  120. SetMeta(meta).
  121. SetNotNilSourceType(&sourceType).
  122. SetNotNilSourceID(&stage.ID).
  123. SetSubSourceID(uint64(i)).
  124. SetOrganizationID(organizationId).
  125. Save(l.ctx)
  126. //if err != nil {
  127. // return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  128. //}
  129. }
  130. }
  131. if stage.ActionForward != nil {
  132. if stage.ActionForward.Wxid != "" {
  133. forwardWxids := splitString(stage.ActionForward.Wxid)
  134. for _, forwardWxid := range forwardWxids {
  135. for i, message := range stage.ActionForward.Action {
  136. meta := custom_types.Meta{}
  137. if message.Meta != nil {
  138. meta.Filename = message.Meta.Filename
  139. }
  140. _, err = l.svcCtx.DB.MessageRecords.Create().
  141. SetBotWxid(c.WxWxid).
  142. SetContactID(0).
  143. SetContactType(0).
  144. SetContactWxid(forwardWxid).
  145. SetContentType(message.Type).
  146. SetContent(message.Content).
  147. SetMeta(meta).
  148. SetSourceType(sourceType).
  149. SetSourceID(stage.ID).
  150. SetSubSourceID(c.ID + uint64(i)).
  151. SetOrganizationID(organizationId).
  152. Save(l.ctx)
  153. }
  154. }
  155. }
  156. }
  157. // 查询当前联系人的标签关系
  158. currentLabelRelationships, err := l.svcCtx.DB.LabelRelationship.Query().Where(labelrelationship.ContactID(c.ID)).All(l.ctx)
  159. if err != nil {
  160. //_ = tx.Rollback()
  161. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  162. }
  163. // 提取当前标签ID
  164. var currentLabelIds []uint64
  165. for _, relationship := range currentLabelRelationships {
  166. currentLabelIds = append(currentLabelIds, relationship.LabelID)
  167. }
  168. if stage.ActionLabelAdd != nil || stage.ActionLabelDel != nil {
  169. // 递归调用 AddLabelRelationships
  170. err = l.AddLabelRelationships(stageMap, *c, currentLabelIds, stage.ActionLabelAdd, stage.ActionLabelDel, organizationId)
  171. if err != nil {
  172. //_ = tx.Rollback()
  173. return nil, err
  174. }
  175. }
  176. }
  177. }
  178. }
  179. }
  180. // 所有操作成功,提交事务
  181. //err = tx.Commit()
  182. //if err != nil {
  183. // return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  184. //}
  185. return &types.BaseMsgResp{Msg: errormsg.Success}, nil
  186. } else {
  187. // 所有操作成功,提交事务
  188. //err = tx.Commit()
  189. //if err != nil {
  190. // return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  191. //}
  192. //// 返回错误信息:任务不存在
  193. return nil, errors.New(errormsg.TargetNotFound)
  194. }
  195. }
  196. func (l *PublishSopTaskLogic) AddLabelRelationships(sopStages map[uint64]*ent.SopStage, contact ent.Contact, currentLabelIds []uint64, addLabelIds []uint64, delLabelIds []uint64, organizationId uint64) (err error) {
  197. //// 开始事务
  198. //tx, err := l.svcCtx.DB.Tx(context.Background())
  199. //if err != nil {
  200. // return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  201. //}
  202. // 获取 addLabelIds 中不在 currentLabelIds 中的标签ID
  203. var newLabelIds []uint64
  204. var remLabelIds []uint64
  205. var finalLabelIds []uint64
  206. // 创建一个映射,用于快速查找 currentLabelIds 中的元素
  207. currentLabelIdSet := make(map[uint64]struct{})
  208. for _, id := range currentLabelIds {
  209. currentLabelIdSet[id] = struct{}{}
  210. }
  211. delLabelIdSet := make(map[uint64]struct{})
  212. for _, id := range delLabelIds {
  213. delLabelIdSet[id] = struct{}{}
  214. }
  215. if addLabelIds != nil {
  216. // 遍历 addLabelIds,找出不在 currentLabelIds 中的元素
  217. for _, id := range addLabelIds {
  218. if _, ce := currentLabelIdSet[id]; !ce {
  219. if _, re := delLabelIdSet[id]; !re {
  220. newLabelIds = append(newLabelIds, id)
  221. }
  222. }
  223. }
  224. if len(newLabelIds) > 0 {
  225. // 创建需要新增的标签关系
  226. for _, id := range newLabelIds {
  227. currentLabelIdSet[id] = struct{}{}
  228. _, err = l.svcCtx.DB.LabelRelationship.Create().
  229. SetLabelID(id).
  230. SetContactID(contact.ID).
  231. SetOrganizationID(organizationId).
  232. Save(l.ctx)
  233. if err != nil {
  234. //_ = tx.Rollback()
  235. return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  236. }
  237. }
  238. // 合并 currentLabelIds 和 newLabelIds
  239. currentLabelIds = append(currentLabelIds, newLabelIds...)
  240. }
  241. }
  242. if delLabelIds != nil {
  243. // 遍历 delLabelIds,找出在 currentLabelIds 中的元素
  244. for _, id := range delLabelIds {
  245. if _, exists := currentLabelIdSet[id]; exists {
  246. remLabelIds = append(newLabelIds, id)
  247. delete(currentLabelIdSet, id)
  248. }
  249. }
  250. if len(remLabelIds) > 0 {
  251. _, err = l.svcCtx.DB.LabelRelationship.Delete().Where(labelrelationship.LabelIDIn(remLabelIds...), labelrelationship.ContactIDEQ(contact.ID), labelrelationship.OrganizationIDEQ(organizationId)).Exec(l.ctx)
  252. if err != nil {
  253. //_ = tx.Rollback()
  254. return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  255. }
  256. }
  257. }
  258. if len(newLabelIds) == 0 && len(remLabelIds) == 0 {
  259. return nil
  260. }
  261. for id := range currentLabelIdSet {
  262. finalLabelIds = append(finalLabelIds, id)
  263. }
  264. // 遍历 sop_stages,找出满足条件的 stage
  265. for key, stage := range sopStages {
  266. if stage != nil && stage.ConditionType == 1 && isLabelIdListMatchFilter(finalLabelIds, stage.ConditionOperator, stage.ConditionList) {
  267. // 判断是否有 contact_wxid、source_type、source_id、sub_source_id 相同的记录
  268. _, err := l.svcCtx.DB.MessageRecords.Query().
  269. Where(
  270. messagerecords.ContactWxid(contact.Wxid),
  271. messagerecords.SourceType(3),
  272. messagerecords.SourceID(stage.ID),
  273. messagerecords.SubSourceID(0),
  274. ).
  275. Only(l.ctx)
  276. if !ent.IsNotFound(err) {
  277. continue
  278. }
  279. // 判断ActionMessage是否为空
  280. sourceType := 3
  281. if stage.ActionMessage != nil {
  282. for i, message := range stage.ActionMessage {
  283. meta := custom_types.Meta{}
  284. if message.Meta != nil {
  285. meta.Filename = message.Meta.Filename
  286. }
  287. _, _ = l.svcCtx.DB.MessageRecords.Create().
  288. SetNotNilBotWxid(&contact.WxWxid).
  289. SetNotNilContactID(&contact.ID).
  290. SetNotNilContactType(&contact.Type).
  291. SetNotNilContactWxid(&contact.Wxid).
  292. SetNotNilContentType(&message.Type).
  293. SetNotNilContent(&message.Content).
  294. SetMeta(meta).
  295. SetNotNilSourceType(&sourceType).
  296. SetNotNilSourceID(&stage.ID).
  297. SetSubSourceID(uint64(i)).
  298. SetOrganizationID(organizationId).
  299. Save(l.ctx)
  300. //if err != nil {
  301. // return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  302. //}
  303. }
  304. }
  305. if stage.ActionForward != nil {
  306. if stage.ActionForward.Wxid != "" {
  307. forwardWxids := splitString(stage.ActionForward.Wxid)
  308. for _, forwardWxid := range forwardWxids {
  309. for i, message := range stage.ActionForward.Action {
  310. meta := custom_types.Meta{}
  311. if message.Meta != nil {
  312. meta.Filename = message.Meta.Filename
  313. }
  314. _, err = l.svcCtx.DB.MessageRecords.Create().
  315. SetBotWxid(contact.WxWxid).
  316. SetContactID(0).
  317. SetContactType(0).
  318. SetContactWxid(forwardWxid).
  319. SetContentType(message.Type).
  320. SetContent(message.Content).
  321. SetMeta(meta).
  322. SetSourceType(sourceType).
  323. SetSourceID(stage.ID).
  324. SetSubSourceID(contact.ID + uint64(i)).
  325. SetOrganizationID(organizationId).
  326. Save(l.ctx)
  327. }
  328. }
  329. }
  330. }
  331. if stage.ActionLabelAdd != nil || stage.ActionLabelDel != nil {
  332. // 递归调用 AddLabelRelationships
  333. sopStages[key] = nil
  334. err = l.AddLabelRelationships(sopStages, contact, finalLabelIds, stage.ActionLabelAdd, stage.ActionLabelDel, organizationId)
  335. if err != nil {
  336. //_ = tx.Rollback()
  337. return err
  338. }
  339. }
  340. }
  341. }
  342. // 所有操作成功,提交事务
  343. //err = tx.Commit()
  344. //if err != nil {
  345. // return dberrorhandler.DefaultEntError(l.Logger, err, nil)
  346. //}
  347. return nil
  348. }
  349. func valueInArray(val string, array []string) bool {
  350. for _, item := range array {
  351. if item == val {
  352. return true
  353. }
  354. }
  355. return false
  356. }
  357. func isLabelIdListMatchFilter(labelIdList []uint64, conditionOperator int, conditionList []custom_types.Condition) bool {
  358. labelIdSet := make(map[uint64]struct{})
  359. for _, id := range labelIdList {
  360. labelIdSet[id] = struct{}{}
  361. }
  362. for _, condition := range conditionList {
  363. match := false
  364. for _, id := range condition.LabelIdList {
  365. if _, ok := labelIdSet[id]; ok {
  366. match = true
  367. break
  368. }
  369. }
  370. if condition.Equal == 2 {
  371. match = !match
  372. }
  373. if conditionOperator == 1 && !match {
  374. return false
  375. } else if conditionOperator == 2 && match {
  376. return true
  377. }
  378. }
  379. return conditionOperator == 1
  380. }
  381. func splitString(input string) []string {
  382. // Define the regular expression pattern to match Chinese comma, English comma, and Chinese enumeration comma
  383. pattern := `[,,、]`
  384. re := regexp.MustCompile(pattern)
  385. // Split the input string based on the pattern
  386. return re.Split(input, -1)
  387. }