create_batch_msg_logic.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. package batch_msg
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "strings"
  7. "time"
  8. "wechat-api/ent/custom_types"
  9. "wechat-api/ent"
  10. "wechat-api/ent/contact"
  11. "wechat-api/ent/label"
  12. "wechat-api/ent/labelrelationship"
  13. "wechat-api/internal/svc"
  14. "wechat-api/internal/types"
  15. "wechat-api/internal/utils/dberrorhandler"
  16. "github.com/suyuan32/simple-admin-common/msg/errormsg"
  17. "github.com/suyuan32/simple-admin-common/utils/uuidx"
  18. "github.com/zeromicro/go-zero/core/logx"
  19. )
  20. type CreateBatchMsgLogic struct {
  21. ctx context.Context
  22. svcCtx *svc.ServiceContext
  23. logx.Logger
  24. }
  25. func NewCreateBatchMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateBatchMsgLogic {
  26. return &CreateBatchMsgLogic{
  27. ctx: ctx,
  28. svcCtx: svcCtx,
  29. Logger: logx.WithContext(ctx),
  30. }
  31. }
  32. func (l *CreateBatchMsgLogic) CreateBatchMsg(req *types.BatchMsgInfo) (*types.BaseMsgResp, error) {
  33. var err error
  34. organizationId := l.ctx.Value("organizationId").(uint64)
  35. all := false
  36. for _, labelName := range req.Labels {
  37. if strings.EqualFold(labelName, "all") || strings.EqualFold(labelName, "全部") {
  38. all = true
  39. tagstring := "all"
  40. req.Tag = &tagstring
  41. }
  42. }
  43. l.Logger.Infof("CreateBatchMsgLogic: %v", *req)
  44. startTime := time.Now()
  45. // req.StartTimeStr 不为nil并且不为空
  46. if req.StartTimeStr != nil && *req.StartTimeStr != "" {
  47. // 将 req.StartTimeStr 转换为 req.StartTime
  48. startTime, err = time.Parse("2006-01-02 15:04:05", *req.StartTimeStr)
  49. if err != nil {
  50. // 处理错误,例如打印错误并返回
  51. l.Logger.Errorf("时间字符串转换错误: %v", err)
  52. return nil, err
  53. }
  54. }
  55. // 定时发送时间
  56. var sendTime time.Time
  57. if req.SendTimeStr != nil && *req.SendTimeStr != "" {
  58. sendTime, err = time.Parse("2006-01-02 15:04:05", *req.SendTimeStr)
  59. if err != nil {
  60. // 处理错误,例如打印错误并返回
  61. l.Logger.Errorf("时间字符串转换错误: %v", err)
  62. return nil, err
  63. }
  64. }
  65. // 把 req.Msg 字符串的内容 json_decode 到 msgArray
  66. // 然后再把每一条信息都给所有指定的用户记录到 message_records 表
  67. var msgArray []custom_types.Action
  68. if req.Msg != nil && *req.Msg != "" {
  69. err = json.Unmarshal([]byte(*req.Msg), &msgArray)
  70. if err != nil {
  71. return nil, errors.New("解析JSON失败")
  72. }
  73. }
  74. var msgActionList []custom_types.Action
  75. if len(msgArray) > 0 {
  76. msgActionList = make([]custom_types.Action, len(msgArray))
  77. for i, msg := range msgArray {
  78. if msg.Type == 1 {
  79. msgActionList[i] = custom_types.Action{
  80. Type: msg.Type,
  81. Content: msg.Content,
  82. }
  83. } else {
  84. msgActionList[i] = custom_types.Action{
  85. Type: msg.Type,
  86. Content: msg.Content,
  87. Meta: &custom_types.Meta{
  88. Filename: msg.Meta.Filename,
  89. },
  90. }
  91. }
  92. }
  93. }
  94. tagstring := strings.Join(req.Labels, ",")
  95. req.Tag = &tagstring
  96. userlist := make([]*ent.Contact, 0)
  97. if all {
  98. // 获取 contact 表中 wx_wxid 等于 req.Fromwxid 的 type 为1或2的数据
  99. userlist, err = l.svcCtx.DB.Contact.Query().Where(contact.WxWxid(*req.Fromwxid), contact.TypeIn(1, 2)).All(l.ctx)
  100. if err != nil {
  101. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  102. }
  103. } else {
  104. // 获取 label 表中 name 为 tags的记录
  105. labids, err := l.svcCtx.DB.Label.Query().Where(label.NameIn(req.Labels...)).IDs(l.ctx)
  106. if err != nil {
  107. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  108. }
  109. //l.Logger.Infof("CreateBatchMsgLogic labids= %v", labids)
  110. // 获取 label_relationship 表中,label_id 等于 labids 的 contact_id
  111. labelrelationships, err := l.svcCtx.DB.LabelRelationship.Query().Where(labelrelationship.LabelIDIn(labids...)).All(l.ctx)
  112. if err != nil {
  113. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  114. }
  115. contact_ids := make([]uint64, 0)
  116. for _, labelrelationship := range labelrelationships {
  117. contact_ids = append(contact_ids, labelrelationship.ContactID)
  118. }
  119. //l.Logger.Infof("CreateBatchMsgLogic contact_ids= %v", contact_ids)
  120. if len(contact_ids) > 0 {
  121. // 获取 contact 表中 wx_wxid 等于 req.Fromwxid 并且 id 等于 contact_ids 并且 type 为1或2 的数据
  122. userlist, err = l.svcCtx.DB.Contact.Query().Where(contact.WxWxid(*req.Fromwxid), contact.IDIn(contact_ids...), contact.TypeIn(1, 2)).All(l.ctx)
  123. if err != nil {
  124. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  125. }
  126. //l.Logger.Infof("CreateBatchMsgLogic userlist= %v", userlist)
  127. }
  128. }
  129. total := int32(len(userlist))
  130. if total == 0 {
  131. return &types.BaseMsgResp{Msg: errormsg.TargetNotFound}, nil
  132. }
  133. uuid := uuidx.NewUUID()
  134. batchNo := uuid.String()
  135. // 开始事务
  136. tx, err := l.svcCtx.DB.Tx(context.Background())
  137. if err != nil {
  138. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  139. }
  140. batchMsg, err := l.svcCtx.DB.BatchMsg.Create().
  141. SetNotNilBatchNo(&batchNo).
  142. SetNotNilFromwxid(req.Fromwxid).
  143. SetNotNilMsg(req.Msg).
  144. SetNotNilTag(req.Tag).
  145. SetTotal(total).
  146. SetNotNilTaskName(req.TaskName).
  147. SetNotNilStartTime(&startTime).
  148. SetNotNilSendTime(&sendTime).
  149. SetNotNilType(req.Type).
  150. Save(l.ctx)
  151. if err != nil {
  152. _ = tx.Rollback()
  153. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  154. }
  155. // 批量记录信息到 message_records 表里
  156. for _, user := range userlist {
  157. // 每个用户的所有 信息 组合到一个数组里然后批量插入,减少DB的压力
  158. bulkCreate := make([]*ent.MessageRecordsCreate, 0)
  159. for idx, msg := range msgActionList {
  160. bulkCreate = append(bulkCreate, l.svcCtx.DB.MessageRecords.Create().
  161. SetStatus(1).
  162. SetNotNilBotWxid(req.Fromwxid).
  163. SetNotNilContactID(&user.ID).
  164. SetNotNilContactType(&user.Type).
  165. SetNotNilContentType(&msg.Type).
  166. SetNotNilContent(&msg.Content).
  167. SetNotNilMeta(msg.Meta).
  168. SetSendTime(sendTime).
  169. SetNotNilContactWxid(&user.Wxid). //接收方wxid
  170. SetSourceType(2). // 2:批量消息
  171. SetSourceID(batchMsg.ID). // 批量消息ID,batch_msg 表主键
  172. SetSubSourceID(uint64(idx)). // 用索引作为 sub_source_id
  173. SetOrganizationID(organizationId),
  174. )
  175. }
  176. err = l.svcCtx.DB.MessageRecords.CreateBulk(bulkCreate...).Exec(l.ctx)
  177. if err != nil {
  178. _ = tx.Rollback()
  179. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  180. }
  181. }
  182. _ = tx.Commit()
  183. return &types.BaseMsgResp{Msg: errormsg.CreateSuccess}, nil
  184. }