push.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. package model
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. IC "jyBXSubscribe/rpc/init"
  7. ms "jyBXSubscribe/rpc/model/service"
  8. "jyBXSubscribe/rpc/type/bxsubscribe"
  9. "log"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "app.yhyue.com/moapp/jybase/common"
  14. "app.yhyue.com/moapp/jybase/date"
  15. "app.yhyue.com/moapp/jybase/encrypt"
  16. "app.yhyue.com/moapp/jybase/esv1"
  17. "app.yhyue.com/moapp/jybase/mongodb"
  18. "app.yhyue.com/moapp/jybase/mysql"
  19. "app.yhyue.com/moapp/jybase/redis"
  20. "bp.jydev.jianyu360.cn/BaseService/jyCodeService/rpc/codeservice/codeservice"
  21. "github.com/zeromicro/go-zero/core/logx"
  22. "go.mongodb.org/mongo-driver/bson/primitive"
  23. )
  24. const (
  25. pageSize = 100
  26. AllSubPushCacheSize = 250
  27. query = `{"query":{"terms":{"_id":["%s"]}},"_source":["_id","area", "publishtime", "s_subscopeclass", "subtype", "title", "toptype", "type", "buyerclass","bidamount","budget","projectname","buyer","bidopentime","s_winner","filetext"],"from":0,"size":%d}`
  28. 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}`
  29. SubFreeFlag = "fType"
  30. SubVipFlag = "vType"
  31. MemberFlag = "mType"
  32. EntnicheFlag = "eType"
  33. oneDay = 24 * 60 * 60
  34. Baseinfo = "global_common_data.dws_f_bid_baseinfo"
  35. BidTags = "global_common_data.dws_f_bid_tags"
  36. )
  37. var (
  38. ennicheInsertCollKey = []string{"entid", "deptid", "userid", "infoid", "matchkeys", "date"}
  39. subscribeInsertCollKey = []string{"userid", "infoid", "matchkeys", "date", "isvip"}
  40. memberInsertCollKey = []string{"userid", "infoid", "matchkeys", "date"}
  41. )
  42. var aboutDbMsg map[string]*AboutDbMsg = map[string]*AboutDbMsg{
  43. SubFreeFlag: &AboutDbMsg{"pushsubscribe", "subpush"},
  44. SubVipFlag: &AboutDbMsg{"pushsubscribe", "subpush"},
  45. MemberFlag: &AboutDbMsg{"pushmember", "memberpush"},
  46. EntnicheFlag: &AboutDbMsg{"pushentniche", "entnichepush"},
  47. }
  48. type AboutDbMsg struct {
  49. MysqlTable string
  50. RedisKeyFlag string
  51. }
  52. type SubPush struct {
  53. Date string
  54. Datas []*bxsubscribe.SubscribeInfo
  55. Count int64
  56. }
  57. type PushCa struct {
  58. Date int64
  59. InfoId string
  60. Visit int
  61. Index int64
  62. Keys []string
  63. Type int
  64. Isvip int
  65. FileExists bool
  66. }
  67. // 查询参数
  68. type SubPushQueryParam struct {
  69. Mgo_bidding mongodb.MongodbSim //
  70. Bidding string //
  71. Bidding_back string //
  72. UserId string //用户id
  73. PageNum int //页面
  74. PageSize int //每页数量
  75. SelectTime string //时间
  76. Area string //区域
  77. City string //城市
  78. Buyerclass string //采购单位行业
  79. Subtype string //信息类型 二级分类
  80. Subscopeclass string //信息行业
  81. Key string //订阅词
  82. Export bool //导出
  83. EntId string //企业id
  84. Price string //价格
  85. FileExists string //是否有附件;默认全部;1:有附件;-1:无附件
  86. EntUserId string //商机管理用户id
  87. DeptId string //商机管理用户部门id
  88. BaseServiceMysql *mysql.Mysql
  89. NewUserId int64
  90. IsEnt bool
  91. SelectInfoIds []string
  92. }
  93. func (spqp *SubPushQueryParam) IsEmpty() bool {
  94. return (spqp.SelectTime == "" || spqp.SelectTime == "all") && spqp.Area == "" && spqp.City == "" && spqp.Buyerclass == "" && spqp.Subscopeclass == "" && spqp.Subtype == "" && spqp.Key == "" && spqp.Price == "" && spqp.FileExists == ""
  95. }
  96. type subscribePush struct {
  97. ModuleFlag string
  98. }
  99. func NewSubscribePush(module ...string) *subscribePush {
  100. m := ""
  101. if len(module) > 0 {
  102. m = module[0]
  103. }
  104. return &subscribePush{m}
  105. }
  106. // 从pushcache_2_a中取
  107. func (s *subscribePush) GetTodayCache(userId string) (*SubPush, error) {
  108. pc_a, err := redis.GetNewBytes("pushcache_2_b", s.todayKey(userId))
  109. if err != nil {
  110. return nil, err
  111. }
  112. if pc_a == nil {
  113. return nil, nil
  114. }
  115. var p *SubPush
  116. if err := json.Unmarshal(*pc_a, &p); err != nil {
  117. return nil, err
  118. }
  119. return p, nil
  120. }
  121. // 往pushcache_2_a中放
  122. func (s *subscribePush) PutTodayCache(userId string, pc_a *SubPush) {
  123. redis.Put("pushcache_2_b", s.todayKey(userId), pc_a, oneDay)
  124. }
  125. // 获取redis key
  126. func (s *subscribePush) todayKey(userId string) string {
  127. return fmt.Sprintf("%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, userId)
  128. }
  129. func (s *subscribePush) allKey(userId string) string {
  130. return fmt.Sprintf("all_%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, userId)
  131. }
  132. // 历史推送记录中单条信息格式化
  133. func (s *subscribePush) InfoFormat(p *PushCa, info *map[string]interface{}) *bxsubscribe.SubscribeInfo {
  134. area := common.ObjToString((*info)["area"])
  135. if area == "A" {
  136. area = "全国"
  137. }
  138. industry := common.ObjToString((*info)["s_subscopeclass"])
  139. scs := strings.Split(industry, ",")
  140. if len(scs) > 0 {
  141. industry = scs[0]
  142. if industry != "" {
  143. iss := strings.Split(industry, "_")
  144. if len(iss) > 0 {
  145. industry = iss[0]
  146. }
  147. }
  148. }
  149. infotype := common.ObjToString((*info)["subtype"])
  150. if infotype == "" {
  151. infotype = common.ObjToString((*info)["toptype"])
  152. }
  153. _id := p.InfoId
  154. if _id == "" {
  155. _id = common.ObjToString((*info)["_id"])
  156. }
  157. return &bxsubscribe.SubscribeInfo{
  158. XId: encrypt.EncodeArticleId2ByCheck(_id),
  159. Title: common.InterfaceToStr((*info)["title"]),
  160. Area: area,
  161. BuyerClass: common.InterfaceToStr((*info)["buyerclass"]),
  162. Subtype: infotype,
  163. Industry: industry,
  164. PublishTime: common.Int64All((*info)["publishtime"]),
  165. CaIndex: p.Index,
  166. CaDate: p.Date,
  167. CaIsvisit: int64(p.Visit),
  168. CaIsvip: int64(p.Isvip),
  169. CaType: int64(p.Type),
  170. MatchKeys: p.Keys,
  171. Budget: common.InterfaceToStr((*info)["budget"]),
  172. BidAmount: common.InterfaceToStr((*info)["bidamount"]),
  173. Buyer: common.InterfaceToStr((*info)["buyer"]),
  174. ProjectName: common.InterfaceToStr((*info)["projectname"]),
  175. Winner: common.InterfaceToStr((*info)["s_winner"]),
  176. BidOpenTime: common.Int64All((*info)["bidopentime"]),
  177. CaFileExists: p.FileExists,
  178. }
  179. }
  180. func (s *subscribePush) Datas(spqp *SubPushQueryParam) (hasNextPage bool, total int64, result []*bxsubscribe.SubscribeInfo) {
  181. logx.Info(spqp.UserId, spqp.NewUserId, s.ModuleFlag, "subscribePush query param:", "SelectTime:", spqp.SelectTime, "Area:", spqp.Area, "City:", spqp.City, "Subtype:", spqp.Subtype, "Subscopeclass:", spqp.Subscopeclass, "Buyerclass:", spqp.Buyerclass, "Key:", spqp.Key, "PageNum:", spqp.PageNum, "Price:", spqp.Price, "FileExists:", spqp.FileExists)
  182. if spqp.UserId == "" {
  183. return
  184. }
  185. if spqp.PageNum < 1 {
  186. spqp.PageNum = 1
  187. }
  188. if spqp.PageSize < 1 || spqp.PageSize > pageSize {
  189. if !spqp.Export {
  190. spqp.PageSize = pageSize
  191. } else { //数据导出查询20000条限制
  192. if spqp.PageSize < 1 || spqp.PageSize > 20000 {
  193. spqp.PageSize = 20000
  194. }
  195. }
  196. }
  197. starttime, endtime := int64(0), int64(0)
  198. if len(strings.Split(spqp.SelectTime, "_")) == 2 {
  199. st := strings.Split(spqp.SelectTime, "_")[0]
  200. et := strings.Split(spqp.SelectTime, "_")[1]
  201. if st != "" && et != "" {
  202. starttime, _ = strconv.ParseInt(st, 0, 64)
  203. endtime, _ = strconv.ParseInt(et, 0, 64)
  204. if endtime > 0 {
  205. etTime := time.Unix(endtime, 0)
  206. endtime = time.Date(etTime.Year(), etTime.Month(), etTime.Day(), 23, 59, 59, 0, time.Local).Unix()
  207. }
  208. }
  209. }
  210. nowFormat := date.NowFormat(date.Date_Short_Layout)
  211. start := (spqp.PageNum - 1) * spqp.PageSize
  212. end := start + spqp.PageSize
  213. //时间是今天,没有别的过滤条件--首先读取当前推送缓存数据 其次查询数据库
  214. if nowFormat == date.FormatDateByInt64(&starttime, date.Date_Short_Layout) && spqp.Area == "" && spqp.City == "" && spqp.Buyerclass == "" && spqp.Subscopeclass == "" && spqp.Subtype == "" && spqp.Key == "" && spqp.Price == "" && spqp.FileExists == "" {
  215. logx.Info("a1:", s.todayKey(spqp.UserId))
  216. subPush := &SubPush{}
  217. var err error
  218. if spqp.IsEnt == false {
  219. subPush, err = s.GetTodayCache(spqp.UserId)
  220. }
  221. if err != nil {
  222. logx.Info(spqp.UserId, "GetTodayCache Error", err)
  223. }
  224. if err != nil || subPush == nil || subPush.Date != nowFormat || len(subPush.Datas) == 0 {
  225. list, countSearch := s.getDatasFromMysql(spqp, starttime, endtime, spqp.PageSize, false)
  226. subPush = &SubPush{
  227. Date: nowFormat,
  228. Datas: list,
  229. Count: countSearch,
  230. }
  231. if spqp.IsEnt == false {
  232. s.PutTodayCache(spqp.UserId, subPush)
  233. }
  234. }
  235. length := len(subPush.Datas)
  236. if end > length {
  237. end = length
  238. }
  239. if start < length {
  240. result = subPush.Datas[start:end]
  241. }
  242. total = int64(length)
  243. } else if spqp.IsEmpty() && (spqp.PageNum-1)*spqp.PageSize < 250 && len(spqp.SelectInfoIds) == 0 && !spqp.Export { //全部,没有过滤条件 之前缓存5页*50条=250 非数据导出
  244. logx.Info("a2:", s.allKey(spqp.UserId))
  245. allCache := &SubPush{}
  246. var err error
  247. if spqp.IsEnt == false {
  248. allCache, err = s.GetAllCache(spqp.UserId)
  249. }
  250. if err != nil {
  251. logx.Info(spqp.UserId, "GetAllCache Error", err)
  252. }
  253. if err != nil || allCache == nil || allCache.Date != nowFormat || len(allCache.Datas) == 0 {
  254. spqp.PageNum = 1
  255. logx.Info(1111)
  256. list, countSearch := s.getDatasFromMysql(spqp, starttime, endtime, AllSubPushCacheSize, true)
  257. allCache = &SubPush{
  258. Date: nowFormat,
  259. Datas: list,
  260. Count: countSearch,
  261. }
  262. if spqp.IsEnt == false {
  263. s.PutAllCache(spqp.UserId, allCache)
  264. }
  265. }
  266. length := len(allCache.Datas)
  267. if end > length {
  268. end = length
  269. }
  270. if start < length {
  271. result = allCache.Datas[start:end]
  272. }
  273. total = allCache.Count
  274. } else {
  275. logx.Info("a4")
  276. result, total = s.getDatasFromMysql(spqp, starttime, endtime, spqp.PageSize, true)
  277. }
  278. logx.Info("-------------------------------------------------", len(result))
  279. log.Println(spqp.IsEmpty() && (spqp.PageNum-1)*spqp.PageSize <= 250)
  280. if result == nil {
  281. result = []*bxsubscribe.SubscribeInfo{}
  282. }
  283. hasNextPage = len(result) >= spqp.PageSize
  284. return
  285. }
  286. func (s *subscribePush) getDatasFromMysql(spqp *SubPushQueryParam, starttime, endtime int64, size int, isLimit bool) (result []*bxsubscribe.SubscribeInfo, count int64) {
  287. querys := []string{}
  288. userStr := " "
  289. leftJoinStr := " "
  290. var (
  291. searchSql, findSql string
  292. )
  293. querys = append(querys, " 1=1 ")
  294. if spqp.SelectInfoIds != nil && len(spqp.SelectInfoIds) > 0 {
  295. searchSql = fmt.Sprintf(" from %s a LEFT JOIN %s b ON a.infoid = b.infoid where %s order by a.id desc", aboutDbMsg[s.ModuleFlag].MysqlTable, Baseinfo, fmt.Sprintf("a.id in ('%s')", strings.Join(spqp.SelectInfoIds, "','")))
  296. fmt.Println("searchSql", searchSql)
  297. //查询总数
  298. count = spqp.BaseServiceMysql.CountBySql(fmt.Sprintf("select count(a.id)" + searchSql))
  299. findSql = "select a.id,a.date,a.infoid,a.isvisit,a.matchkeys,a.type,b.isvalidfile as attachment_count"
  300. } else {
  301. if spqp.IsEnt {
  302. userStr = fmt.Sprintf(" a.entid='%s'", spqp.EntId)
  303. } else {
  304. userStr = fmt.Sprintf(" a.userid='%s'", common.If(s.ModuleFlag == "eType", spqp.EntUserId, common.InterfaceToStr(spqp.NewUserId)))
  305. }
  306. codeMap, err := IC.CodeLib.CodeTransformation(context.Background(), &codeservice.Request{})
  307. if codeMap.Data == nil || err != nil {
  308. logx.Error("代码表获取失败")
  309. return result, count
  310. }
  311. //时间
  312. logx.Info("starttime,endtime", starttime, endtime)
  313. if starttime > 0 && endtime > 0 {
  314. querys = append(querys, fmt.Sprintf("a.date>=%d and date<=%d", starttime, endtime))
  315. } else if starttime > 0 && endtime == 0 {
  316. querys = append(querys, fmt.Sprintf("a.date>=%d", starttime))
  317. } else if starttime == 0 && endtime > 0 {
  318. querys = append(querys, fmt.Sprintf("a.date<=%d", endtime))
  319. }
  320. if spqp.Area != "" || spqp.City != "" {
  321. var sqlAreaCity = ""
  322. //城市
  323. city := []string{}
  324. for _, v := range strings.Split(spqp.City, ",") {
  325. if codeMap.Data.City[v] != "" {
  326. city = append(city, fmt.Sprint(codeMap.Data.City[v]))
  327. } else {
  328. city = append(city, "-1")
  329. }
  330. }
  331. if len(city) == 1 {
  332. city = append(city, "9999")
  333. }
  334. if len(city) > 0 {
  335. sqlAreaCity = fmt.Sprintf("b.city_code in (%s)", strings.Join(city, ","))
  336. }
  337. //区域
  338. var sqlArea = ""
  339. area := []string{}
  340. for _, v := range strings.Split(spqp.Area, ",") {
  341. if codeMap.Data.Area[v] != "" {
  342. area = append(area, fmt.Sprint(codeMap.Data.Area[v]))
  343. } else {
  344. area = append(area, "-1")
  345. }
  346. }
  347. if len(area) == 1 {
  348. area = append(area, "9999")
  349. }
  350. if len(area) > 0 {
  351. sqlArea = fmt.Sprintf("b.area_code in (%s)", strings.Join(area, ","))
  352. }
  353. if sqlAreaCity != "" && sqlArea != "" {
  354. sqlAreaCity = "( " + sqlAreaCity + " or " + sqlArea + " )"
  355. } else if sqlAreaCity == "" && sqlArea != "" {
  356. sqlAreaCity = sqlArea
  357. }
  358. if sqlAreaCity != "" {
  359. querys = append(querys, sqlAreaCity)
  360. }
  361. }
  362. //采购单位行业
  363. if spqp.Buyerclass != "" {
  364. buyerclass := []string{}
  365. for _, v := range strings.Split(spqp.Buyerclass, ",") {
  366. if codeMap.Data.Buyerclass[v] != "" {
  367. buyerclass = append(buyerclass, fmt.Sprint(codeMap.Data.Buyerclass[v]))
  368. }
  369. }
  370. if len(buyerclass) == 1 {
  371. buyerclass = append(buyerclass, "9999")
  372. }
  373. if len(buyerclass) > 0 {
  374. querys = append(querys, fmt.Sprintf("b.buyerclass_code in (%s)", strings.Join(buyerclass, ",")))
  375. }
  376. }
  377. //信息类型
  378. if spqp.Subtype != "" {
  379. subtype := []string{}
  380. for _, v := range strings.Split(spqp.Subtype, ",") {
  381. if codeMap.Data.Subtype[v] != "" {
  382. subtype = append(subtype, fmt.Sprint(codeMap.Data.Subtype[v]))
  383. }
  384. }
  385. if len(subtype) == 1 {
  386. subtype = append(subtype, "9999")
  387. }
  388. if len(subtype) > 0 {
  389. querys = append(querys, fmt.Sprintf("b.subtype_code in (%s)", strings.Join(subtype, ",")))
  390. }
  391. }
  392. //信息行业
  393. if spqp.Subscopeclass != "" {
  394. find_in_set := []string{}
  395. for _, v := range strings.Split(spqp.Subscopeclass, ",") {
  396. if codeMap.Data.Subscopeclass[v] != "" {
  397. find_in_set = append(find_in_set, codeMap.Data.Subscopeclass[v])
  398. }
  399. }
  400. if len(find_in_set) > 0 {
  401. leftJoinStr = fmt.Sprintf(" INNER JOIN %s t on t.infoid = b.infoid and t.labelcode=2 ", BidTags)
  402. querys = append(querys, fmt.Sprintf(" t.labelvalues in (%s)", strings.Join(find_in_set, ",")))
  403. }
  404. }
  405. //关键词
  406. if spqp.Key != "" {
  407. find_in_set := []string{}
  408. for _, v := range strings.Split(spqp.Key, ",") {
  409. find_in_set = append(find_in_set, fmt.Sprintf("find_in_set('%s',replace(replace(a.matchkeys,'+',','),' ',','))", v))
  410. }
  411. if len(find_in_set) == 1 {
  412. querys = append(querys, find_in_set[0])
  413. } else if len(find_in_set) > 1 {
  414. querys = append(querys, fmt.Sprintf("(%s)", strings.Join(find_in_set, " or ")))
  415. }
  416. }
  417. //价格- 预算和中标金额
  418. if spqp.Price != "" && strings.Contains(spqp.Price, "-") {
  419. minPriceStr, maxPriceStr := strings.Split(spqp.Price, "-")[0], strings.Split(spqp.Price, "-")[1]
  420. minPrice := common.Int64All(common.Float64All(minPriceStr) * 10000) //换成元
  421. maxPrice := common.Int64All(common.Float64All(maxPriceStr) * 10000) //换成元
  422. if minPriceStr != "" && maxPriceStr != "" {
  423. querys = append(querys, fmt.Sprintf("((b.bidamount>=%d and b.bidamount<=%d) or (b.budget>=%d and b.budget<=%d and b.bidamount is null))", minPrice, maxPrice, minPrice, maxPrice))
  424. } else if minPriceStr != "" {
  425. querys = append(querys, fmt.Sprintf("(b.bidamount>=%d or (b.budget>=%d and b.bidamount is null))", minPrice, minPrice))
  426. } else if maxPriceStr != "" {
  427. querys = append(querys, fmt.Sprintf("(b.bidamount<=%d or (b.budget<=%d and b.bidamount is null))", maxPrice, maxPrice))
  428. }
  429. }
  430. //附件
  431. if spqp.FileExists != "" {
  432. if spqp.FileExists == "1" {
  433. querys = append(querys, fmt.Sprintf("b.isvalidfile =1 "))
  434. } else if spqp.FileExists == "-1" {
  435. querys = append(querys, fmt.Sprintf("b.isvalidfile =0 "))
  436. }
  437. }
  438. searchSql = fmt.Sprintf(" from %s a INNER JOIN %s b ON %s and a.infoid = b.infoid %s where %s"+
  439. " order by a.id desc", aboutDbMsg[s.ModuleFlag].MysqlTable, Baseinfo, userStr, leftJoinStr, strings.Join(querys, " and "))
  440. logx.Info("searchSql", searchSql)
  441. //查询总数
  442. logx.Info(fmt.Sprintf("select count(a.id) " + searchSql))
  443. count = spqp.BaseServiceMysql.CountBySql(fmt.Sprintf("select count(a.id) " + searchSql))
  444. logx.Info("count:", count, "---", s.ModuleFlag)
  445. findSql = "select a.id,a.date,a.infoid,a.isvisit,a.matchkeys,a.type,b.isvalidfile as attachment_count"
  446. }
  447. if s.ModuleFlag != MemberFlag && s.ModuleFlag != EntnicheFlag {
  448. findSql += ",a.isvip"
  449. }
  450. findSql += searchSql
  451. if isLimit {
  452. findSql += fmt.Sprintf(" limit %d,%d", (spqp.PageNum-1)*size, size)
  453. }
  454. logx.Info("findSql", findSql)
  455. logx.Info(spqp.NewUserId, "subscribePush query sql:", findSql)
  456. list := spqp.BaseServiceMysql.SelectBySql(findSql)
  457. if list != nil && len(*list) > 0 {
  458. pushCas := s.GetJyPushs(*list)
  459. if !spqp.Export {
  460. result = s.GetInfoByIds(spqp.Mgo_bidding, spqp.Bidding, spqp.Bidding_back, pushCas)
  461. } else {
  462. result = s.GetOnlyExportInfo(pushCas)
  463. }
  464. } else {
  465. result = []*bxsubscribe.SubscribeInfo{}
  466. }
  467. logx.Info("result", result)
  468. return
  469. }
  470. // GetOnlyInfoId 获取信息id
  471. func (s *subscribePush) GetOnlyExportInfo(pushCas []*PushCa) []*bxsubscribe.SubscribeInfo {
  472. array := make([]*bxsubscribe.SubscribeInfo, len(pushCas))
  473. for k, v := range pushCas {
  474. array[k] = &bxsubscribe.SubscribeInfo{XId: encrypt.EncodeArticleId2ByCheck(v.InfoId), MatchKeys: v.Keys}
  475. }
  476. return array
  477. }
  478. // 根据id取内容
  479. func (s *subscribePush) GetInfoByIds(Mgo_bidding mongodb.MongodbSim, bidding, bidding_back string, pushCas []*PushCa) []*bxsubscribe.SubscribeInfo {
  480. array := make([]*bxsubscribe.SubscribeInfo, len(pushCas))
  481. if len(pushCas) == 0 {
  482. return array
  483. }
  484. m := map[string]bool{}
  485. ids := []string{}
  486. for _, v := range pushCas {
  487. if m[v.InfoId] {
  488. continue
  489. }
  490. m[v.InfoId] = true
  491. ids = append(ids, v.InfoId)
  492. }
  493. infos := map[string]map[string]interface{}{}
  494. //redis
  495. es_ids := []string{}
  496. for _, v := range ids {
  497. //剑鱼程序未找到赋值 位置;猜测在推送程序中
  498. info_i := redis.Get("pushcache_1", fmt.Sprintf("info_%s", v))
  499. if info_i != nil {
  500. info_m, _ := info_i.(map[string]interface{})
  501. info_m["_id"] = v
  502. infos[v] = info_m
  503. } else {
  504. es_ids = append(es_ids, v)
  505. }
  506. }
  507. //elasticsearch
  508. if len(es_ids) > 0 {
  509. list := elastic.Get("bidding", "bidding", fmt.Sprintf(query, strings.Join(es_ids, `","`), len(es_ids)))
  510. if list != nil {
  511. for _, v := range *list {
  512. _id := common.ObjToString(v["_id"])
  513. infos[_id] = v
  514. }
  515. }
  516. }
  517. //mongodb bidding
  518. mgo_ids := []primitive.ObjectID{}
  519. for _, v := range es_ids {
  520. if infos[v] == nil {
  521. _id, _ := primitive.ObjectIDFromHex(v)
  522. mgo_ids = append(mgo_ids, _id)
  523. }
  524. }
  525. if len(mgo_ids) > 0 {
  526. list, ok := Mgo_bidding.Find(bidding, map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_ids}}, nil, mongodb_fields, false, -1, -1)
  527. if ok && *list != nil {
  528. for _, v := range *list {
  529. _id := mongodb.BsonIdToSId(v["_id"])
  530. v["_id"] = _id
  531. infos[_id] = v
  532. }
  533. }
  534. }
  535. //mongodb bidding_back
  536. mgo_back_ids := []primitive.ObjectID{}
  537. for _, v := range mgo_ids {
  538. if infos[mongodb.BsonIdToSId(v)] == nil {
  539. mgo_back_ids = append(mgo_back_ids, v)
  540. }
  541. }
  542. if len(mgo_back_ids) > 0 {
  543. list, ok := Mgo_bidding.Find(bidding_back, map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_back_ids}}, nil, mongodb_fields, false, -1, -1)
  544. if ok && *list != nil {
  545. for _, v := range *list {
  546. _id := mongodb.BsonIdToSId(v["_id"])
  547. v["_id"] = _id
  548. infos[_id] = v
  549. }
  550. }
  551. }
  552. //
  553. for k, v := range pushCas {
  554. info := infos[v.InfoId]
  555. if info == nil {
  556. info = map[string]interface{}{}
  557. }
  558. array[k] = s.InfoFormat(v, &info)
  559. }
  560. return array
  561. }
  562. // 获取历史推送
  563. func (s *subscribePush) GetJyPushs(datas []map[string]interface{}) (pushCas []*PushCa) {
  564. pushCas = []*PushCa{}
  565. for _, v := range datas {
  566. keys := []string{}
  567. if matchkeys := common.ObjToString(v["matchkeys"]); matchkeys != "" {
  568. keys = strings.Split(matchkeys, " ")
  569. }
  570. pushCas = append(pushCas, &PushCa{
  571. Date: common.Int64All(v["date"]),
  572. InfoId: common.ObjToString(v["infoid"]),
  573. Visit: common.IntAll(v["isvisit"]),
  574. Index: common.Int64All(v["id"]),
  575. Keys: keys,
  576. Type: common.IntAll(v["type"]),
  577. Isvip: common.IntAll(v["isvip"]),
  578. FileExists: common.IntAll(v["attachment_count"]) > 0,
  579. })
  580. }
  581. return
  582. }
  583. // 查看全部列表缓存
  584. func (s *subscribePush) PutAllCache(userId string, datas *SubPush) {
  585. log.Println(s.allKey(userId), datas, oneDay)
  586. redis.Put("pushcache_2_a", s.allKey(userId), datas, oneDay)
  587. }
  588. func (s *subscribePush) GetAllCache(userId string) (*SubPush, error) {
  589. return s.GetCache("pushcache_2_a", s.allKey(userId))
  590. }
  591. func (s *subscribePush) GetCache(code, key string) (*SubPush, error) {
  592. pc_a, err := redis.GetNewBytes(code, key)
  593. if err != nil {
  594. return nil, err
  595. }
  596. if pc_a == nil {
  597. return nil, nil
  598. }
  599. var p *SubPush
  600. if err := json.Unmarshal(*pc_a, &p); err != nil {
  601. return nil, err
  602. }
  603. return p, nil
  604. }
  605. // 是否收藏
  606. func (s *subscribePush) MakeCollection(userId string, list []*bxsubscribe.SubscribeInfo) {
  607. if list == nil || len(list) == 0 {
  608. return
  609. }
  610. param := []interface{}{userId}
  611. wh := []string{}
  612. for _, v := range list {
  613. array := encrypt.DecodeArticleId2ByCheck(v.XId)
  614. if len(array) == 1 && array[0] != "" {
  615. param = append(param, array[0])
  616. wh = append(wh, "?")
  617. }
  618. }
  619. if len(wh) > 0 {
  620. result := IC.MainMysql.SelectBySql(`select bid from bdcollection where userid=? and bid in (`+strings.Join(wh, ",")+`)`, param...)
  621. bid_map := map[string]bool{}
  622. if result != nil {
  623. for _, v := range *result {
  624. bid_map[encrypt.EncodeArticleId2ByCheck(common.ObjToString(v["bid"]))] = true
  625. }
  626. }
  627. for _, v := range list {
  628. if bid_map[v.XId] {
  629. v.Collection = 1
  630. }
  631. }
  632. }
  633. }
  634. // 仅移动端首页使用,历史推送7天信息
  635. func (s *subscribePush) sevenDayKey(userId string) string {
  636. return fmt.Sprintf("7day_subpush_%s", userId)
  637. }
  638. func (s *subscribePush) PutSevenDayCache(userId string, datas []*bxsubscribe.SubscribeInfo) {
  639. redis.Put("pushcache_2_a", s.sevenDayKey(userId), SubPush{Datas: datas}, 7*24*60*60)
  640. }
  641. // 从pushcache_2_a中取
  642. func (s *subscribePush) GetSevenDayCache(userId string) ([]*bxsubscribe.SubscribeInfo, error) {
  643. allPush, _ := s.GetCache("pushcache_2_a", s.sevenDayKey(userId))
  644. if allPush != nil && allPush.Datas != nil && len(allPush.Datas) > 0 {
  645. return allPush.Datas, nil
  646. }
  647. return nil, nil
  648. }
  649. // 历史推送记录中单条信息格式化
  650. func InfoFormats(info map[string]interface{}, tmp map[string]interface{}) map[string]interface{} {
  651. area := common.ObjToString(info["area"])
  652. if area == "A" {
  653. area = "全国"
  654. }
  655. industry := common.ObjToString(info["s_subscopeclass"])
  656. scs := strings.Split(industry, ",")
  657. if len(scs) > 0 {
  658. industry = scs[0]
  659. if industry != "" {
  660. iss := strings.Split(industry, "_")
  661. if len(iss) > 0 {
  662. industry = iss[0]
  663. }
  664. }
  665. }
  666. infotype := common.ObjToString(info["subtype"])
  667. if infotype == "" {
  668. infotype = common.ObjToString(info["toptype"])
  669. }
  670. if infotype == "" {
  671. infotype = common.ObjToString(info["type"])
  672. if infotype == "tender" {
  673. infotype = "招标"
  674. } else if infotype == "bid" {
  675. infotype = "中标"
  676. }
  677. }
  678. info["type"] = infotype
  679. return info
  680. }
  681. // UpdateUserPushUnread 更新app未读标识为已读
  682. func UpdateUserPushUnread(userid string, vt string) {
  683. if vt == MemberFlag {
  684. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_member_apppushunread": 0}})
  685. } else if vt == EntnicheFlag {
  686. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_entniche_apppushunread": 0}})
  687. } else {
  688. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_apppushunread": 0}})
  689. }
  690. }
  691. //
  692. // 获取用户信息
  693. func (s *subscribePush) UserInfo(userId string) (*map[string]interface{}, int64) {
  694. user, ok := IC.Mgo.FindById("user", userId, `{"s_m_openid":1,"a_m_openid":1,"s_phone":1,"a_mergeorder":1,"o_jy":1,"l_firstpushtime":1,"i_vip_status":1,"l_vip_endtime":1,"o_vipjy":1,"i_member_status":1,"o_member_jy":1}`)
  695. if !ok || user == nil {
  696. return nil, 0
  697. }
  698. return user, common.Int64All((*user)["l_firstpushtime"])
  699. }
  700. // 是否有订阅词
  701. func GetKeySet(t string, u *map[string]interface{}, data []string) (bool, []string) {
  702. var industry_ = []string{}
  703. if u != nil {
  704. if t == SubFreeFlag {
  705. o_jy, _ := (*u)["o_jy"].(map[string]interface{})
  706. a_key, _ := o_jy["a_key"].([]interface{})
  707. return len(a_key) > 0, industry_
  708. } else {
  709. var obj map[string]interface{}
  710. if t == SubVipFlag {
  711. obj, _ = (*u)["o_vipjy"].(map[string]interface{})
  712. } else if t == MemberFlag {
  713. obj, _ = (*u)["o_member_jy"].(map[string]interface{})
  714. } else if t == EntnicheFlag {
  715. if len(data) > 0 {
  716. return true, data
  717. } else {
  718. return false, data
  719. }
  720. }
  721. if obj != nil {
  722. if buyerclassObj, ok := obj["a_buyerclass"].([]interface{}); ok {
  723. industry_ = common.ObjArrToStringArr(buyerclassObj)
  724. }
  725. itmes, _ := obj["a_items"].([]interface{})
  726. for _, v := range itmes {
  727. item, _ := v.(map[string]interface{})
  728. keys, _ := item["a_key"].([]interface{})
  729. if len(keys) > 0 {
  730. return true, industry_
  731. }
  732. }
  733. }
  734. }
  735. }
  736. return false, industry_
  737. }
  738. const (
  739. INDEX = "bidding"
  740. TYPE = "bidding"
  741. bidField = `"_id","title","publishtime","toptype","subtype","type","area","city","s_subscopeclass","buyerclass","budget","bidamount","filetext","spidercode","site"`
  742. bidTime = `{"range":{"publishtime":{"gt":%d}}}`
  743. bidSort = `{"publishtime":"desc"}`
  744. findfields = `"title"`
  745. )
  746. // 首次访问推送页面 默认生成推送数据
  747. // 默认匹配es 7天内数据
  748. func (s *subscribePush) DefaultDatas(spqp *SubPushQueryParam) (hasNextPage bool, total int64, result []*bxsubscribe.SubscribeInfo) {
  749. if spqp.UserId == "" {
  750. return false, 0, nil
  751. }
  752. t1 := time.Now()
  753. log.Println("userId:", spqp.UserId)
  754. log.Println("newUserId:", spqp.NewUserId)
  755. //用户信息
  756. bsp := s.getUserInfo(spqp)
  757. logx.Info("获取用户信息耗时:", time.Since(t1))
  758. t2 := time.Now()
  759. if len(bsp.Keyword) > 0 {
  760. logx.Info(time.Since(t1), "--bsp:", bsp)
  761. //获取查询语句
  762. qstr := s.getDefaultDatasSQL(bsp)
  763. list := elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSort, bidField, 0, bsp.Size, 0, false)
  764. //logx.Info(time.Since(t1), "count:", len(*list))
  765. if list != nil && len(*list) > 0 {
  766. total = int64(len(*list))
  767. result = s.listManager(spqp, *list, bsp.Keyword)
  768. if len(result) > pageSize {
  769. result = result[:pageSize]
  770. hasNextPage = true
  771. }
  772. }
  773. }
  774. logx.Info("请求耗时:", time.Since(t2))
  775. return
  776. }
  777. // 保存推送表
  778. func (s *subscribePush) listManager(spqp *SubPushQueryParam, list []map[string]interface{}, keyword []ViewKeyWord) (resultList []*bxsubscribe.SubscribeInfo) {
  779. t2 := time.Now()
  780. now := time.Now().Unix()
  781. length := len(list)
  782. resultList = make([]*bxsubscribe.SubscribeInfo, length)
  783. pushInsert := []interface{}{}
  784. for i := length - 1; i >= 0; i-- {
  785. v := list[i]
  786. title := strings.Replace(common.ObjToString(v["title"]), "\n", "", -1)
  787. infoid := common.InterfaceToStr(v["_id"])
  788. matchkeys := getKeys(title, keyword)
  789. matchkey := strings.Join(matchkeys, " ")
  790. redisKey := fmt.Sprintf("pushinfo_%s_%s", spqp.UserId, common.ObjToString(v["_id"]))
  791. entid := spqp.EntId
  792. entUserId := spqp.EntUserId
  793. deptid := spqp.DeptId
  794. switch s.ModuleFlag {
  795. case "eType":
  796. pushInsert = append(pushInsert, entid, deptid, entUserId, common.InterfaceToStr(infoid), matchkey, now)
  797. case "mType":
  798. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId), common.InterfaceToStr(infoid), matchkey, now)
  799. case "vType":
  800. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId), common.InterfaceToStr(infoid), matchkey, now, 1)
  801. case "fType":
  802. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId), common.InterfaceToStr(infoid), matchkey, now, 0)
  803. }
  804. redis.Put("pushcache_2_a", redisKey, 1, 86400)
  805. resultList[i] = s.InfoFormat(&PushCa{
  806. InfoId: infoid,
  807. Date: time.Now().Unix(),
  808. Keys: matchkeys,
  809. FileExists: v["filetext"] != nil,
  810. }, &v)
  811. }
  812. id := int64(0)
  813. switch s.ModuleFlag {
  814. case "eType":
  815. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, ennicheInsertCollKey, pushInsert)
  816. case "mType":
  817. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, memberInsertCollKey, pushInsert)
  818. default:
  819. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, subscribeInsertCollKey, pushInsert)
  820. }
  821. for i := length - 1; i >= 0; i-- {
  822. resultList[i].CaIndex = id
  823. id++
  824. }
  825. log.Println("数据处理耗时:", time.Since(t2))
  826. return
  827. }
  828. // 获取匹配得关键词
  829. func getKeys(title string, keywords []ViewKeyWord) (str []string) {
  830. if len(keywords) > 0 {
  831. L:
  832. for _, v := range keywords {
  833. for _, vk := range v.Keyword {
  834. if strings.Contains(title, vk) {
  835. str = append(str, v.Keyword...)
  836. break L
  837. }
  838. }
  839. for _, va := range v.Appended {
  840. if strings.Contains(title, va) {
  841. str = append(str, v.Appended...)
  842. break L
  843. }
  844. }
  845. }
  846. }
  847. return
  848. }
  849. // 获取查询语句
  850. func (s *subscribePush) getDefaultDatasSQL(bsp *ViewCondition) (str string) {
  851. query := `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match": %d}}}`
  852. query_bool_should := `{"bool":{"should":[%s],"minimum_should_match": 1}}`
  853. multi_match := `{"multi_match": {"query": %s,"type": "phrase", "fields": [%s]}}`
  854. query_bool_must_and := `{"bool":{"must":[%s]%s}}`
  855. bools := []string{}
  856. musts := []string{}
  857. //发布时间最新7天(正式环境需要修改)
  858. musts = append(musts, fmt.Sprintf(bidTime, time.Now().AddDate(0, 0, -7).Unix()))
  859. //省份
  860. areaCity := []string{}
  861. if len(bsp.Area) > 0 {
  862. areaquery := `{"terms":{"area":[`
  863. for k, v := range bsp.Area {
  864. if k > 0 {
  865. areaquery += `,`
  866. }
  867. areaquery += `"` + v + `"`
  868. }
  869. areaquery += `]}}`
  870. areaCity = append(areaCity, areaquery)
  871. }
  872. //城市
  873. if len(bsp.City) > 0 {
  874. areaquery := `{"terms":{"city":[`
  875. for k, v := range bsp.City {
  876. if k > 0 {
  877. areaquery += `,`
  878. }
  879. areaquery += `"` + v + `"`
  880. }
  881. areaquery += `]}}`
  882. areaCity = append(areaCity, areaquery)
  883. }
  884. if len(areaCity) > 0 {
  885. musts = append(musts, fmt.Sprintf(query_bool_should, strings.Join(areaCity, ",")))
  886. }
  887. if len(bsp.Subtype) > 0 {
  888. subquery := `{"terms":{"subtype":[`
  889. for k, v := range bsp.Subtype {
  890. if k > 0 {
  891. subquery += `,`
  892. }
  893. subquery += `"` + v + `"`
  894. }
  895. subquery += `]}}`
  896. musts = append(musts, subquery)
  897. }
  898. if len(bsp.Buyerclass) > 0 {
  899. Buyerclass := `{"terms":{"buyerclass":[`
  900. for k, v := range bsp.Buyerclass {
  901. if k > 0 {
  902. Buyerclass += `,`
  903. }
  904. Buyerclass += `"` + v + `"`
  905. }
  906. Buyerclass += `]}}`
  907. musts = append(musts, Buyerclass)
  908. }
  909. boolsNum := 0 //should
  910. if len(bsp.Keyword) > 0 {
  911. boolsNum = 1
  912. if bsp.SelectType == "" || bsp.SelectType == "2" {
  913. bsp.SelectType = "detail\", \"title"
  914. } else {
  915. bsp.SelectType = "title"
  916. }
  917. multi_match = fmt.Sprintf(multi_match, "%s", "\""+bsp.SelectType+"\"")
  918. for _, v := range bsp.Keyword {
  919. shoulds := []string{}
  920. must_not := []string{}
  921. //附加词
  922. for _, vv := range v.Keyword {
  923. vv = strings.TrimSpace(vv)
  924. if vv == "" {
  925. continue
  926. }
  927. shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
  928. }
  929. for _, vv := range v.Appended {
  930. vv = strings.TrimSpace(vv)
  931. if vv == "" {
  932. continue
  933. }
  934. shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
  935. }
  936. //排除词
  937. for _, vv := range v.Exclude {
  938. vv = strings.TrimSpace(vv)
  939. if vv == "" {
  940. continue
  941. }
  942. must_not = append(must_not, fmt.Sprintf(multi_match, "\""+vv+"\""))
  943. }
  944. //添加
  945. if len(shoulds) > 0 {
  946. notStr := ""
  947. if len(must_not) > 0 {
  948. notStr = fmt.Sprintf(`,"must_not":[%s]`, strings.Join(must_not, ","))
  949. }
  950. bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(shoulds, ","), notStr))
  951. }
  952. }
  953. }
  954. qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum)
  955. logx.Info("----", qstr)
  956. return qstr
  957. }
  958. /*已选条件--关键词*/
  959. type ViewKeyWord struct {
  960. Keyword []string `json:"key"` //关键词
  961. Appended []string `json:"appendkey"` //附加词
  962. Exclude []string `json:"notkey"` //排除词
  963. MatchWay int `json:"matchway"` //匹配模式
  964. }
  965. /*已选条件*/
  966. type ViewCondition struct {
  967. Area []string //地区-省份
  968. City []string //地区-城市
  969. Buyerclass []string //采购行业
  970. Keyword []ViewKeyWord //关键词
  971. SelectType string //筛选(正文 or 标题)
  972. Subtype []string //信息类型
  973. Size int //数量
  974. }
  975. // 获取用户信息
  976. func (s *subscribePush) getUserInfo(spqp *SubPushQueryParam) (vc *ViewCondition) {
  977. var isPayBool = false
  978. var tmpInfo = struct {
  979. Items []interface{}
  980. BuyerClass []interface{}
  981. SubType []interface{}
  982. Area map[string]interface{}
  983. SelectType string
  984. }{}
  985. switch s.ModuleFlag {
  986. case "mType":
  987. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_member_jy":1,"i_member_status":1}`)
  988. if !ok || userMap == nil || len(*userMap) == 0 {
  989. return &ViewCondition{}
  990. }
  991. //大会员
  992. if common.IntAll((*userMap)["i_member_status"]) > 0 {
  993. isPayBool = true
  994. o_member_jy, _ := (*userMap)["o_member_jy"].(map[string]interface{})
  995. tmpInfo.Items, _ = o_member_jy["a_items"].([]interface{})
  996. tmpInfo.BuyerClass, _ = o_member_jy["a_buyerclass"].([]interface{})
  997. tmpInfo.SubType, _ = o_member_jy["a_infotype"].([]interface{})
  998. tmpInfo.Area, _ = o_member_jy["o_area"].(map[string]interface{})
  999. }
  1000. case "vType":
  1001. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_vipjy":1,"i_vip_status":1}`)
  1002. if !ok || userMap == nil || len(*userMap) == 0 {
  1003. return &ViewCondition{}
  1004. }
  1005. if common.IntAll((*userMap)["i_vip_status"]) > 0 {
  1006. isPayBool = true
  1007. o_vipjy, _ := (*userMap)["o_vipjy"].(map[string]interface{})
  1008. tmpInfo.Items, _ = o_vipjy["a_items"].([]interface{})
  1009. tmpInfo.BuyerClass, _ = o_vipjy["a_buyerclass"].([]interface{})
  1010. tmpInfo.SubType, _ = o_vipjy["a_infotype"].([]interface{})
  1011. tmpInfo.Area, _ = o_vipjy["o_area"].(map[string]interface{})
  1012. }
  1013. case "eType":
  1014. //商机管理
  1015. entUserId, _ := strconv.Atoi(spqp.EntUserId)
  1016. entId, _ := strconv.Atoi(spqp.EntId)
  1017. entInfo, deptId := (&ms.MatchJob{}).Start(entId, entUserId)
  1018. if entInfo != nil && len(entInfo) > 0 {
  1019. spqp.DeptId = strconv.Itoa(deptId)
  1020. isPayBool = true
  1021. tmpInfo.Items, _ = entInfo["a_items"].([]interface{})
  1022. tmpInfo.BuyerClass, _ = entInfo["a_buyerclass"].([]interface{})
  1023. tmpInfo.SubType, _ = entInfo["a_infotype"].([]interface{})
  1024. tmpInfo.Area, _ = entInfo["o_area"].(map[string]interface{})
  1025. }
  1026. default:
  1027. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_jy":1}`)
  1028. if !ok || userMap == nil || len(*userMap) == 0 {
  1029. return &ViewCondition{}
  1030. }
  1031. o_jy, _ := (*userMap)["o_jy"].(map[string]interface{})
  1032. if o_jy["a_key"] != nil {
  1033. tmpInfo.Items, _ = o_jy["a_key"].([]interface{})
  1034. //信息类型
  1035. tmpInfo.SubType, _ = o_jy["a_infotype"].([]interface{})
  1036. //省份
  1037. tmpInfo.Area, _ = o_jy["o_area"].(map[string]interface{})
  1038. if common.IntAllDef(o_jy["i_ppstatus"], 0) == 1 && o_jy["o_area_p"] != nil {
  1039. tmpInfo.Area, _ = o_jy["o_area_p"].(map[string]interface{})
  1040. }
  1041. }
  1042. }
  1043. vc = &ViewCondition{
  1044. Buyerclass: common.ObjArrToStringArr(tmpInfo.BuyerClass),
  1045. Subtype: common.ObjArrToStringArr(tmpInfo.SubType),
  1046. Area: getStringArrFromDbResult(tmpInfo.Area, 1),
  1047. City: getStringArrFromDbResult(tmpInfo.Area, 2),
  1048. SelectType: "1",
  1049. }
  1050. //付费用户
  1051. if isPayBool {
  1052. vc.Size = IC.C.DefaulCount.Pay
  1053. vc.Keyword = getKeyWordArrFromDbResult(tmpInfo.Items, "", -1)
  1054. } else {
  1055. vc.Size = IC.C.DefaulCount.Free
  1056. vc.Keyword = getKeyWordArrFromDbResultByFree(tmpInfo.Items, "", -1)
  1057. //vc.Keyword = getKeyWordArrFromDbResult(tmpInfo.Items, "", -1)
  1058. }
  1059. return
  1060. }
  1061. // 关键词 附加词 排除词
  1062. func getKeyWordArrFromDbResult(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
  1063. if a_items == nil {
  1064. return
  1065. }
  1066. for _, v := range a_items {
  1067. vm, _ := v.(map[string]interface{})
  1068. if item != "" && index >= 0 && item != common.ObjToString(vm["s_item"]) {
  1069. continue
  1070. }
  1071. kwsArr := vm["a_key"]
  1072. for i, k := range kwsArr.([]interface{}) {
  1073. if item != "" && index >= 0 && i != index {
  1074. continue
  1075. }
  1076. kw := ViewKeyWord{}
  1077. b, e := json.Marshal(k)
  1078. if e != nil {
  1079. log.Println(e.Error())
  1080. }
  1081. json.Unmarshal(b, &kw)
  1082. if kw.MatchWay == 1 {
  1083. for _, kk := range kw.Keyword {
  1084. arr = append(arr, ViewKeyWord{
  1085. Keyword: []string{kk},
  1086. Exclude: kw.Exclude,
  1087. })
  1088. }
  1089. for _, kk := range kw.Appended {
  1090. arr = append(arr, ViewKeyWord{
  1091. Keyword: []string{kk},
  1092. Exclude: kw.Exclude,
  1093. })
  1094. }
  1095. } else {
  1096. arr = append(arr, kw)
  1097. }
  1098. }
  1099. }
  1100. return
  1101. }
  1102. // //关键词 附加词 排除词 省份订阅包 - 普通用户
  1103. func getKeyWordArrFromDbResultByFree(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
  1104. if a_items == nil {
  1105. return
  1106. }
  1107. for _, v := range a_items {
  1108. kw := ViewKeyWord{}
  1109. b, e := json.Marshal(v)
  1110. if e != nil {
  1111. log.Println(e.Error())
  1112. }
  1113. json.Unmarshal(b, &kw)
  1114. if kw.MatchWay == 1 {
  1115. for _, kk := range kw.Keyword {
  1116. arr = append(arr, ViewKeyWord{
  1117. Keyword: []string{kk},
  1118. Exclude: kw.Exclude,
  1119. })
  1120. }
  1121. for _, kk := range kw.Appended {
  1122. arr = append(arr, ViewKeyWord{
  1123. Keyword: []string{kk},
  1124. Exclude: kw.Exclude,
  1125. })
  1126. }
  1127. } else {
  1128. arr = append(arr, kw)
  1129. }
  1130. }
  1131. return
  1132. }
  1133. // 地区格式化
  1134. func getStringArrFromDbResult(area map[string]interface{}, i int) (arr []string) {
  1135. if area == nil {
  1136. return
  1137. }
  1138. var eareArr []string
  1139. var cityArr []string
  1140. for k, v := range area {
  1141. if len(v.([]interface{})) > 0 {
  1142. cityArr = append(cityArr, common.ObjArrToStringArr(v.([]interface{}))...)
  1143. } else {
  1144. eareArr = append(eareArr, k)
  1145. }
  1146. }
  1147. if i == 1 {
  1148. arr = eareArr
  1149. } else {
  1150. arr = cityArr
  1151. }
  1152. return
  1153. }
  1154. // IsInTsGuide 是否进入向导
  1155. func (s *subscribePush) IsInTsGuide(userid string) bool {
  1156. if userid == "" {
  1157. return false
  1158. }
  1159. data, ok := IC.Mgo.FindById("user", userid, `{"o_jy":1,"i_ts_guide":1,"":1,"i_member_status":1,"i_vip_status":1}`)
  1160. if ok {
  1161. //付费用户无免费订阅,不进入订阅向导页面
  1162. if common.IntAll((*data)["i_member_status"]) > 0 || common.IntAll((*data)["i_vip_status"]) > 0 {
  1163. return false
  1164. }
  1165. o_jy, _ := (*data)["o_jy"].(map[string]interface{})
  1166. i_ts_guide := common.IntAll((*data)["i_ts_guide"])
  1167. if i_ts_guide == 2 || (i_ts_guide == 0 && len(o_jy) == 0) {
  1168. return true
  1169. }
  1170. }
  1171. return false
  1172. }