task.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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/jybase/common"
  6. "app.yhyue.com/moapp/jybase/encrypt"
  7. "app.yhyue.com/moapp/jybase/redis"
  8. "context"
  9. "fmt"
  10. "github.com/robfig/cron/v3"
  11. "log"
  12. "strings"
  13. "time"
  14. )
  15. var GlobMsgMap map[int]map[string]interface{}
  16. func LoadTask() {
  17. // 每隔10分钟执行一次
  18. c := cron.New(cron.WithSeconds())
  19. c.AddFunc(config.ConfigJson.GlobMsgLoadTime, LoadMsgOnTime)
  20. c.AddFunc(config.ConfigJson.FreeIntelTime, FreeIntelUserPush) //免费用户推送
  21. c.AddFunc(config.ConfigJson.PayIntelTime, PayIntelUserPush) //付费用户推送
  22. go c.Start()
  23. defer c.Stop()
  24. }
  25. func LoadMsgOnTime() {
  26. fmt.Println("开始执行")
  27. msgMap := make(map[int]map[string]interface{})
  28. m := entity.Mysql.SelectBySql("SELECT id,msg_type,title,content,send_time,menu_name,link,group_id,sign FROM message_send_log WHERE send_status = 4 AND isdel = 1 ORDER BY send_time DESC limit 2000")
  29. if m != nil && len(*m) > 0 {
  30. for _, val := range *m {
  31. msgMap[common.IntAll(val["id"])] = val
  32. }
  33. GlobMsgMap = msgMap
  34. }
  35. fmt.Println("GlobMsgMap len", len(GlobMsgMap))
  36. }
  37. func FreeIntelUserPush() {
  38. id := FreeMessageData(config.ConfigJson.FreePushNumber)
  39. if id == 0 {
  40. return
  41. }
  42. users := StatisticalUser(true)
  43. PushData(users, id, nil)
  44. }
  45. func PayIntelUserPush() {
  46. data := messageData(config.ConfigJson.PayPushNumber)
  47. if data == nil || len(*data) == 0 {
  48. return
  49. }
  50. users := StatisticalUser(false)
  51. PushData(users, 0, data)
  52. }
  53. func PushData(users []string, id int64, data *[]map[string]interface{}) {
  54. log.Printf("需推送用户:%d\n", len(users))
  55. var ids []int64
  56. switch id {
  57. case 0: //付费用户
  58. if data != nil {
  59. for _, m := range *data {
  60. _id := common.InterfaceToStr(m["_id"])
  61. var link []string
  62. link = append(link, fmt.Sprintf("/swordfish/page_big_pc/business_detail/%s", encrypt.EncodeArticleId2ByCheck(_id)))
  63. mobLink := fmt.Sprintf("/jy_mobile/business/detail/%s", encrypt.EncodeArticleId2ByCheck(_id))
  64. link = append(link, mobLink)
  65. link = append(link, mobLink)
  66. link = append(link, mobLink)
  67. iData := map[string]interface{}{
  68. "msg_type": 9,
  69. "title": "您有一条专属商机情报",
  70. "content": fmt.Sprintf("【商机情报】%s", common.ObjToString(m["title"])),
  71. "send_mode": 1,
  72. "send_time": time.Now().Format("2006-01-02 15:04:05"),
  73. "send_status": 4,
  74. "update_time": time.Now().Format("2006-01-02 15:04:05"),
  75. "createtime": time.Now().Format("2006-01-02 15:04:05"),
  76. "link": strings.Join(link, ","),
  77. "isdel": 1,
  78. "send_userid": "商机情报定时推送",
  79. "sign": 0,
  80. "group_id": 5,
  81. }
  82. logId := entity.Mysql.Insert("message_send_log", iData)
  83. ids = append(ids, logId)
  84. }
  85. }
  86. if len(ids) > 0 {
  87. var bits []string
  88. for _, i2 := range ids {
  89. bits = append(bits, fmt.Sprintf("toUInt64(%d)", i2))
  90. }
  91. biyStr := strings.Join(bits, ",")
  92. err := entity.ClickhouseConn.Exec(context.Background(), fmt.Sprintf(`alter table message_summary UPDATE msg_bitmap = bitmapOr(msg_bitmap,bitmapBuild([%s])) where group_id = %d`, biyStr, 5))
  93. if err != nil {
  94. log.Println("message_summary err=== ", err.Error())
  95. return
  96. }
  97. var userIds []string
  98. for k, user := range users {
  99. userIds = append(userIds, user)
  100. if len(userIds) == 1000 || k == len(users)-1 {
  101. UpdateBatch(userIds, biyStr)
  102. userIds = []string{}
  103. }
  104. }
  105. }
  106. default: //免费用户
  107. log.Println(fmt.Sprintf(`alter table message_user_summary UPDATE allMsg = bitmapOr(allMsg,bitmapBuild([toUInt64(%d)])) where 1=1`, id))
  108. err1 := entity.ClickhouseConn.Exec(context.Background(), fmt.Sprintf(`alter table message_user_summary UPDATE allMsg = bitmapOr(allMsg,bitmapBuild([toUInt64(%d)])) where 1=1`, id))
  109. if err1 != nil {
  110. log.Printf("批量更新message_user_summary出错:%s", err1)
  111. return
  112. }
  113. for _, userid := range users {
  114. keyString := fmt.Sprintf(MsgCountKey, userid, 5)
  115. redis.Del(redisModule, keyString)
  116. }
  117. }
  118. log.Println("PushData完成")
  119. }
  120. // 用户
  121. func StatisticalUser(isFree bool) []string {
  122. var ids []string
  123. mUser := make(map[string]bool) //商机管理用户
  124. data := entity.Mysql.SelectBySql(`SELECT a.phone as phone FROM entniche_user a INNER JOIN entniche_info b on b.status = 1 and a.power = 1 and a.ent_id = b.id and a.phone != ''`)
  125. if data != nil && len(*data) > 0 { //统计商机管理用户
  126. for _, m := range *data {
  127. if common.InterfaceToStr(m["phone"]) != "" {
  128. mUser[common.InterfaceToStr(m["phone"])] = true
  129. }
  130. }
  131. }
  132. log.Printf("获取商机管理用户:%d\n", len(mUser))
  133. //企业大会员或超级订阅
  134. entPayUser, ok := entity.MQFW.Find("ent_user", map[string]interface{}{
  135. "$or": []map[string]interface{}{
  136. { //个人订阅
  137. "i_vip_status": map[string]interface{}{
  138. "$gt": 0,
  139. },
  140. },
  141. { //个人大会员
  142. "i_member_status": map[string]interface{}{
  143. "$gt": 0,
  144. },
  145. },
  146. },
  147. }, nil, `{"i_userid":1}`, false, -1, -1)
  148. if ok && entPayUser != nil && len(*entPayUser) > 0 {
  149. var userIds []string
  150. for k, m := range *entPayUser {
  151. userIds = append(userIds, common.InterfaceToStr(m["i_userid"]))
  152. if len(userIds) == 100 || k == len(*entPayUser)-1 {
  153. idSql := fmt.Sprintf(`SELECT phone FROM entniche_user WHERE id in (%s)`, strings.Join(userIds, `,`))
  154. phoneArr := entity.Mysql.SelectBySql(idSql)
  155. if phoneArr != nil && len(*phoneArr) > 0 {
  156. for _, m2 := range *phoneArr {
  157. if common.InterfaceToStr(m2["phone"]) != "" {
  158. mUser[common.InterfaceToStr(m2["phone"])] = true
  159. }
  160. }
  161. }
  162. userIds = []string{}
  163. }
  164. }
  165. }
  166. log.Printf("获取商机管理+企业付费用户:%d\n", len(mUser))
  167. switch isFree {
  168. case false: //付费用户
  169. payMap := make(map[string]bool)
  170. payUsers, _ := entity.MQFW.Find("user", map[string]interface{}{
  171. "$or": []map[string]interface{}{
  172. { //个人订阅
  173. "i_vip_status": map[string]interface{}{
  174. "$gt": 0,
  175. },
  176. },
  177. { //个人大会员
  178. "i_member_status": map[string]interface{}{
  179. "$gt": 0,
  180. },
  181. },
  182. },
  183. }, nil, `{"_id":1,"s_phone":1,"s_m_phone":1}`, false, -1, -1)
  184. if payUsers != nil && len(*payUsers) > 0 {
  185. for _, m := range *payUsers {
  186. phone := common.If(common.InterfaceToStr(m["s_phone"]) == "", common.InterfaceToStr(m["s_m_phone"]), common.InterfaceToStr(m["s_phone"])).(string)
  187. payMap[common.InterfaceToStr(m["_id"])] = true
  188. if mUser[phone] { //避免重复获取
  189. delete(mUser, phone)
  190. }
  191. }
  192. }
  193. var (
  194. phones []string
  195. count int
  196. )
  197. maxCount := len(mUser)
  198. for phone := range mUser { //获取剩余商机管理与企业付费用户
  199. count++
  200. phones = append(phones, phone)
  201. if len(phones) == 100 || count == maxCount {
  202. entPayUsers, _ := entity.MQFW.Find("user", map[string]interface{}{
  203. "$or": []map[string]interface{}{
  204. {"s_phone": map[string]interface{}{ //企业订阅||大会员||商机管理
  205. "$in": phones,
  206. }},
  207. {"s_m_phone": map[string]interface{}{ //企业订阅||大会员||商机管理
  208. "$in": phones,
  209. }},
  210. },
  211. }, nil, `{"_id":1}`, false, -1, -1)
  212. if entPayUsers != nil && len(*entPayUsers) > 0 {
  213. for _, m := range *entPayUsers {
  214. payMap[common.InterfaceToStr(m["_id"])] = true
  215. }
  216. }
  217. phones = []string{}
  218. }
  219. }
  220. for id := range payMap {
  221. ids = append(ids, id)
  222. }
  223. case true:
  224. sess := entity.MQFW.GetMgoConn()
  225. defer entity.MQFW.DestoryMongoConn(sess)
  226. iter := sess.DB("qfw").C("user").Find(map[string]interface{}{
  227. "i_appid": 2,
  228. }).Select(map[string]interface{}{"_id": 1, "i_vip_status": 1, "i_member_status": 1, "s_phone": 1, "s_m_phone": 1}).Iter()
  229. for m := make(map[string]interface{}); iter.Next(&m); {
  230. if common.IntAll(m["i_vip_status"]) <= 0 && common.IntAll(m["i_member_status"]) <= 0 {
  231. phone := common.If(common.InterfaceToStr(m["s_phone"]) == "", common.InterfaceToStr(m["s_m_phone"]), common.InterfaceToStr(m["s_phone"])).(string)
  232. if !mUser[phone] {
  233. ids = append(ids, common.InterfaceToStr(m["_id"]))
  234. }
  235. }
  236. m = map[string]interface{}{}
  237. }
  238. }
  239. log.Printf("用户类型:%v,用户数:%d", isFree, len(ids))
  240. return ids
  241. }
  242. // 获取推送消息
  243. func messageData(number int) *[]map[string]interface{} {
  244. now := time.Now().AddDate(0, 0, -1)
  245. starttime := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).Unix()
  246. enttime := time.Date(now.Year(), now.Month(), now.Day(), 24, 0, 0, 0, time.Local).Unix()
  247. query := map[string]interface{}{
  248. "yucetime": map[string]interface{}{"$gt": starttime, "$lt": enttime},
  249. }
  250. data, _ := entity.Bidding.Find("project_forecast", query, `{"yucetime": -1}`, `{"title":1,"_id":1}`, false, 0, number)
  251. return data
  252. }
  253. func FreeMessageData(number int) int64 {
  254. now := time.Now()
  255. startTime := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).String()
  256. m := entity.Mysql.SelectBySql(fmt.Sprintf(`SELECT id FROM message_send_log WHERE createtime > '%s' and send_userid = '商机情报定时推送' ORDER BY createtime DESC LIMIT %d `, startTime, number))
  257. if m != nil && len(*m) > 0 {
  258. return common.Int64All((*m)[0]["id"])
  259. }
  260. return 0
  261. }
  262. func UpdateBatch(ids []string, biyStr string) {
  263. str := fmt.Sprintf(`'%s'`, strings.Join(ids, `','`))
  264. log.Println(fmt.Sprintf(`alter table message_user_summary UPDATE allMsg = bitmapOr(allMsg,bitmapBuild([%s])) where userId in (%s)`, biyStr, str))
  265. err1 := entity.ClickhouseConn.Exec(context.Background(), fmt.Sprintf(`alter table message_user_summary UPDATE allMsg = bitmapOr(allMsg,bitmapBuild([%s])) where userId in (%s)`, biyStr, str))
  266. if err1 != nil {
  267. log.Printf("批量更新message_user_summary出错:%s", err1)
  268. return
  269. }
  270. for _, id := range ids {
  271. keyString := fmt.Sprintf(MsgCountKey, id, 5)
  272. redis.Del(redisModule, keyString)
  273. }
  274. }