create_whatcapp_batch_msg_logic.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. package batch_msg
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "github.com/suyuan32/simple-admin-common/msg/errormsg"
  7. "github.com/suyuan32/simple-admin-common/utils/uuidx"
  8. "github.com/zeromicro/go-zero/core/errorx"
  9. "strings"
  10. "time"
  11. "wechat-api/ent"
  12. "wechat-api/ent/contact"
  13. "wechat-api/ent/custom_types"
  14. "wechat-api/ent/label"
  15. "wechat-api/ent/labelrelationship"
  16. "wechat-api/hook/aliyun"
  17. "wechat-api/internal/utils/dberrorhandler"
  18. "wechat-api/internal/svc"
  19. "wechat-api/internal/types"
  20. "github.com/zeromicro/go-zero/core/logx"
  21. )
  22. type CreateWhatcappBatchMsgLogic struct {
  23. logx.Logger
  24. ctx context.Context
  25. svcCtx *svc.ServiceContext
  26. }
  27. func NewCreateWhatcappBatchMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateWhatcappBatchMsgLogic {
  28. return &CreateWhatcappBatchMsgLogic{
  29. Logger: logx.WithContext(ctx),
  30. ctx: ctx,
  31. svcCtx: svcCtx}
  32. }
  33. func (l *CreateWhatcappBatchMsgLogic) CreateWhatcappBatchMsg(req *types.BatchMsgInfo) (*types.BaseMsgResp, error) {
  34. organizationId := l.ctx.Value("organizationId").(uint64)
  35. var err error
  36. var tagstring, tag string
  37. allContact := false
  38. tagIdArray := make([]uint64, 0)
  39. for _, labelId := range req.Labels {
  40. tagIdArray = append(tagIdArray, labelId)
  41. if labelId == uint64(0) { //全部
  42. allContact = true
  43. }
  44. }
  45. startTime := time.Now()
  46. sendNow := true
  47. // 把 req.Msg 字符串的内容 json_decode 到 msgArray
  48. // 然后再把每一条信息都给所有指定的用户记录到 message_records 表
  49. var msgArray []custom_types.Action
  50. if req.Msg != nil && *req.Msg != "" {
  51. err = json.Unmarshal([]byte(*req.Msg), &msgArray)
  52. if err != nil {
  53. return nil, errors.New("解析JSON失败")
  54. }
  55. }
  56. var msgActionList []custom_types.Action
  57. if len(msgArray) > 0 {
  58. msgActionList = make([]custom_types.Action, len(msgArray))
  59. for i, msg := range msgArray {
  60. if msg.Type == 1 {
  61. msgActionList[i] = custom_types.Action{
  62. Type: msg.Type,
  63. Content: msg.Content,
  64. }
  65. } else {
  66. msgActionList[i] = custom_types.Action{
  67. Type: msg.Type,
  68. Content: msg.Content,
  69. Meta: &custom_types.Meta{
  70. Filename: msg.Meta.Filename,
  71. },
  72. }
  73. }
  74. }
  75. }
  76. userList := make([]*ent.Contact, 0)
  77. tagMap := make(map[string][]uint64)
  78. if allContact {
  79. // 获取 contact 表中 cc+phone 匹配的联系人
  80. userList, err = l.svcCtx.DB.Contact.Query().Where(
  81. contact.OrganizationID(organizationId),
  82. contact.Ctype(2),
  83. ).All(l.ctx)
  84. if err != nil {
  85. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  86. }
  87. tagids := make([]uint64, 0, 1)
  88. tagids = append(tagids, uint64(0))
  89. tagMap["contact_tag"] = tagids
  90. tagByte, err := json.Marshal(tagMap)
  91. if err != nil {
  92. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  93. }
  94. tagstring = string(tagByte)
  95. tag = "全部"
  96. } else {
  97. if allContact { // 所有联系人
  98. // 获取 contact 表中 wx_wxid 等于 req.Fromwxid 的 type 为1的数据
  99. userList, err = l.svcCtx.DB.Contact.Query().Where(
  100. contact.OrganizationID(organizationId),
  101. contact.Ctype(2),
  102. ).All(l.ctx)
  103. if err != nil {
  104. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  105. }
  106. tag = "全部联系人"
  107. } else {
  108. userList, err = l.getContactList(req.Labels, *req.Cc, *req.Phone)
  109. if err != nil {
  110. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  111. }
  112. }
  113. tagMap["contact_tag"] = req.Labels
  114. tagByte, err := json.Marshal(tagMap)
  115. if err != nil {
  116. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  117. }
  118. tagstring = string(tagByte)
  119. tagArray := l.getLabelListByIds(req.Labels, req.GroupLabels)
  120. if tag != "" {
  121. tagArray = append(tagArray, tag)
  122. }
  123. tag = strings.Join(tagArray, ",")
  124. }
  125. // 这里是根据userlist 和 批量消息数 获得最终待发送消息总数
  126. total := int32(len(userList)) * int32(len(msgActionList))
  127. l.Logger.Infof("userList=%v user_total=%v\n", userList, total)
  128. if total == 0 {
  129. return &types.BaseMsgResp{Msg: "未查询到收信人,请重新选择", Code: 3}, nil
  130. }
  131. //TODO 发送批量消息
  132. sto := make([]string, 0)
  133. for _, v := range userList {
  134. sto = append(sto, v.Cc+v.Phone)
  135. }
  136. fullPhone := *req.Cc + *req.Phone
  137. result, err := aliyun.SendBatchChatappMessage(*req.TemplateCode, *req.Lang, fullPhone, sto)
  138. if err != nil {
  139. return nil, errorx.NewInvalidArgumentError(err.Error())
  140. }
  141. l.Logger.Infof("send_batch_chatapp_message result=%v\n", result)
  142. batchNo := uuidx.NewUUID().String()
  143. var sendTime *time.Time
  144. if !sendNow {
  145. sendTime = &startTime
  146. }
  147. tx, err := l.svcCtx.DB.Tx(context.Background())
  148. _, err = tx.BatchMsg.Create().
  149. SetNotNilBatchNo(&batchNo).
  150. SetStatus(0).
  151. //SetNotNilFromwxid(req.Fromwxid).
  152. SetNotNilMsg(req.Msg).
  153. SetNotNilTag(&tag).
  154. SetNotNilPhone(req.Phone).
  155. SetNotNilCc(req.Cc).
  156. SetNotNilTagids(&tagstring).
  157. SetTotal(total).
  158. SetNotNilTaskName(req.TaskName).
  159. SetNotNilStartTime(&startTime).
  160. SetNillableSendTime(sendTime).
  161. SetType(3).
  162. SetNotNilOrganizationID(&organizationId).
  163. SetCtype(2).
  164. Save(l.ctx)
  165. if err != nil {
  166. _ = tx.Rollback()
  167. l.Logger.Errorf("insert whatsapp batch_msg err=%v\n", err)
  168. if err != nil {
  169. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  170. }
  171. }
  172. msgs := make([]*ent.MsgCreate, 100)
  173. for idx, user := range userList {
  174. phone := user.Cc + user.Phone
  175. msgRow := tx.Msg.Create().
  176. SetNotNilCc(req.Cc).
  177. SetNotNilPhone(req.Phone).
  178. SetNotNilToid(&phone).
  179. SetMsgtype(int32(1)).
  180. SetNotNilMsg(req.Msg).
  181. SetStatus(1).
  182. SetNotNilBatchNo(&batchNo)
  183. msgs = append(msgs, msgRow)
  184. // 100条插入一次
  185. if idx == 100 {
  186. _, err = tx.Msg.CreateBulk(msgs...).Save(l.ctx)
  187. if err != nil {
  188. _ = tx.Rollback()
  189. l.Logger.Errorf("msg CreateBulk err: %v", err)
  190. }
  191. }
  192. msgs = make([]*ent.MsgCreate, 100)
  193. }
  194. // 不足100条插入一次
  195. if len(msgs) > 0 {
  196. _, err = tx.Msg.CreateBulk(msgs...).Save(l.ctx)
  197. if err != nil {
  198. _ = tx.Rollback()
  199. l.Logger.Errorf("msg CreateBulk err: %v", err)
  200. }
  201. }
  202. _ = tx.Commit()
  203. return &types.BaseMsgResp{Msg: errormsg.CreateSuccess}, nil
  204. }
  205. func (l *CreateWhatcappBatchMsgLogic) getContactList(labels []uint64, cc, phone string) ([]*ent.Contact, error) {
  206. // 获取 label_relationship 表中,label_id 等于 labids 的 contact_id
  207. labelrelationships, err := l.svcCtx.DB.LabelRelationship.Query().Where(labelrelationship.LabelIDIn(labels...)).All(l.ctx)
  208. if err != nil {
  209. return nil, dberrorhandler.DefaultEntError(l.Logger, err, nil)
  210. }
  211. contact_ids := make([]uint64, 0, len(labelrelationships))
  212. for _, labelrelationship := range labelrelationships {
  213. contact_ids = append(contact_ids, labelrelationship.ContactID)
  214. }
  215. userList := make([]*ent.Contact, 0)
  216. if len(contact_ids) > 0 {
  217. // 获取 contact 表中 wx_wxid 等于 req.Fromwxid 并且 id 等于 contact_ids 并且 type 为1或2 的数据
  218. userList, err = l.svcCtx.DB.Contact.Query().Where(
  219. contact.Cc(cc),
  220. contact.Phone(phone),
  221. contact.IDIn(contact_ids...),
  222. contact.Ctype(2),
  223. ).All(l.ctx)
  224. if err != nil {
  225. return nil, dberrorhandler.DefaultEntError(l.Logger, err, nil)
  226. }
  227. }
  228. return userList, nil
  229. }
  230. func (l *CreateWhatcappBatchMsgLogic) getLabelListByIds(labels, groupLabels []uint64) []string {
  231. result := make([]string, 0)
  232. labels = append(labels, groupLabels...)
  233. if len(labels) > 0 {
  234. contacts, err := l.svcCtx.DB.Label.Query().Where(
  235. label.IDIn(labels...),
  236. ).Select("name").All(l.ctx)
  237. l.Logger.Infof("contacts=%v", contacts)
  238. if err != nil {
  239. return result
  240. }
  241. for _, val := range contacts {
  242. result = append(result, val.Name)
  243. }
  244. }
  245. return result
  246. }