publish_sop_task_logic.go 14 KB

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