newSendMsgService.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. package common
  2. import (
  3. "app.yhyue.com/moapp/MessageCenter/entity"
  4. "app.yhyue.com/moapp/MessageCenter/rpc/internal/config"
  5. "app.yhyue.com/moapp/MessageCenter/rpc/type/message"
  6. "app.yhyue.com/moapp/jybase/redis"
  7. "context"
  8. "errors"
  9. "fmt"
  10. "github.com/zeromicro/go-zero/core/logx"
  11. "log"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. )
  17. var MsgGroupIdMap map[int]int
  18. func SetMsgSummary(newMsg, groupId, msgType int64) error {
  19. //更新所有消息
  20. if groupId == 11 {
  21. groupId = msgType
  22. //根据msgType更新待办二级分类汇总
  23. /*err1 := entity.ClickhouseConn.Exec(context.Background(), fmt.Sprintf(`alter table message_summary UPDATE msg_bitmap = bitmapOr(msg_bitmap,bitmapBuild([toUInt64(%d)])) where group_id = %d`, newMsg, msgType))
  24. if err1 != nil {
  25. //插入失败
  26. return err1
  27. }*/
  28. }
  29. err := entity.ClickhouseConn.Exec(context.Background(), fmt.Sprintf(`alter table message_summary UPDATE msg_bitmap = bitmapOr(msg_bitmap,bitmapBuild([toUInt64(%d)])) where group_id = %d`, newMsg, groupId))
  30. if err != nil {
  31. return err
  32. }
  33. return nil
  34. }
  35. func NewUserSendMsg(in *message.NewUserInsertMsgReq) error {
  36. userIdArr := strings.Split(in.UserIds, ",")
  37. //positionIdArr := strings.Split(in.PositionIds, ",")
  38. if len(userIdArr) == 0 {
  39. return errors.New("无效的用户id")
  40. }
  41. //wg := &sync.WaitGroup{}
  42. group_id := MsgGroupIdMap[int(in.MsgType)]
  43. for i := 0; i < len(userIdArr); i++ {
  44. if userIdArr[i] == "" {
  45. continue
  46. }
  47. //查询
  48. /*var positionId int64
  49. if len(positionIdArr) == len(userIdArr) {
  50. positionId = common.Int64All(positionIdArr[i])
  51. }*/
  52. row := entity.ClickhouseConn.QueryRow(context.Background(), fmt.Sprintf("SELECT COUNT(*) from message_user_summary where userId = '%s'", userIdArr[i]))
  53. var count uint64
  54. row.Scan(&count)
  55. if count > 0 { //存在则更新
  56. err1 := entity.ClickhouseConn.Exec(context.Background(), fmt.Sprintf(`alter table message_user_summary UPDATE allMsg = bitmapOr(allMsg,bitmapBuild([toUInt64(%d)])) where userId = '%s'`, in.MsgLogId, userIdArr[i]))
  57. if err1 != nil {
  58. log.Println("新用户update message_user_summary表出错,error", err1)
  59. return err1
  60. }
  61. } else {
  62. //新用户需要insert
  63. sql := "INSERT INTO message_user_summary values "
  64. sql += fmt.Sprintf(" ('%s',bitmapBuild([toUInt64(%d)]),bitmapBuild([toUInt64(0)])) ", userIdArr[i], int(in.MsgLogId))
  65. log.Println("sql", sql)
  66. err1 := entity.ClickhouseConn.Exec(context.Background(), sql)
  67. if err1 != nil {
  68. //插入失败
  69. log.Println("新用户insert message_user_summary表出错,error", err1)
  70. return err1
  71. }
  72. }
  73. //微信推送模板消息、app push
  74. pushData := WxTmplAndPush{
  75. MsgType: in.MsgType,
  76. Title: in.Title,
  77. Content: in.Content,
  78. WxPushUrl: in.WxPushUrl,
  79. AppPushUrl: in.AppPushUrl,
  80. ProductName: in.ProductName,
  81. OrderId: in.OrderId,
  82. OrderMoney: in.OrderMoney,
  83. Row4: in.Row4,
  84. }
  85. SentWxTmplAndAppPush(pushData, userIdArr[i], group_id, "", "")
  86. /*key := fmt.Sprintf(MsgCountKey, userIdArr[i], group_id)
  87. redis.Del(redisModule, key)
  88. if in.MsgType == 11 || in.MsgType == 12 {
  89. key1 := fmt.Sprintf(MsgClassCountKey, userIdArr[i], in.MsgType)
  90. redis.Del(redisModule, key1)
  91. }*/
  92. DelRedis(userIdArr[i], in.MsgType, group_id)
  93. }
  94. //wg.Wait()
  95. return nil
  96. }
  97. func UpdateUserMsgSummary(in *message.MultipleSaveMsgReq) error {
  98. userIdArr := strings.Split(in.UserIds, ",")
  99. //positionIdArr := strings.Split(in.PositionIds, ",")
  100. if len(userIdArr) == 0 {
  101. return errors.New("无效的用户id")
  102. }
  103. wg := &sync.WaitGroup{}
  104. group_id := MsgGroupIdMap[int(in.MsgType)]
  105. var ids []string
  106. for _, v := range userIdArr {
  107. ids = append(ids, v)
  108. if len(ids) == 1000 {
  109. go Update(ids, in.MsgLogId)
  110. ids = []string{}
  111. }
  112. }
  113. if len(ids) > 0 {
  114. go Update(ids, in.MsgLogId)
  115. }
  116. //p459 特殊处理 传过来的消息内容格式为 消息内容#jy#微信模板项目名称#jy#服务地址
  117. equityName, equityAddr := "", ""
  118. if in.MsgType == config.ConfigJson.EquityInfoMsgType {
  119. equityRs := strings.Split(in.Content, "#jy#")
  120. if len(equityRs) != 3 {
  121. log.Println("消息内容格式有误:", in.Content)
  122. return errors.New("无效的消息内容格式")
  123. }
  124. in.Content = equityRs[0]
  125. equityName = equityRs[1]
  126. equityAddr = equityRs[2]
  127. }
  128. for i := 0; i < len(userIdArr); i++ {
  129. if userIdArr[i] == "" {
  130. continue
  131. }
  132. //查询
  133. wg.Add(1)
  134. entity.SaveConcurrencyChan <- 1
  135. /*var positionId int64
  136. if len(positionIdArr) == len(userIdArr) {
  137. positionId = common.Int64All(positionIdArr[i])
  138. }*/
  139. go func(v string) {
  140. defer func() {
  141. <-entity.SaveConcurrencyChan
  142. wg.Done()
  143. }()
  144. //微信推送模板消息、app push
  145. pushData := WxTmplAndPush{
  146. MsgType: in.MsgType,
  147. Title: in.Title,
  148. Content: in.Content,
  149. WxPushUrl: in.WxPushUrl,
  150. AppPushUrl: in.AppPushUrl,
  151. ProductName: in.ProductName,
  152. OrderId: in.OrderId,
  153. OrderMoney: in.OrderMoney,
  154. Row4: in.Row4,
  155. }
  156. SentWxTmplAndAppPush(pushData, v, group_id, equityName, equityAddr)
  157. /*key := fmt.Sprintf(MsgCountKey, v, group_id)
  158. redis.Del(redisModule, key)
  159. if in.MsgType == 11 || in.MsgType == 12 {
  160. key1 := fmt.Sprintf(MsgClassCountKey, v, in.MsgType)
  161. redis.Del(redisModule, key1)
  162. }*/
  163. DelRedis(v, in.MsgType, group_id)
  164. }(userIdArr[i])
  165. }
  166. wg.Wait()
  167. return nil
  168. }
  169. func DelRedis(userId string, msgType int64, groupId int) {
  170. key := fmt.Sprintf(MsgCountKey, userId, groupId)
  171. redis.Del(redisModule, key)
  172. if msgType == 11 || msgType == 12 {
  173. key1 := fmt.Sprintf(MsgClassCountKey, userId, msgType)
  174. redis.Del(redisModule, key1)
  175. }
  176. if groupId == 5 || groupId == 11 {
  177. redis.Del(redisModule, fmt.Sprintf(UserWorkDeskKey, userId))
  178. }
  179. redis.Del(redisModule, fmt.Sprintf(UserMsgSummery, userId))
  180. redis.Del(redisModule, fmt.Sprintf(UserClassMapKey, userId))
  181. }
  182. func Update(ids []string, msgLogId int64) {
  183. // 查询是否存在 都存在updae 不存在的插入
  184. userMap := make(map[string]bool)
  185. row, err := entity.ClickhouseConn.Query(context.Background(), fmt.Sprintf("SELECT userId FROM message_user_summary where userId in ('%s')", strings.Join(ids, `','`)))
  186. if err != nil {
  187. log.Println("查询消息失败")
  188. return
  189. }
  190. for row.Next() {
  191. var userId string
  192. _ = row.Scan(&userId)
  193. userMap[userId] = true
  194. }
  195. if len(userMap) == len(ids) {
  196. log.Println(fmt.Sprintf(`alter table message_user_summary UPDATE allMsg = bitmapOr(allMsg,bitmapBuild([toUInt64(%d)])) where userId in ('%s')`, msgLogId, strings.Join(ids, `','`)))
  197. err1 := entity.ClickhouseConn.Exec(context.Background(), fmt.Sprintf(`alter table message_user_summary UPDATE allMsg = bitmapOr(allMsg,bitmapBuild([toUInt64(%d)])) where userId in ('%s')`, msgLogId, strings.Join(ids, `','`)))
  198. if err1 != nil {
  199. log.Printf("批量更新message_user_summary出错:%s", err1)
  200. return
  201. }
  202. } else {
  203. log.Println("匹配到数据量:", len(userMap))
  204. var uData, sqlArr []string
  205. for _, id := range ids {
  206. if userMap[id] {
  207. uData = append(uData, id)
  208. } else {
  209. sqlArr = append(sqlArr, fmt.Sprintf(" ('%s',bitmapBuild([toUInt64(%d)]),bitmapBuild([toUInt64(0)])) ", id, msgLogId))
  210. }
  211. }
  212. log.Println("缺失数据量:", len(sqlArr))
  213. if len(uData) > 0 {
  214. err1 := entity.ClickhouseConn.Exec(context.Background(), fmt.Sprintf(`alter table message_user_summary UPDATE allMsg = bitmapOr(allMsg,bitmapBuild([toUInt64(%d)])) where userId in ('%s')`, msgLogId, strings.Join(uData, `','`)))
  215. if err1 != nil {
  216. log.Printf("批量更新message_user_summary出错:%s", err1)
  217. }
  218. }
  219. if len(sqlArr) > 0 {
  220. //新用户需要insert
  221. sql := "INSERT INTO message_user_summary values %s"
  222. log.Println("sql", sql)
  223. err1 := entity.ClickhouseConn.Exec(context.Background(), fmt.Sprintf(sql, strings.Join(sqlArr, ",")))
  224. if err1 != nil {
  225. //插入失败
  226. log.Println("insert message_user_summary表出错,error", err1)
  227. }
  228. }
  229. }
  230. }
  231. // 附件下载、剑鱼币活动到期提醒存消息发送记录
  232. func InsertMsgSendLog(in *message.MultipleSaveMsgReq) int64 {
  233. groupId := MsgGroupIdMap[int(in.MsgType)]
  234. id := entity.Mysql.Insert("message_send_log", map[string]interface{}{
  235. "send_usergroup_id": "",
  236. "send_usergroup_name": "",
  237. "msg_type": in.MsgType,
  238. "title": in.Title,
  239. "content": in.Content,
  240. "send_mode": 2,
  241. "send_time": time.Now().Format("2006-01-02 15:04:05"),
  242. "send_status": 4,
  243. "update_time": time.Now().Format("2006-01-02 15:04:05"),
  244. "link": in.Link,
  245. "isdel": 1,
  246. "send_userid": "",
  247. "update_user": "",
  248. "Sign": 5,
  249. "menu_name": "message",
  250. "group_id": groupId,
  251. })
  252. if id > 0 {
  253. //更新消息汇总表
  254. err := SetMsgSummary(id, int64(groupId), in.MsgType)
  255. if err != nil {
  256. log.Println("更新消息汇总表出错:", err)
  257. return 0
  258. }
  259. return id
  260. }
  261. return 0
  262. }
  263. func ConvertToBitmap(num int) (res []uint32) {
  264. binary := strconv.FormatInt(int64(num), 2)
  265. total := len(binary)
  266. for i := total - 1; i >= 0; i-- {
  267. if binary[i] == '1' {
  268. res = append(res, uint32(total-i))
  269. }
  270. }
  271. return
  272. }
  273. type WxTmplAndPush struct {
  274. MsgType int64
  275. Title string
  276. Content string
  277. WxPushUrl string
  278. AppPushUrl string
  279. ProductName string
  280. OrderId string
  281. OrderMoney string
  282. Row4 string
  283. SendUserId string
  284. }
  285. func SentWxTmplAndAppPush(this WxTmplAndPush, v string, group_id int, equityName, equityAddr string) {
  286. nTime := time.Now().Format("2006-01-02 15:04:05")
  287. //发送消息成功,推送微信、app
  288. //fmt.Println("this.MsgType", this.MsgType)
  289. pushConfig, err := GetWxTmplConfig(this.MsgType)
  290. if err != nil {
  291. logx.Error(fmt.Sprintf("SendWxTmplMsg uId %s Error %s", v, err.Error()))
  292. }
  293. p := &WxTmplPush{
  294. Config: pushConfig,
  295. }
  296. p.MgoId = v
  297. if this.MsgType == 10 {
  298. this.Title = this.ProductName
  299. this.Content = this.OrderId
  300. nTime = this.OrderMoney
  301. }
  302. // 消息模版 工单类型 {{thing19.DATA}} 工单标题 {{thing6.DATA}} 项目名称 {{thing13.DATA}} 服务时间 {{time25.DATA}} 服务地址 {{thing26.DATA}}
  303. if this.MsgType != 1 && this.MsgType != 10 {
  304. if this.MsgType == config.ConfigJson.EquityInfoMsgType {
  305. // p459 服务地址特殊处理
  306. err = p.SendMsg(this.WxPushUrl, this.Title, equityName, nTime, this.Row4, equityAddr)
  307. } else {
  308. err = p.SendMsg(this.WxPushUrl, this.Title, this.Content, nTime, this.Row4, "")
  309. }
  310. if err != nil {
  311. logx.Error(fmt.Sprintf("SendWxTmplMsg uId %s Error %s", v, err.Error()))
  312. } else {
  313. logx.Infof("SendWxTmplMsg uId success %s ", v)
  314. }
  315. }
  316. if this.MsgType == 1 {
  317. mst := new(WxTmplConfig)
  318. mst.Switch = AppPushMsgType[group_id]
  319. p.Config = mst
  320. }
  321. uData := p.GetUserPushInfo()
  322. //app推送
  323. if this.MsgType != 10 {
  324. category := ""
  325. if this.SendUserId == "cbgl" {
  326. category = "服务通知_工作事项"
  327. }
  328. if err = AppPushMsg(uData, AppPushMsgType[group_id], this.AppPushUrl, this.Title, this.Content, this.MsgType, category); err != nil {
  329. logx.Error(fmt.Sprintf("SendAppMsg uId %s Error %s", v, err.Error()))
  330. }
  331. }
  332. }