task.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. StatisticalUser(true)
  19. c := cron.New(cron.WithSeconds())
  20. c.AddFunc(config.ConfigJson.GlobMsgLoadTime, LoadMsgOnTime)
  21. c.AddFunc(config.ConfigJson.FreeIntelTime, FreeIntelUserPush) //免费用户推送
  22. c.AddFunc(config.ConfigJson.PayIntelTime, PayIntelUserPush) //付费用户推送
  23. go c.Start()
  24. defer c.Stop()
  25. }
  26. func LoadMsgOnTime() {
  27. fmt.Println("开始执行")
  28. msgMap := make(map[int]map[string]interface{})
  29. 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")
  30. if m != nil && len(*m) > 0 {
  31. for _, val := range *m {
  32. msgMap[common.IntAll(val["id"])] = val
  33. }
  34. GlobMsgMap = msgMap
  35. }
  36. fmt.Println("GlobMsgMap len", len(GlobMsgMap))
  37. }
  38. func FreeIntelUserPush() {
  39. ids := FreeMessageData(config.ConfigJson.FreePushNumber)
  40. if len(ids) == 0 {
  41. return
  42. }
  43. users := StatisticalUser(true)
  44. PushData(users, ids, nil)
  45. }
  46. func PayIntelUserPush() {
  47. data := messageData(config.ConfigJson.PayPushNumber)
  48. if data == nil || len(*data) == 0 {
  49. return
  50. }
  51. users := StatisticalUser(false)
  52. PushData(users, nil, data)
  53. }
  54. func PushData(users []string, ids []int64, data *[]map[string]interface{}) {
  55. log.Printf("需推送用户:%d\n", len(users))
  56. switch len(ids) {
  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. var bits []string
  108. for _, i2 := range ids {
  109. bits = append(bits, fmt.Sprintf("toUInt64(%d)", i2))
  110. }
  111. log.Println(fmt.Sprintf(`alter table message_user_summary UPDATE allMsg = bitmapOr(allMsg,bitmapBuild([%s])) where 1=1`, strings.Join(bits, ",")))
  112. err1 := entity.ClickhouseConn.Exec(context.Background(), fmt.Sprintf(`alter table message_user_summary UPDATE allMsg = bitmapOr(allMsg,bitmapBuild([%s])) where 1=1`, strings.Join(bits, ",")))
  113. if err1 != nil {
  114. log.Printf("批量更新message_user_summary出错:%s", err1)
  115. return
  116. }
  117. for _, userid := range users {
  118. keyString := fmt.Sprintf(MsgCountKey, userid, 5)
  119. redis.Del(redisModule, keyString)
  120. }
  121. }
  122. log.Println("PushData完成")
  123. }
  124. // 用户
  125. func StatisticalUser(isFree bool) []string {
  126. var ids []string
  127. mUser := make(map[string]bool) //商机管理用户
  128. 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 != ''`)
  129. if data != nil && len(*data) > 0 { //统计商机管理用户
  130. for _, m := range *data {
  131. if common.InterfaceToStr(m["phone"]) != "" {
  132. mUser[common.InterfaceToStr(m["phone"])] = true
  133. }
  134. }
  135. }
  136. log.Printf("获取商机管理用户:%d\n", len(mUser))
  137. //企业大会员或超级订阅
  138. entPayUser, ok := entity.MQFW.Find("ent_user", map[string]interface{}{
  139. "$or": []map[string]interface{}{
  140. { //个人订阅
  141. "i_vip_status": map[string]interface{}{
  142. "$gt": 0,
  143. },
  144. },
  145. { //个人大会员
  146. "i_member_status": map[string]interface{}{
  147. "$gt": 0,
  148. },
  149. },
  150. },
  151. }, nil, `{"i_userid":1}`, false, -1, -1)
  152. if ok && entPayUser != nil && len(*entPayUser) > 0 {
  153. var userIds []string
  154. for k, m := range *entPayUser {
  155. userIds = append(userIds, common.InterfaceToStr(m["i_userid"]))
  156. if len(userIds) == 100 || k == len(*entPayUser)-1 {
  157. idSql := fmt.Sprintf(`SELECT phone FROM entniche_user WHERE id in (%s)`, strings.Join(userIds, `,`))
  158. phoneArr := entity.Mysql.SelectBySql(idSql)
  159. if phoneArr != nil && len(*phoneArr) > 0 {
  160. for _, m2 := range *phoneArr {
  161. if common.InterfaceToStr(m2["phone"]) != "" {
  162. mUser[common.InterfaceToStr(m2["phone"])] = true
  163. }
  164. }
  165. }
  166. userIds = []string{}
  167. }
  168. }
  169. }
  170. log.Printf("获取商机管理+企业付费用户:%d\n", len(mUser))
  171. switch isFree {
  172. case false: //付费用户
  173. payMap := make(map[string]bool)
  174. payUsers, _ := entity.MQFW.Find("user", map[string]interface{}{
  175. "$or": []map[string]interface{}{
  176. { //个人订阅
  177. "i_vip_status": map[string]interface{}{
  178. "$gt": 0,
  179. },
  180. },
  181. { //个人大会员
  182. "i_member_status": map[string]interface{}{
  183. "$gt": 0,
  184. },
  185. },
  186. },
  187. }, nil, `{"_id":1,"s_phone":1,"s_m_phone":1}`, false, -1, -1)
  188. if payUsers != nil && len(*payUsers) > 0 {
  189. for _, m := range *payUsers {
  190. phone := common.If(common.InterfaceToStr(m["s_phone"]) == "", common.InterfaceToStr(m["s_m_phone"]), common.InterfaceToStr(m["s_phone"])).(string)
  191. payMap[common.InterfaceToStr(m["_id"])] = true
  192. if mUser[phone] { //避免重复获取
  193. delete(mUser, phone)
  194. }
  195. }
  196. }
  197. var (
  198. phones []string
  199. count int
  200. )
  201. maxCount := len(mUser)
  202. for phone := range mUser { //获取剩余商机管理与企业付费用户
  203. count++
  204. phones = append(phones, phone)
  205. if len(phones) == 100 || count == maxCount {
  206. entPayUsers, _ := entity.MQFW.Find("user", map[string]interface{}{
  207. "$or": []map[string]interface{}{
  208. {"s_phone": map[string]interface{}{ //企业订阅||大会员||商机管理
  209. "$in": phones,
  210. }},
  211. {"s_m_phone": map[string]interface{}{ //企业订阅||大会员||商机管理
  212. "$in": phones,
  213. }},
  214. },
  215. }, nil, `{"_id":1}`, false, -1, -1)
  216. if entPayUsers != nil && len(*entPayUsers) > 0 {
  217. for _, m := range *entPayUsers {
  218. payMap[common.InterfaceToStr(m["_id"])] = true
  219. }
  220. }
  221. phones = []string{}
  222. }
  223. }
  224. for id := range payMap {
  225. ids = append(ids, id)
  226. }
  227. case true:
  228. sess := entity.MQFW.GetMgoConn()
  229. defer entity.MQFW.DestoryMongoConn(sess)
  230. iter := sess.DB("qfw").C("user").Find(map[string]interface{}{
  231. "i_appid": 2,
  232. }).Select(map[string]interface{}{"_id": 1, "i_vip_status": 1, "i_member_status": 1, "s_phone": 1, "s_m_phone": 1}).Iter()
  233. for m := make(map[string]interface{}); iter.Next(&m); {
  234. if common.IntAll(m["i_vip_status"]) <= 0 && common.IntAll(m["i_member_status"]) <= 0 {
  235. phone := common.If(common.InterfaceToStr(m["s_phone"]) == "", common.InterfaceToStr(m["s_m_phone"]), common.InterfaceToStr(m["s_phone"])).(string)
  236. if !mUser[phone] {
  237. ids = append(ids, common.InterfaceToStr(m["_id"]))
  238. }
  239. }
  240. m = map[string]interface{}{}
  241. }
  242. }
  243. log.Printf("用户类型:%v,用户数:%d", isFree, len(ids))
  244. return ids
  245. }
  246. // 获取推送消息
  247. func messageData(number int) *[]map[string]interface{} {
  248. now := time.Now().AddDate(0, 0, -1)
  249. starttime := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).Unix()
  250. enttime := time.Date(now.Year(), now.Month(), now.Day(), 24, 0, 0, 0, time.Local).Unix()
  251. query := map[string]interface{}{
  252. "yucetime": map[string]interface{}{"$gt": starttime, "$lt": enttime},
  253. }
  254. data, _ := entity.Bidding.Find("project_forecast", query, `{"yucetime": -1}`, `{"title":1,"_id":1}`, false, 0, number)
  255. return data
  256. }
  257. func FreeMessageData(number int) []int64 {
  258. var ids []int64
  259. now := time.Now()
  260. startTime := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).String()
  261. 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))
  262. if m != nil && len(*m) > 0 {
  263. for _, i2 := range *m {
  264. ids = append(ids, common.Int64All(i2["id"]))
  265. }
  266. }
  267. return ids
  268. }
  269. func UpdateBatch(ids []string, bitStr string) {
  270. str := fmt.Sprintf(`'%s'`, strings.Join(ids, `','`))
  271. log.Println(fmt.Sprintf(`alter table message_user_summary UPDATE allMsg = bitmapOr(allMsg,bitmapBuild([%s])) where userId in (%s)`, bitStr, str))
  272. err1 := entity.ClickhouseConn.Exec(context.Background(), fmt.Sprintf(`alter table message_user_summary UPDATE allMsg = bitmapOr(allMsg,bitmapBuild([%s])) where userId in (%s)`, bitStr, str))
  273. if err1 != nil {
  274. log.Printf("批量更新message_user_summary出错:%s", err1)
  275. return
  276. }
  277. for _, id := range ids {
  278. keyString := fmt.Sprintf(MsgCountKey, id, 5)
  279. redis.Del(redisModule, keyString)
  280. }
  281. }