newestBidding.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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, err := redis.Exists("new", countKey); err == nil && b {
  85. return 1
  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. if c := n.MysqlDb.CountBySql(countSql); c > 0 {
  91. redis.Put("new", countKey, c, IC.C.NewsCache.Count.Timeout) //过期时间走配置,比最新标讯列表缓存时间 要短1/10 尽量不超过两分钟
  92. return c
  93. }
  94. return 0
  95. }
  96. func (n *NewestInfo) GetPushHistory() (res []*bxbase.NewestList) {
  97. 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 ?"
  98. findSQL = fmt.Sprintf(findSQL, n.TableName, n.NewUserId)
  99. logx.Info(n.TableName, "-------", n.NewUserId, ",findSQL:", findSQL)
  100. list := n.MysqlDb.SelectBySql(findSQL, n.NewsLimitNum)
  101. if len(*list) > 0 && list != nil {
  102. m := map[string]bool{}
  103. es_ids := []string{}
  104. infos := map[string]*bxbase.NewestList{}
  105. for _, v := range *list {
  106. infoId := MC.ObjToString(v["infoid"])
  107. if m[infoId] {
  108. continue
  109. }
  110. es_ids = append(es_ids, infoId)
  111. m[MC.ObjToString(v["infoid"])] = true
  112. //
  113. infos[infoId] = &bxbase.NewestList{
  114. Id: ME.EncodeArticleId2ByCheck(MC.ObjToString(v["infoid"])),
  115. Matchkeys: strings.Split(MC.ObjToString(v["matchkeys"]), " "),
  116. Budget: MC.Int64All(v["budget"]),
  117. Bidamount: MC.Int64All(v["bidamount"]),
  118. FileExists: MC.Int64All(v["attachment_count"]) > 0,
  119. }
  120. }
  121. if len(es_ids) > 0 {
  122. list := elastic.Get(search_index, search_type, fmt.Sprintf(query, strings.Join(es_ids, `","`), len(es_ids)))
  123. if list != nil {
  124. for _, v := range *list {
  125. _id := MC.ObjToString(v["_id"])
  126. bn := infos[_id]
  127. bn.Title = MC.ObjToString(v["title"])
  128. bn.PublishTime = MC.Int64All(v["publishtime"])
  129. bn.Subtype = MC.If(v["subtype"] != nil, MC.ObjToString(v["subtype"]), MC.ObjToString(v["toptype"])).(string)
  130. bn.Area = MC.If(MC.ObjToString(v["area"]) == "A", "全国", MC.ObjToString(v["area"])).(string)
  131. bn.Buyerclass = MC.ObjToString(v["buyerclass"])
  132. bn.City = MC.ObjToString(v["city"])
  133. bn.Industry = MC.If(MC.ObjToString(v["s_subscopeclass"]) != "", strings.Split(strings.Split(MC.ObjToString(v["s_subscopeclass"]), ",")[0], "_")[0], "").(string)
  134. bn.SpiderCode = MC.ObjToString(v["spidercode"])
  135. bn.Site = MC.ObjToString(v["site"])
  136. }
  137. }
  138. }
  139. //mongodb bidding
  140. mgo_ids := []primitive.ObjectID{}
  141. for _, v := range es_ids {
  142. if infos[v].Title == "" {
  143. mgo_ids = append(mgo_ids, mongodb.StringTOBsonId(v))
  144. }
  145. }
  146. if len(mgo_ids) > 0 {
  147. list, ok := IC.MgoBidding.Find("bidding", map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_ids}}, nil, mongodb_fields, false, -1, -1)
  148. if ok && *list != nil {
  149. for _, v := range *list {
  150. _id := mongodb.BsonIdToSId(v["_id"])
  151. bn := infos[_id]
  152. bn.Title = MC.ObjToString(v["title"])
  153. bn.PublishTime = MC.Int64All(v["publishtime"])
  154. bn.Subtype = MC.If(v["subtype"] != nil, MC.ObjToString(v["subtype"]), MC.ObjToString(v["toptype"])).(string)
  155. bn.Area = MC.If(MC.ObjToString(v["area"]) == "A", "全国", MC.ObjToString(v["area"])).(string)
  156. bn.Buyerclass = MC.ObjToString(v["buyerclass"])
  157. bn.City = MC.ObjToString(v["city"])
  158. bn.Industry = MC.If(MC.ObjToString(v["s_subscopeclass"]) != "", strings.Split(strings.Split(MC.ObjToString(v["s_subscopeclass"]), ",")[0], "_")[0], "").(string)
  159. bn.SpiderCode = MC.ObjToString(v["spidercode"])
  160. bn.Site = MC.ObjToString(v["site"])
  161. }
  162. }
  163. }
  164. //mongodb bidding_back
  165. mgo_back_ids := []primitive.ObjectID{}
  166. for _, v := range mgo_ids {
  167. if infos[mongodb.BsonIdToSId(v)].Title == "" {
  168. mgo_back_ids = append(mgo_back_ids, v)
  169. }
  170. }
  171. if len(mgo_back_ids) > 0 {
  172. list, ok := IC.MgoBidding.Find("bidding_back", map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_back_ids}}, nil, mongodb_fields, false, -1, -1)
  173. if ok && *list != nil {
  174. for _, v := range *list {
  175. _id := mongodb.BsonIdToSId(v["_id"])
  176. bn := infos[_id]
  177. bn.Title = MC.ObjToString(v["title"])
  178. bn.PublishTime = MC.Int64All(v["publishtime"])
  179. bn.Subtype = MC.If(v["subtype"] != nil, MC.ObjToString(v["subtype"]), MC.ObjToString(v["toptype"])).(string)
  180. bn.Area = MC.If(MC.ObjToString(v["area"]) == "A", "全国", MC.ObjToString(v["area"])).(string)
  181. bn.Buyerclass = MC.ObjToString(v["buyerclass"])
  182. bn.City = MC.ObjToString(v["city"])
  183. bn.Industry = MC.If(MC.ObjToString(v["s_subscopeclass"]) != "", strings.Split(strings.Split(MC.ObjToString(v["s_subscopeclass"]), ",")[0], "_")[0], "").(string)
  184. bn.SpiderCode = MC.ObjToString(v["spidercode"])
  185. bn.Site = MC.ObjToString(v["site"])
  186. }
  187. }
  188. }
  189. //
  190. for _, v := range infos {
  191. res = append(res, v)
  192. }
  193. }
  194. return
  195. }
  196. // 根据定位或者搜索历史 查es
  197. func NewestQuery(city, keys, subtype string) (str string) {
  198. var musts, bools []string
  199. if keys != "" {
  200. for _, v := range strings.Split(keys, ",") {
  201. keys := strings.Split(v, " ") //历史搜索 空格划分
  202. must_tmp := []string{}
  203. for _, key := range keys {
  204. must_tmp = append(must_tmp, fmt.Sprintf(multi_match, "\""+key+"\""))
  205. }
  206. bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(must_tmp, ","), ""))
  207. }
  208. }
  209. if city != "" {
  210. musts = append(musts, fmt.Sprintf(query_bool_must, "city", `"`+city+`"`))
  211. }
  212. //未登录首页推送数据限制
  213. if subtype != "" {
  214. musts = append(musts, fmt.Sprintf(query_bool_must, "subtype", subtype))
  215. }
  216. minimum_should_match := 0
  217. if len(bools) > 0 {
  218. minimum_should_match = 1
  219. }
  220. str = fmt.Sprintf(query_city_hkeys, strings.Join(musts, ","), strings.Join(bools, ","), minimum_should_match, IC.C.NewsLimitNum)
  221. logx.Info("str:", str)
  222. return
  223. }
  224. // es查询
  225. func NewestES(doSearchStr string) (res []*bxbase.NewestList) {
  226. list := elastic.Get(search_index, search_type, doSearchStr)
  227. if list != nil && len(*list) > 0 {
  228. for _, v := range *list {
  229. _id := mongodb.BsonIdToSId(v["_id"])
  230. isValidFile, _ := v["isValidFile"].(bool)
  231. res = append(res, &bxbase.NewestList{
  232. Id: ME.EncodeArticleId2ByCheck(_id),
  233. Title: MC.ObjToString(v["title"]),
  234. Subtype: MC.If(v["subtype"] != nil, MC.ObjToString(v["subtype"]), MC.ObjToString(v["toptype"])).(string),
  235. Area: MC.If(MC.ObjToString(v["area"]) == "A", "全国", MC.ObjToString(v["area"])).(string),
  236. Buyerclass: MC.ObjToString(v["buyerclass"]),
  237. City: MC.ObjToString(v["city"]),
  238. Industry: MC.If(MC.ObjToString(v["s_subscopeclass"]) != "", strings.Split(strings.Split(MC.ObjToString(v["s_subscopeclass"]), ",")[0], "_")[0], "").(string),
  239. Budget: MC.Int64All(v["budget"]),
  240. Bidamount: MC.Int64All(v["bidamount"]),
  241. FileExists: isValidFile, //附件
  242. PublishTime: MC.Int64All(v["publishtime"]),
  243. Site: MC.ObjToString(v["site"]),
  244. SpiderCode: MC.ObjToString(v["spidercode"]),
  245. })
  246. }
  247. }
  248. return
  249. }
  250. // GetRedisKeyTimeout 获取缓存的key 和超时时间
  251. func GetRedisKeyTimeout(status int, positionId int64) (redisKey string, timeout int) {
  252. switch status {
  253. case StatusNoLogin:
  254. redisKey = IC.C.NewsCache.NoLogin.Key
  255. redisKey = fmt.Sprintf(redisKey, time.Now().Year(), time.Now().Month(), time.Now().Day())
  256. timeout = IC.C.NewsCache.NoLogin.Timeout
  257. case StatusLoginUser:
  258. redisKey = IC.C.NewsCache.LoginUser.Key // 登录用户使用的缓存key
  259. redisKey = fmt.Sprintf(redisKey, positionId, time.Now().Year(), time.Now().Month(), time.Now().Day())
  260. timeout = IC.C.NewsCache.LoginUser.Timeout
  261. case StatusLogin:
  262. redisKey = IC.C.NewsCache.Login.Key // 登录用户使用的最新标讯缓存key
  263. redisKey = fmt.Sprintf(redisKey, time.Now().Year(), time.Now().Month(), time.Now().Day())
  264. timeout = IC.C.NewsCache.Login.Timeout
  265. }
  266. return
  267. }
  268. // PutNewsCache 存缓存
  269. func PutNewsCache(redisKey string, redisTimeout int, list []*bxbase.NewestList) {
  270. b, err := json.Marshal(list)
  271. if err != nil {
  272. log.Printf("保存缓存 序列化异常,data:%s,err:%s\n", list, err.Error())
  273. return
  274. }
  275. if err = redis.PutBytes("new", redisKey, &b, redisTimeout); err != nil {
  276. log.Printf("保存缓存 redis 异常,key:%s,err:%s\n", redisKey, err.Error())
  277. }
  278. }
  279. // GetNewsCache 取缓存
  280. func GetNewsCache(redisKey string) (list []*bxbase.NewestList, err error) {
  281. redisByte, err := redis.GetBytes("new", redisKey)
  282. if err != nil || redisByte == nil || len(*redisByte) == 0 {
  283. return list, err
  284. }
  285. err = json.Unmarshal(*redisByte, &list)
  286. if err != nil {
  287. logx.Info(fmt.Sprintf("读取缓存 序列化异常,err:%s", err.Error()))
  288. return nil, err
  289. }
  290. return list, nil
  291. }