newestBidding.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. package model
  2. import (
  3. "app.yhyue.com/moapp/jybase/redis"
  4. "encoding/json"
  5. "fmt"
  6. "jyBXBase/rpc/bxbase"
  7. IC "jyBXBase/rpc/init"
  8. "log"
  9. "strings"
  10. "time"
  11. MC "app.yhyue.com/moapp/jybase/common"
  12. ME "app.yhyue.com/moapp/jybase/encrypt"
  13. elastic "app.yhyue.com/moapp/jybase/es"
  14. "app.yhyue.com/moapp/jybase/mongodb"
  15. "app.yhyue.com/moapp/jybase/mysql"
  16. "github.com/zeromicro/go-zero/core/logx"
  17. "go.mongodb.org/mongo-driver/bson/primitive"
  18. )
  19. const (
  20. search_index = "bidding"
  21. search_type = "bidding"
  22. mongodb_fields = `{"_id":1,"area":1,"publishtime":1,"s_subscopeclass":1,"subtype":1,"title":1,"toptype":1,"type":1, "buyerclass":1,"budget":1,"bidamount":1,"s_winner":1,"bidopentime":1,"buyer":1,"projectname":1,"spidercode":1,"site":1}`
  23. query = `{"query":{"terms":{"_id":["%s"]}},"_source":["_id","area", "publishtime", "s_subscopeclass", "subtype", "title", "toptype", "type", "buyerclass","bidamount","budget","projectname","buyer","bidopentime","s_winner","filetext","spidercode","site"],"from":0,"size":%d}`
  24. multi_match = `{"multi_match": {"query": %s,"type": "phrase", "fields": ["title"]}}`
  25. query_bool_must = `{"terms":{"%s":[%s]}}`
  26. query_bool_must_and = `{"bool":{"must":[%s],"must_not":[%s]}}`
  27. search_field = `"_id","area", "publishtime", "s_subscopeclass", "subtype", "title", "toptype", "type", "buyerclass","bidamount","budget","projectname","buyer","bidopentime","s_winner","filetext","isValidFile","spidercode","site"`
  28. query_city_hkeys = `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match":%d}},"highlight": {"pre_tags": ["<a>"],"post_tags": ["</a>"],"fields": {"title": {"fragment_size": 0,"number_of_fragments": 1}}},"_source":[` + search_field + `],"sort":[{"publishtime":"desc"},{"budget":"desc"}],"from":0,"size":%d}`
  29. Pushbidding = "global_common_data.dws_f_bid_baseinfo"
  30. Province = "province"
  31. StatusNoLogin = 1 // 1-未登录用户
  32. StatusLoginUser = 2 // 2-用户自己的key
  33. StatusLogin = 3 // 3-登录用户最新标讯
  34. StatusCache = 0 // 0 -不存缓存 本来查的就是缓存的数据
  35. )
  36. type NewestInfo struct {
  37. TableName string
  38. UserId string
  39. MysqlDb *mysql.Mysql
  40. NewUserId int64
  41. PushMysql *mysql.Mysql
  42. NewsLimitNum int64 // 最新标讯数量条数限制
  43. }
  44. var mysqlTables = map[string]string{
  45. "f": "push.pushsubscribe",
  46. "v": "push.pushsubscribe",
  47. "m": "push.pushmember",
  48. "e": "push.pushentniche",
  49. }
  50. func GetRoleNewestInfoService(AppId, MgoUserId string, NewUserId, AccountId, EntId, EntUserId, PositionType, PositionId int64) (roleNewestInfo *NewestInfo, flag string) {
  51. powerCheck := IC.Middleground.PowerCheckCenter.Check(AppId, MgoUserId, NewUserId, AccountId, EntId, PositionType, PositionId)
  52. thisUserId := MC.If(PositionType == 1, MC.InterfaceToStr(EntUserId), MC.InterfaceToStr(NewUserId)).(string)
  53. thisNewUserId := MC.If(PositionType == 1, EntUserId, NewUserId).(int64)
  54. if powerCheck.Member.Status > 0 {
  55. // 大会员
  56. flag = "m"
  57. } else if powerCheck.Entniche.Status > 0 && powerCheck.Entniche.PowerSource != 1 && powerCheck.Entniche.IsEntPower == 1 {
  58. // 商机管理
  59. flag = "e"
  60. } else if powerCheck.Vip.Status > 0 {
  61. // 超级订阅
  62. flag = "v"
  63. } else {
  64. // 普通用户
  65. flag = "f"
  66. }
  67. thisUserType := MC.If(PositionType == 1, "e", flag).(string)
  68. return GetNewestInfo(thisUserId, thisUserType, thisNewUserId), flag
  69. }
  70. func GetNewestInfo(userId, userType string, newUserId int64) *NewestInfo {
  71. nt := &NewestInfo{
  72. UserId: userId,
  73. TableName: mysqlTables[userType],
  74. MysqlDb: IC.BaseServiceMysql,
  75. NewUserId: newUserId,
  76. NewsLimitNum: IC.C.NewsLimitNum,
  77. }
  78. return nt
  79. }
  80. // GetPushHistoryCount 缓存code 配置最新的redis code;可以感觉redis内存大小 调节redis存储;
  81. // 根据GetPushHistoryCount 返回值 作为列表缓存key中一个参数
  82. func (n *NewestInfo) GetPushHistoryCount() int64 {
  83. countKey := fmt.Sprintf(IC.C.NewsCache.Count.Key, n.TableName, n.UserId)
  84. if b := redis.GetInt("new", countKey); b != 0 {
  85. return int64(b)
  86. }
  87. countSql := "SELECT COUNT(1) FROM (SELECT 1 FROM %s WHERE userid = %d LIMIT 1) AS ph"
  88. //countSql := "select count(1) from %s a where a.userid=%d order by a.id desc"
  89. countSql = fmt.Sprintf(countSql, n.TableName, n.NewUserId)
  90. timeOut := IC.C.NewsCache.Count.Timeout
  91. c := n.MysqlDb.CountBySql(countSql)
  92. if c > 0 {
  93. timeOut = timeOut * 4
  94. } else {
  95. c = -1
  96. }
  97. redis.Put("new", countKey, c, IC.C.NewsCache.Count.Timeout) //过期时间走配置,比最新标讯列表缓存时间 要短1/10 尽量不超过两分钟
  98. return c
  99. }
  100. func (n *NewestInfo) GetPushHistory() (res []*bxbase.NewestList) {
  101. findSQL := "select a.infoid,REPLACE(a.matchkeys,'+',' ') as matchkeys,a.attachment_count,a.budget,a.bidamount from %s a where a.userid=%d order by a.id desc limit ?"
  102. findSQL = fmt.Sprintf(findSQL, n.TableName, n.NewUserId)
  103. logx.Info(n.TableName, "-------", n.NewUserId, ",findSQL:", findSQL)
  104. list := n.MysqlDb.SelectBySql(findSQL, n.NewsLimitNum)
  105. if len(*list) > 0 && list != nil {
  106. m := map[string]bool{}
  107. es_ids := []string{}
  108. infos := map[string]*bxbase.NewestList{}
  109. for _, v := range *list {
  110. infoId := MC.ObjToString(v["infoid"])
  111. if m[infoId] {
  112. continue
  113. }
  114. es_ids = append(es_ids, infoId)
  115. m[MC.ObjToString(v["infoid"])] = true
  116. //
  117. infos[infoId] = &bxbase.NewestList{
  118. Id: ME.EncodeArticleId2ByCheck(MC.ObjToString(v["infoid"])),
  119. Matchkeys: strings.Split(MC.ObjToString(v["matchkeys"]), " "),
  120. Budget: MC.Int64All(v["budget"]),
  121. Bidamount: MC.Int64All(v["bidamount"]),
  122. FileExists: MC.Int64All(v["attachment_count"]) > 0,
  123. }
  124. }
  125. if len(es_ids) > 0 {
  126. list := elastic.Get(search_index, search_type, fmt.Sprintf(query, strings.Join(es_ids, `","`), len(es_ids)))
  127. if list != nil {
  128. for _, v := range *list {
  129. _id := MC.ObjToString(v["_id"])
  130. bn := infos[_id]
  131. bn.Title = MC.ObjToString(v["title"])
  132. bn.PublishTime = MC.Int64All(v["publishtime"])
  133. bn.Subtype = MC.If(v["subtype"] != nil, MC.ObjToString(v["subtype"]), MC.ObjToString(v["toptype"])).(string)
  134. bn.Area = MC.If(MC.ObjToString(v["area"]) == "A", "全国", MC.ObjToString(v["area"])).(string)
  135. bn.Buyerclass = MC.ObjToString(v["buyerclass"])
  136. bn.City = MC.ObjToString(v["city"])
  137. bn.Industry = MC.If(MC.ObjToString(v["s_subscopeclass"]) != "", strings.Split(strings.Split(MC.ObjToString(v["s_subscopeclass"]), ",")[0], "_")[0], "").(string)
  138. bn.SpiderCode = MC.ObjToString(v["spidercode"])
  139. bn.Site = MC.ObjToString(v["site"])
  140. }
  141. }
  142. }
  143. //mongodb bidding
  144. mgo_ids := []primitive.ObjectID{}
  145. for _, v := range es_ids {
  146. if infos[v].Title == "" {
  147. mgo_ids = append(mgo_ids, mongodb.StringTOBsonId(v))
  148. }
  149. }
  150. if len(mgo_ids) > 0 {
  151. list, ok := IC.MgoBidding.Find("bidding", map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_ids}}, nil, mongodb_fields, false, -1, -1)
  152. if ok && *list != nil {
  153. for _, v := range *list {
  154. _id := mongodb.BsonIdToSId(v["_id"])
  155. bn := infos[_id]
  156. bn.Title = MC.ObjToString(v["title"])
  157. bn.PublishTime = MC.Int64All(v["publishtime"])
  158. bn.Subtype = MC.If(v["subtype"] != nil, MC.ObjToString(v["subtype"]), MC.ObjToString(v["toptype"])).(string)
  159. bn.Area = MC.If(MC.ObjToString(v["area"]) == "A", "全国", MC.ObjToString(v["area"])).(string)
  160. bn.Buyerclass = MC.ObjToString(v["buyerclass"])
  161. bn.City = MC.ObjToString(v["city"])
  162. bn.Industry = MC.If(MC.ObjToString(v["s_subscopeclass"]) != "", strings.Split(strings.Split(MC.ObjToString(v["s_subscopeclass"]), ",")[0], "_")[0], "").(string)
  163. bn.SpiderCode = MC.ObjToString(v["spidercode"])
  164. bn.Site = MC.ObjToString(v["site"])
  165. }
  166. }
  167. }
  168. //mongodb bidding_back
  169. mgo_back_ids := []primitive.ObjectID{}
  170. for _, v := range mgo_ids {
  171. if infos[mongodb.BsonIdToSId(v)].Title == "" {
  172. mgo_back_ids = append(mgo_back_ids, v)
  173. }
  174. }
  175. if len(mgo_back_ids) > 0 {
  176. list, ok := IC.MgoBidding.Find("bidding_back", map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_back_ids}}, nil, mongodb_fields, false, -1, -1)
  177. if ok && *list != nil {
  178. for _, v := range *list {
  179. _id := mongodb.BsonIdToSId(v["_id"])
  180. bn := infos[_id]
  181. bn.Title = MC.ObjToString(v["title"])
  182. bn.PublishTime = MC.Int64All(v["publishtime"])
  183. bn.Subtype = MC.If(v["subtype"] != nil, MC.ObjToString(v["subtype"]), MC.ObjToString(v["toptype"])).(string)
  184. bn.Area = MC.If(MC.ObjToString(v["area"]) == "A", "全国", MC.ObjToString(v["area"])).(string)
  185. bn.Buyerclass = MC.ObjToString(v["buyerclass"])
  186. bn.City = MC.ObjToString(v["city"])
  187. bn.Industry = MC.If(MC.ObjToString(v["s_subscopeclass"]) != "", strings.Split(strings.Split(MC.ObjToString(v["s_subscopeclass"]), ",")[0], "_")[0], "").(string)
  188. bn.SpiderCode = MC.ObjToString(v["spidercode"])
  189. bn.Site = MC.ObjToString(v["site"])
  190. }
  191. }
  192. }
  193. //
  194. for _, v := range infos {
  195. res = append(res, v)
  196. }
  197. }
  198. return
  199. }
  200. // 根据定位或者搜索历史 查es
  201. func NewestQuery(city, keys, subtype string) (str string) {
  202. var musts, bools []string
  203. if keys != "" {
  204. for _, v := range strings.Split(keys, ",") {
  205. keys := strings.Split(v, " ") //历史搜索 空格划分
  206. must_tmp := []string{}
  207. for _, key := range keys {
  208. must_tmp = append(must_tmp, fmt.Sprintf(multi_match, "\""+key+"\""))
  209. }
  210. bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(must_tmp, ","), ""))
  211. }
  212. }
  213. if city != "" {
  214. musts = append(musts, fmt.Sprintf(query_bool_must, "city", `"`+city+`"`))
  215. }
  216. //未登录首页推送数据限制
  217. if subtype != "" {
  218. musts = append(musts, fmt.Sprintf(query_bool_must, "subtype", subtype))
  219. }
  220. minimum_should_match := 0
  221. if len(bools) > 0 {
  222. minimum_should_match = 1
  223. }
  224. str = fmt.Sprintf(query_city_hkeys, strings.Join(musts, ","), strings.Join(bools, ","), minimum_should_match, IC.C.NewsLimitNum)
  225. logx.Info("str:", str)
  226. return
  227. }
  228. // es查询
  229. func NewestES(doSearchStr string) (res []*bxbase.NewestList) {
  230. list := elastic.Get(search_index, search_type, doSearchStr)
  231. if list != nil && len(*list) > 0 {
  232. for _, v := range *list {
  233. _id := mongodb.BsonIdToSId(v["_id"])
  234. isValidFile, _ := v["isValidFile"].(bool)
  235. res = append(res, &bxbase.NewestList{
  236. Id: ME.EncodeArticleId2ByCheck(_id),
  237. Title: MC.ObjToString(v["title"]),
  238. Subtype: MC.If(v["subtype"] != nil, MC.ObjToString(v["subtype"]), MC.ObjToString(v["toptype"])).(string),
  239. Area: MC.If(MC.ObjToString(v["area"]) == "A", "全国", MC.ObjToString(v["area"])).(string),
  240. Buyerclass: MC.ObjToString(v["buyerclass"]),
  241. City: MC.ObjToString(v["city"]),
  242. Industry: MC.If(MC.ObjToString(v["s_subscopeclass"]) != "", strings.Split(strings.Split(MC.ObjToString(v["s_subscopeclass"]), ",")[0], "_")[0], "").(string),
  243. Budget: MC.Int64All(v["budget"]),
  244. Bidamount: MC.Int64All(v["bidamount"]),
  245. FileExists: isValidFile, //附件
  246. PublishTime: MC.Int64All(v["publishtime"]),
  247. Site: MC.ObjToString(v["site"]),
  248. SpiderCode: MC.ObjToString(v["spidercode"]),
  249. })
  250. }
  251. }
  252. return
  253. }
  254. // GetRedisKeyTimeout 获取缓存的key 和超时时间
  255. func GetRedisKeyTimeout(status int, positionId int64) (redisKey string, timeout int) {
  256. switch status {
  257. case StatusNoLogin:
  258. redisKey = IC.C.NewsCache.NoLogin.Key
  259. redisKey = fmt.Sprintf(redisKey, time.Now().Year(), time.Now().Month(), time.Now().Day())
  260. timeout = IC.C.NewsCache.NoLogin.Timeout
  261. case StatusLoginUser:
  262. redisKey = IC.C.NewsCache.LoginUser.Key // 登录用户使用的缓存key
  263. redisKey = fmt.Sprintf(redisKey, positionId, time.Now().Year(), time.Now().Month(), time.Now().Day())
  264. timeout = IC.C.NewsCache.LoginUser.Timeout
  265. case StatusLogin:
  266. redisKey = IC.C.NewsCache.Login.Key // 登录用户使用的最新标讯缓存key
  267. redisKey = fmt.Sprintf(redisKey, time.Now().Year(), time.Now().Month(), time.Now().Day())
  268. timeout = IC.C.NewsCache.Login.Timeout
  269. }
  270. return
  271. }
  272. // PutNewsCache 存缓存
  273. func PutNewsCache(redisKey string, redisTimeout int, list []*bxbase.NewestList) {
  274. b, err := json.Marshal(list)
  275. if err != nil {
  276. log.Printf("保存缓存 序列化异常,data:%s,err:%s\n", list, err.Error())
  277. return
  278. }
  279. if err = redis.PutBytes("new", redisKey, &b, redisTimeout); err != nil {
  280. log.Printf("保存缓存 redis 异常,key:%s,err:%s\n", redisKey, err.Error())
  281. }
  282. }
  283. // GetNewsCache 取缓存
  284. func GetNewsCache(redisKey string) (list []*bxbase.NewestList, err error) {
  285. redisByte, err := redis.GetBytes("new", redisKey)
  286. if err != nil || redisByte == nil || len(*redisByte) == 0 {
  287. return list, err
  288. }
  289. err = json.Unmarshal(*redisByte, &list)
  290. if err != nil {
  291. logx.Info(fmt.Sprintf("读取缓存 序列化异常,err:%s", err.Error()))
  292. return nil, err
  293. }
  294. return list, nil
  295. }