create_batch_msg_logic.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. all := false
  34. for _, label := range req.Labels {
  35. if strings.EqualFold(label, "all") || strings.EqualFold(label, "全部") {
  36. all = true
  37. tagstring := "all"
  38. req.Tag = &tagstring
  39. }
  40. }
  41. l.Logger.Infof("CreateBatchMsgLogic: %v", *req)
  42. startTime := time.Now()
  43. // req.StartTimeStr 不为nil并且不为空
  44. if req.StartTimeStr != nil && *req.StartTimeStr != "" {
  45. var err error
  46. // 将 req.StartTimeStr 转换为 req.StartTime
  47. startTime, err = time.Parse("2006-01-02 15:04:05", *req.StartTimeStr)
  48. if err != nil {
  49. // 处理错误,例如打印错误并返回
  50. l.Logger.Errorf("时间字符串转换错误: %v", err)
  51. return nil, err
  52. }
  53. }
  54. // 定时发送时间
  55. var sendTime time.Time
  56. if req.SendTimeStr != nil && *req.SendTimeStr != "" {
  57. var err error
  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 err error
  68. var msgArray []custom_types.Action
  69. if req.Msg != nil && *req.Msg != "" {
  70. err = json.Unmarshal([]byte(*req.Msg), &msgArray)
  71. if err != nil {
  72. return nil, errors.New("解析JSON失败")
  73. }
  74. }
  75. var msgActionList []custom_types.Action
  76. if len(msgArray) > 0 {
  77. msgActionList = make([]custom_types.Action, len(msgArray))
  78. for i, msg := range msgArray {
  79. if msg.Type == 1 {
  80. msgActionList[i] = custom_types.Action{
  81. Type: msg.Type,
  82. Content: msg.Content,
  83. }
  84. } else {
  85. msgActionList[i] = custom_types.Action{
  86. Type: msg.Type,
  87. Content: msg.Content,
  88. Meta: &custom_types.Meta{
  89. Filename: msg.Meta.Filename,
  90. },
  91. }
  92. }
  93. }
  94. }
  95. tagstring := strings.Join(req.Labels, ",")
  96. req.Tag = &tagstring
  97. userlist := make([]*ent.Contact, 0)
  98. if all {
  99. // 获取 contact 表中 wx_wxid 等于 req.Fromwxid 的 type 为1或2的数据
  100. userlist, err = l.svcCtx.DB.Contact.Query().Where(contact.WxWxid(*req.Fromwxid), contact.TypeIn(1, 2)).All(l.ctx)
  101. if err != nil {
  102. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  103. }
  104. } else {
  105. // 获取 label 表中 name 为 tags的记录
  106. labids, err := l.svcCtx.DB.Label.Query().Where(label.NameIn(req.Labels...)).IDs(l.ctx)
  107. if err != nil {
  108. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  109. }
  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. if len(contact_ids) > 0 {
  120. // 获取 contact 表中 wx_wxid 等于 req.Fromwxid 并且 id 等于 contact_ids 并且 type 为1或2 的数据
  121. userlist, err = l.svcCtx.DB.Contact.Query().Where(contact.WxWxid(*req.Fromwxid), contact.IDIn(contact_ids...), contact.TypeIn(1, 2)).All(l.ctx)
  122. if err != nil {
  123. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  124. }
  125. }
  126. }
  127. total := int32(len(userlist))
  128. if total == 0 {
  129. return &types.BaseMsgResp{Msg: errormsg.TargetNotFound}, nil
  130. }
  131. uuid := uuidx.NewUUID()
  132. batchNo := uuid.String()
  133. // 开始事务
  134. tx, err := l.svcCtx.DB.Tx(context.Background())
  135. if err != nil {
  136. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  137. }
  138. _, err = l.svcCtx.DB.BatchMsg.Create().
  139. SetNotNilBatchNo(&batchNo).
  140. SetNotNilFromwxid(req.Fromwxid).
  141. SetNotNilMsg(req.Msg).
  142. SetNotNilTag(req.Tag).
  143. SetTotal(total).
  144. SetNotNilStartTime(&startTime).
  145. SetNotNilSendTime(&sendTime).
  146. Save(l.ctx)
  147. if err != nil {
  148. _ = tx.Rollback()
  149. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  150. }
  151. // 批量记录信息到 message_records 表里
  152. for _, user := range userlist {
  153. // 每个用户的所有 信息 组合到一个数组里然后批量插入,减少DB的压力
  154. bulkCreate := make([]*ent.MessageRecordsCreate, 0)
  155. for _, msg := range msgActionList {
  156. bulkCreate = append(bulkCreate, l.svcCtx.DB.MessageRecords.Create().
  157. SetStatus(1).
  158. SetNotNilBotWxid(req.Fromwxid).
  159. SetNotNilContactID(&user.ID).
  160. SetNotNilContactType(&user.Type).
  161. SetNotNilContactWxid(&user.Wxid).
  162. SetNotNilContentType(&msg.Type).
  163. SetNotNilContent(&msg.Content).
  164. SetNotNilMeta(msg.Meta).
  165. SetSendTime(sendTime),
  166. )
  167. }
  168. err = l.svcCtx.DB.MessageRecords.CreateBulk(bulkCreate...).Exec(l.ctx)
  169. if err != nil {
  170. _ = tx.Rollback()
  171. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  172. }
  173. }
  174. _ = tx.Commit()
  175. return &types.BaseMsgResp{Msg: errormsg.CreateSuccess}, nil
  176. }