create_whatcapp_batch_msg_logic.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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.Phone(*req.Phone),
  82. contact.Cc(*req.Cc),
  83. contact.Ctype(2),
  84. ).All(l.ctx)
  85. if err != nil {
  86. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  87. }
  88. tagids := make([]uint64, 0, 1)
  89. tagids = append(tagids, uint64(0))
  90. tagMap["contact_tag"] = tagids
  91. tagByte, err := json.Marshal(tagMap)
  92. if err != nil {
  93. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  94. }
  95. tagstring = string(tagByte)
  96. tag = "全部"
  97. } else {
  98. if allContact { // 所有联系人
  99. // 获取 contact 表中 wx_wxid 等于 req.Fromwxid 的 type 为1的数据
  100. userList, err = l.svcCtx.DB.Contact.Query().Where(
  101. contact.Cc(*req.Cc),
  102. contact.Phone(*req.Phone),
  103. contact.Ctype(2),
  104. ).All(l.ctx)
  105. if err != nil {
  106. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  107. }
  108. tag = "全部联系人"
  109. } else {
  110. userList, err = l.getContactList(req.Labels, *req.Cc, *req.Phone)
  111. if err != nil {
  112. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  113. }
  114. }
  115. tagMap["contact_tag"] = req.Labels
  116. tagByte, err := json.Marshal(tagMap)
  117. if err != nil {
  118. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  119. }
  120. tagstring = string(tagByte)
  121. tagArray := l.getLabelListByIds(req.Labels, req.GroupLabels)
  122. if tag != "" {
  123. tagArray = append(tagArray, tag)
  124. }
  125. tag = strings.Join(tagArray, ",")
  126. }
  127. // 这里是根据userlist 和 批量消息数 获得最终待发送消息总数
  128. total := int32(len(userList)) * int32(len(msgActionList))
  129. l.Logger.Infof("userList=%v user_total=%v\n", userList, total)
  130. if total == 0 {
  131. return &types.BaseMsgResp{Msg: "未查询到收信人,请重新选择", Code: 3}, nil
  132. }
  133. //TODO 发送批量消息
  134. sto := make([]string, 0)
  135. for _, v := range userList {
  136. sto = append(sto, v.Cc+v.Phone)
  137. }
  138. fullPhone := *req.Cc + *req.Phone
  139. result, err := aliyun.SendBatchChatappMessage(*req.TemplateCode, *req.Lang, fullPhone, sto)
  140. if err != nil {
  141. return nil, errorx.NewInvalidArgumentError(err.Error())
  142. }
  143. l.Logger.Infof("send_batch_chatapp_message result=%v\n", result)
  144. batchNo := uuidx.NewUUID().String()
  145. var sendTime *time.Time
  146. if !sendNow {
  147. sendTime = &startTime
  148. }
  149. tx, err := l.svcCtx.DB.Tx(context.Background())
  150. _, err = tx.BatchMsg.Create().
  151. SetNotNilBatchNo(&batchNo).
  152. SetStatus(0).
  153. //SetNotNilFromwxid(req.Fromwxid).
  154. SetNotNilMsg(req.Msg).
  155. SetNotNilTag(&tag).
  156. SetNotNilPhone(req.Phone).
  157. SetNotNilCc(req.Cc).
  158. SetNotNilTagids(&tagstring).
  159. SetTotal(total).
  160. SetNotNilTaskName(req.TaskName).
  161. SetNotNilStartTime(&startTime).
  162. SetNillableSendTime(sendTime).
  163. SetType(3).
  164. SetNotNilOrganizationID(&organizationId).
  165. SetCtype(2).
  166. Save(l.ctx)
  167. if err != nil {
  168. _ = tx.Rollback()
  169. l.Logger.Errorf("insert whatsapp batch_msg err=%v\n", err)
  170. if err != nil {
  171. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  172. }
  173. }
  174. msgs := make([]*ent.MsgCreate, 100)
  175. for idx, user := range userList {
  176. phone := user.Cc + user.Phone
  177. msgRow := tx.Msg.Create().
  178. SetNotNilCc(req.Cc).
  179. SetNotNilPhone(req.Phone).
  180. SetNotNilToid(&phone).
  181. SetMsgtype(int32(1)).
  182. SetNotNilMsg(req.Msg).
  183. SetStatus(1).
  184. SetNotNilBatchNo(&batchNo)
  185. msgs = append(msgs, msgRow)
  186. // 100条插入一次
  187. if idx == 100 {
  188. _, err = tx.Msg.CreateBulk(msgs...).Save(l.ctx)
  189. if err != nil {
  190. _ = tx.Rollback()
  191. l.Logger.Errorf("msg CreateBulk err: %v", err)
  192. }
  193. }
  194. msgs = make([]*ent.MsgCreate, 100)
  195. }
  196. // 不足100条插入一次
  197. if len(msgs) > 0 {
  198. _, err = tx.Msg.CreateBulk(msgs...).Save(l.ctx)
  199. if err != nil {
  200. _ = tx.Rollback()
  201. l.Logger.Errorf("msg CreateBulk err: %v", err)
  202. }
  203. }
  204. _ = tx.Commit()
  205. return &types.BaseMsgResp{Msg: errormsg.CreateSuccess}, nil
  206. }
  207. func (l *CreateWhatcappBatchMsgLogic) getContactList(labels []uint64, cc, phone string) ([]*ent.Contact, error) {
  208. // 获取 label_relationship 表中,label_id 等于 labids 的 contact_id
  209. labelrelationships, err := l.svcCtx.DB.LabelRelationship.Query().Where(labelrelationship.LabelIDIn(labels...)).All(l.ctx)
  210. if err != nil {
  211. return nil, dberrorhandler.DefaultEntError(l.Logger, err, nil)
  212. }
  213. contact_ids := make([]uint64, 0, len(labelrelationships))
  214. for _, labelrelationship := range labelrelationships {
  215. contact_ids = append(contact_ids, labelrelationship.ContactID)
  216. }
  217. userList := make([]*ent.Contact, 0)
  218. if len(contact_ids) > 0 {
  219. // 获取 contact 表中 wx_wxid 等于 req.Fromwxid 并且 id 等于 contact_ids 并且 type 为1或2 的数据
  220. userList, err = l.svcCtx.DB.Contact.Query().Where(
  221. contact.Cc(cc),
  222. contact.Phone(phone),
  223. contact.IDIn(contact_ids...),
  224. contact.Ctype(2),
  225. ).All(l.ctx)
  226. if err != nil {
  227. return nil, dberrorhandler.DefaultEntError(l.Logger, err, nil)
  228. }
  229. }
  230. return userList, nil
  231. }
  232. func (l *CreateWhatcappBatchMsgLogic) getLabelListByIds(labels, groupLabels []uint64) []string {
  233. result := make([]string, 0)
  234. labels = append(labels, groupLabels...)
  235. if len(labels) > 0 {
  236. contacts, err := l.svcCtx.DB.Label.Query().Where(
  237. label.IDIn(labels...),
  238. ).Select("name").All(l.ctx)
  239. l.Logger.Infof("contacts=%v", contacts)
  240. if err != nil {
  241. return result
  242. }
  243. for _, val := range contacts {
  244. result = append(result, val.Name)
  245. }
  246. }
  247. return result
  248. }