push.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  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.InterfaceToStr((*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, true)
  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. var (
  289. searchSql, findSql string
  290. )
  291. if spqp.SelectInfoIds != nil && len(spqp.SelectInfoIds) > 0 {
  292. 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, "','")))
  293. fmt.Println("searchSql", searchSql)
  294. //查询总数
  295. count = spqp.BaseServiceMysql.CountBySql(fmt.Sprintf("select count(a.id)" + searchSql))
  296. findSql = "select a.id,a.date,a.infoid,a.isvisit,a.matchkeys,a.type,b.isvalidfile as attachment_count"
  297. } else {
  298. if spqp.IsEnt {
  299. querys = []string{fmt.Sprintf("a.entid='%s'", spqp.EntId)}
  300. } else {
  301. querys = []string{fmt.Sprintf("a.userid='%s'", common.If(s.ModuleFlag == "eType", spqp.EntUserId, common.InterfaceToStr(spqp.NewUserId)))}
  302. }
  303. codeMap, err := IC.CodeLib.CodeTransformation(context.Background(), &codeservice.Request{})
  304. if codeMap.Data == nil || err != nil {
  305. logx.Error("代码表获取失败")
  306. return result, count
  307. }
  308. //时间
  309. logx.Info("starttime,endtime", starttime, endtime)
  310. if starttime > 0 && endtime > 0 {
  311. querys = append(querys, fmt.Sprintf("a.date>=%d and date<=%d", starttime, endtime))
  312. } else if starttime > 0 && endtime == 0 {
  313. querys = append(querys, fmt.Sprintf("a.date>=%d", starttime))
  314. } else if starttime == 0 && endtime > 0 {
  315. querys = append(querys, fmt.Sprintf("a.date<=%d", endtime))
  316. }
  317. if spqp.Area != "" || spqp.City != "" {
  318. var sqlAreaCity = ""
  319. //城市
  320. city := []string{}
  321. for _, v := range strings.Split(spqp.City, ",") {
  322. if codeMap.Data.City[v] != "" {
  323. city = append(city, fmt.Sprint(codeMap.Data.City[v]))
  324. } else {
  325. city = append(city, "-1")
  326. }
  327. }
  328. if len(city) == 1 {
  329. city = append(city, "9999")
  330. }
  331. if len(city) > 0 {
  332. sqlAreaCity = fmt.Sprintf("b.city_code in (%s)", strings.Join(city, ","))
  333. }
  334. //区域
  335. var sqlArea = ""
  336. area := []string{}
  337. for _, v := range strings.Split(spqp.Area, ",") {
  338. if codeMap.Data.Area[v] != "" {
  339. area = append(area, fmt.Sprint(codeMap.Data.Area[v]))
  340. } else {
  341. area = append(area, "-1")
  342. }
  343. }
  344. if len(area) == 1 {
  345. area = append(area, "9999")
  346. }
  347. if len(area) > 0 {
  348. sqlArea = fmt.Sprintf("b.area_code in (%s)", strings.Join(area, ","))
  349. }
  350. if sqlAreaCity != "" && sqlArea != "" {
  351. sqlAreaCity = "( " + sqlAreaCity + " or " + sqlArea + " )"
  352. } else if sqlAreaCity == "" && sqlArea != "" {
  353. sqlAreaCity = sqlArea
  354. }
  355. if sqlAreaCity != "" {
  356. querys = append(querys, sqlAreaCity)
  357. }
  358. }
  359. //采购单位行业
  360. if spqp.Buyerclass != "" {
  361. buyerclass := []string{}
  362. for _, v := range strings.Split(spqp.Buyerclass, ",") {
  363. if codeMap.Data.Buyerclass[v] != "" {
  364. buyerclass = append(buyerclass, fmt.Sprint(codeMap.Data.Buyerclass[v]))
  365. }
  366. }
  367. if len(buyerclass) == 1 {
  368. buyerclass = append(buyerclass, "9999")
  369. }
  370. if len(buyerclass) > 0 {
  371. querys = append(querys, fmt.Sprintf("b.buyerclass_code in (%s)", strings.Join(buyerclass, ",")))
  372. }
  373. }
  374. //信息类型
  375. if spqp.Subtype != "" {
  376. subtype := []string{}
  377. for _, v := range strings.Split(spqp.Subtype, ",") {
  378. if codeMap.Data.Subtype[v] != "" {
  379. subtype = append(subtype, fmt.Sprint(codeMap.Data.Subtype[v]))
  380. }
  381. }
  382. if len(subtype) == 1 {
  383. subtype = append(subtype, "9999")
  384. }
  385. if len(subtype) > 0 {
  386. querys = append(querys, fmt.Sprintf("b.subtype_code in (%s)", strings.Join(subtype, ",")))
  387. }
  388. }
  389. //信息行业
  390. if spqp.Subscopeclass != "" {
  391. find_in_set := []string{}
  392. for _, v := range strings.Split(spqp.Subscopeclass, ",") {
  393. if codeMap.Data.Subscopeclass[v] != "" {
  394. find_in_set = append(find_in_set, codeMap.Data.Subscopeclass[v])
  395. }
  396. }
  397. if len(find_in_set) == 1 {
  398. find_in_set = append(find_in_set, "9999")
  399. }
  400. if len(find_in_set) > 0 {
  401. querys = append(querys, fmt.Sprintf(" t.labelvalues in (%s)", strings.Join(find_in_set, ",")))
  402. }
  403. }
  404. //关键词
  405. if spqp.Key != "" {
  406. find_in_set := []string{}
  407. for _, v := range strings.Split(spqp.Key, ",") {
  408. find_in_set = append(find_in_set, fmt.Sprintf("find_in_set('%s',replace(replace(a.matchkeys,'+',','),' ',','))", v))
  409. }
  410. if len(find_in_set) == 1 {
  411. querys = append(querys, find_in_set[0])
  412. } else if len(find_in_set) > 1 {
  413. querys = append(querys, fmt.Sprintf("(%s)", strings.Join(find_in_set, " or ")))
  414. }
  415. }
  416. //价格- 预算和中标金额
  417. if spqp.Price != "" && strings.Contains(spqp.Price, "-") {
  418. minPriceStr, maxPriceStr := strings.Split(spqp.Price, "-")[0], strings.Split(spqp.Price, "-")[1]
  419. minPrice := common.Int64All(common.Float64All(minPriceStr) * 10000) //换成元
  420. maxPrice := common.Int64All(common.Float64All(maxPriceStr) * 10000) //换成元
  421. if minPriceStr != "" && maxPriceStr != "" {
  422. 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))
  423. } else if minPriceStr != "" {
  424. querys = append(querys, fmt.Sprintf("(b.bidamount>=%d or (b.budget>=%d and b.bidamount is null))", minPrice, minPrice))
  425. } else if maxPriceStr != "" {
  426. querys = append(querys, fmt.Sprintf("(b.bidamount<=%d or (b.budget<=%d and b.bidamount is null))", maxPrice, maxPrice))
  427. }
  428. }
  429. //附件
  430. if spqp.FileExists != "" {
  431. if spqp.FileExists == "1" {
  432. querys = append(querys, fmt.Sprintf("b.isvalidfile =1 "))
  433. } else if spqp.FileExists == "-1" {
  434. querys = append(querys, fmt.Sprintf("b.isvalidfile =0 "))
  435. }
  436. }
  437. searchSql = fmt.Sprintf(" from %s a LEFT JOIN %s b ON a.infoid = b.infoid LEFT JOIN %s t on t.infoid = b.infoid and t.labelcode=2 where %s"+
  438. " order by a.id desc", aboutDbMsg[s.ModuleFlag].MysqlTable, Baseinfo, BidTags, strings.Join(querys, " and "))
  439. logx.Info("searchSql", searchSql)
  440. //查询总数
  441. logx.Info(fmt.Sprintf("select count(a.id) " + searchSql))
  442. count = spqp.BaseServiceMysql.CountBySql(fmt.Sprintf("select count(a.id) " + searchSql))
  443. logx.Info("count:", count, "---", s.ModuleFlag)
  444. findSql = "select a.id,a.date,a.infoid,a.isvisit,a.matchkeys,a.type,b.isvalidfile as attachment_count"
  445. }
  446. if s.ModuleFlag != MemberFlag && s.ModuleFlag != EntnicheFlag {
  447. findSql += ",a.isvip"
  448. }
  449. findSql += searchSql
  450. if isLimit {
  451. findSql += fmt.Sprintf(" limit %d,%d", (spqp.PageNum-1)*size, size)
  452. }
  453. logx.Info("findSql", findSql)
  454. logx.Info(spqp.NewUserId, "subscribePush query sql:", findSql)
  455. list := spqp.BaseServiceMysql.SelectBySql(findSql)
  456. if list != nil && len(*list) > 0 {
  457. logx.Info("数据库数据", list)
  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()
  781. var pushInsert = []interface{}{}
  782. for _, v := range list {
  783. title := strings.Replace(common.ObjToString(v["title"]), "\n", "", -1)
  784. infoid := common.InterfaceToStr(v["_id"])
  785. matchkeys := getKeys(title, keyword)
  786. matchkey := strings.Join(matchkeys, " ")
  787. redisKey := fmt.Sprintf("pushinfo_%s_%s", spqp.UserId, common.ObjToString(v["_id"]))
  788. entid := spqp.EntId
  789. entUserId := spqp.EntUserId
  790. deptid := spqp.DeptId
  791. switch s.ModuleFlag {
  792. case "eType":
  793. pushInsert = append(pushInsert, entid, deptid, entUserId, common.InterfaceToStr(infoid), matchkey, now)
  794. case "mType":
  795. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId), common.InterfaceToStr(infoid), matchkey, now)
  796. case "vType":
  797. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId), common.InterfaceToStr(infoid), matchkey, now, 1)
  798. case "fType":
  799. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId), common.InterfaceToStr(infoid), matchkey, now, 0)
  800. }
  801. redis.Put("pushcache_2_a", redisKey, 1, 86400)
  802. resultList = append(resultList, s.InfoFormat(&PushCa{
  803. InfoId: infoid,
  804. Date: time.Now().Unix(),
  805. Keys: matchkeys,
  806. FileExists: v["filetext"] != nil,
  807. }, &v))
  808. }
  809. id := int64(0)
  810. switch s.ModuleFlag {
  811. case "eType":
  812. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, ennicheInsertCollKey, pushInsert)
  813. case "mType":
  814. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, memberInsertCollKey, pushInsert)
  815. default:
  816. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, subscribeInsertCollKey, pushInsert)
  817. }
  818. for i := 0; i < len(resultList); i++ {
  819. resultList[i].CaIndex = id
  820. id--
  821. }
  822. log.Println("数据处理耗时:", time.Since(t2))
  823. return
  824. }
  825. // 获取匹配得关键词
  826. func getKeys(title string, keywords []ViewKeyWord) (str []string) {
  827. if len(keywords) > 0 {
  828. L:
  829. for _, v := range keywords {
  830. for _, vk := range v.Keyword {
  831. if strings.Contains(title, vk) {
  832. str = append(str, v.Keyword...)
  833. break L
  834. }
  835. }
  836. for _, va := range v.Appended {
  837. if strings.Contains(title, va) {
  838. str = append(str, v.Appended...)
  839. break L
  840. }
  841. }
  842. }
  843. }
  844. return
  845. }
  846. // 获取查询语句
  847. func (s *subscribePush) getDefaultDatasSQL(bsp *ViewCondition) (str string) {
  848. query := `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match": %d}}}`
  849. query_bool_should := `{"bool":{"should":[%s],"minimum_should_match": 1}}`
  850. multi_match := `{"multi_match": {"query": %s,"type": "phrase", "fields": [%s]}}`
  851. query_bool_must_and := `{"bool":{"must":[%s]%s}}`
  852. bools := []string{}
  853. musts := []string{}
  854. //发布时间最新7天(正式环境需要修改)
  855. musts = append(musts, fmt.Sprintf(bidTime, time.Now().AddDate(0, 0, -365).Unix()))
  856. //省份
  857. areaCity := []string{}
  858. if len(bsp.Area) > 0 {
  859. areaquery := `{"terms":{"area":[`
  860. for k, v := range bsp.Area {
  861. if k > 0 {
  862. areaquery += `,`
  863. }
  864. areaquery += `"` + v + `"`
  865. }
  866. areaquery += `]}}`
  867. areaCity = append(areaCity, areaquery)
  868. }
  869. //城市
  870. if len(bsp.City) > 0 {
  871. areaquery := `{"terms":{"city":[`
  872. for k, v := range bsp.City {
  873. if k > 0 {
  874. areaquery += `,`
  875. }
  876. areaquery += `"` + v + `"`
  877. }
  878. areaquery += `]}}`
  879. areaCity = append(areaCity, areaquery)
  880. }
  881. if len(areaCity) > 0 {
  882. musts = append(musts, fmt.Sprintf(query_bool_should, strings.Join(areaCity, ",")))
  883. }
  884. if len(bsp.Subtype) > 0 {
  885. subquery := `{"terms":{"subtype":[`
  886. for k, v := range bsp.Subtype {
  887. if k > 0 {
  888. subquery += `,`
  889. }
  890. subquery += `"` + v + `"`
  891. }
  892. subquery += `]}}`
  893. musts = append(musts, subquery)
  894. }
  895. if len(bsp.Buyerclass) > 0 {
  896. Buyerclass := `{"terms":{"buyerclass":[`
  897. for k, v := range bsp.Buyerclass {
  898. if k > 0 {
  899. Buyerclass += `,`
  900. }
  901. Buyerclass += `"` + v + `"`
  902. }
  903. Buyerclass += `]}}`
  904. musts = append(musts, Buyerclass)
  905. }
  906. boolsNum := 0 //should
  907. if len(bsp.Keyword) > 0 {
  908. boolsNum = 1
  909. if bsp.SelectType == "" || bsp.SelectType == "2" {
  910. bsp.SelectType = "detail\", \"title"
  911. } else {
  912. bsp.SelectType = "title"
  913. }
  914. multi_match = fmt.Sprintf(multi_match, "%s", "\""+bsp.SelectType+"\"")
  915. for _, v := range bsp.Keyword {
  916. shoulds := []string{}
  917. must_not := []string{}
  918. //附加词
  919. for _, vv := range v.Keyword {
  920. vv = strings.TrimSpace(vv)
  921. if vv == "" {
  922. continue
  923. }
  924. shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
  925. }
  926. for _, vv := range v.Appended {
  927. vv = strings.TrimSpace(vv)
  928. if vv == "" {
  929. continue
  930. }
  931. shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
  932. }
  933. //排除词
  934. for _, vv := range v.Exclude {
  935. vv = strings.TrimSpace(vv)
  936. if vv == "" {
  937. continue
  938. }
  939. must_not = append(must_not, fmt.Sprintf(multi_match, "\""+vv+"\""))
  940. }
  941. //添加
  942. if len(shoulds) > 0 {
  943. notStr := ""
  944. if len(must_not) > 0 {
  945. notStr = fmt.Sprintf(`,"must_not":[%s]`, strings.Join(must_not, ","))
  946. }
  947. bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(shoulds, ","), notStr))
  948. }
  949. }
  950. }
  951. qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum)
  952. logx.Info("----", qstr)
  953. return qstr
  954. }
  955. /*已选条件--关键词*/
  956. type ViewKeyWord struct {
  957. Keyword []string `json:"key"` //关键词
  958. Appended []string `json:"appendkey"` //附加词
  959. Exclude []string `json:"notkey"` //排除词
  960. MatchWay int `json:"matchway"` //匹配模式
  961. }
  962. /*已选条件*/
  963. type ViewCondition struct {
  964. Area []string //地区-省份
  965. City []string //地区-城市
  966. Buyerclass []string //采购行业
  967. Keyword []ViewKeyWord //关键词
  968. SelectType string //筛选(正文 or 标题)
  969. Subtype []string //信息类型
  970. Size int //数量
  971. }
  972. // 获取用户信息
  973. func (s *subscribePush) getUserInfo(spqp *SubPushQueryParam) (vc *ViewCondition) {
  974. var isPayBool = false
  975. var tmpInfo = struct {
  976. Items []interface{}
  977. BuyerClass []interface{}
  978. SubType []interface{}
  979. Area map[string]interface{}
  980. SelectType string
  981. }{}
  982. switch s.ModuleFlag {
  983. case "mType":
  984. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_member_jy":1,"i_member_status":1}`)
  985. if !ok || userMap == nil || len(*userMap) == 0 {
  986. return &ViewCondition{}
  987. }
  988. //大会员
  989. if common.IntAll((*userMap)["i_member_status"]) > 0 {
  990. isPayBool = true
  991. o_member_jy, _ := (*userMap)["o_member_jy"].(map[string]interface{})
  992. tmpInfo.Items, _ = o_member_jy["a_items"].([]interface{})
  993. tmpInfo.BuyerClass, _ = o_member_jy["a_buyerclass"].([]interface{})
  994. tmpInfo.SubType, _ = o_member_jy["a_infotype"].([]interface{})
  995. tmpInfo.Area, _ = o_member_jy["o_area"].(map[string]interface{})
  996. }
  997. case "vType":
  998. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_vipjy":1,"i_vip_status":1}`)
  999. if !ok || userMap == nil || len(*userMap) == 0 {
  1000. return &ViewCondition{}
  1001. }
  1002. if common.IntAll((*userMap)["i_vip_status"]) > 0 {
  1003. isPayBool = true
  1004. o_vipjy, _ := (*userMap)["o_vipjy"].(map[string]interface{})
  1005. tmpInfo.Items, _ = o_vipjy["a_items"].([]interface{})
  1006. tmpInfo.BuyerClass, _ = o_vipjy["a_buyerclass"].([]interface{})
  1007. tmpInfo.SubType, _ = o_vipjy["a_infotype"].([]interface{})
  1008. tmpInfo.Area, _ = o_vipjy["o_area"].(map[string]interface{})
  1009. }
  1010. case "eType":
  1011. //商机管理
  1012. entUserId, _ := strconv.Atoi(spqp.EntUserId)
  1013. entId, _ := strconv.Atoi(spqp.EntId)
  1014. entInfo, deptId := (&ms.MatchJob{}).Start(entId, entUserId)
  1015. if entInfo != nil && len(entInfo) > 0 {
  1016. spqp.DeptId = strconv.Itoa(deptId)
  1017. isPayBool = true
  1018. tmpInfo.Items, _ = entInfo["a_items"].([]interface{})
  1019. tmpInfo.BuyerClass, _ = entInfo["a_buyerclass"].([]interface{})
  1020. tmpInfo.SubType, _ = entInfo["a_infotype"].([]interface{})
  1021. tmpInfo.Area, _ = entInfo["o_area"].(map[string]interface{})
  1022. }
  1023. default:
  1024. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_jy":1}`)
  1025. if !ok || userMap == nil || len(*userMap) == 0 {
  1026. return &ViewCondition{}
  1027. }
  1028. o_jy, _ := (*userMap)["o_jy"].(map[string]interface{})
  1029. if o_jy["a_key"] != nil {
  1030. tmpInfo.Items, _ = o_jy["a_key"].([]interface{})
  1031. //信息类型
  1032. tmpInfo.SubType, _ = o_jy["a_infotype"].([]interface{})
  1033. //省份
  1034. tmpInfo.Area, _ = o_jy["o_area"].(map[string]interface{})
  1035. if common.IntAllDef(o_jy["i_ppstatus"], 0) == 1 && o_jy["o_area_p"] != nil {
  1036. tmpInfo.Area, _ = o_jy["o_area_p"].(map[string]interface{})
  1037. }
  1038. }
  1039. }
  1040. vc = &ViewCondition{
  1041. Buyerclass: common.ObjArrToStringArr(tmpInfo.BuyerClass),
  1042. Subtype: common.ObjArrToStringArr(tmpInfo.SubType),
  1043. Area: getStringArrFromDbResult(tmpInfo.Area, 1),
  1044. City: getStringArrFromDbResult(tmpInfo.Area, 2),
  1045. SelectType: "1",
  1046. }
  1047. //付费用户
  1048. if isPayBool {
  1049. vc.Size = IC.C.DefaulCount.Pay
  1050. vc.Keyword = getKeyWordArrFromDbResult(tmpInfo.Items, "", -1)
  1051. } else {
  1052. vc.Size = IC.C.DefaulCount.Free
  1053. vc.Keyword = getKeyWordArrFromDbResultByFree(tmpInfo.Items, "", -1)
  1054. //vc.Keyword = getKeyWordArrFromDbResult(tmpInfo.Items, "", -1)
  1055. }
  1056. return
  1057. }
  1058. // 关键词 附加词 排除词
  1059. func getKeyWordArrFromDbResult(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
  1060. if a_items == nil {
  1061. return
  1062. }
  1063. for _, v := range a_items {
  1064. vm, _ := v.(map[string]interface{})
  1065. if item != "" && index >= 0 && item != common.ObjToString(vm["s_item"]) {
  1066. continue
  1067. }
  1068. kwsArr := vm["a_key"]
  1069. for i, k := range kwsArr.([]interface{}) {
  1070. if item != "" && index >= 0 && i != index {
  1071. continue
  1072. }
  1073. kw := ViewKeyWord{}
  1074. b, e := json.Marshal(k)
  1075. if e != nil {
  1076. log.Println(e.Error())
  1077. }
  1078. json.Unmarshal(b, &kw)
  1079. if kw.MatchWay == 1 {
  1080. for _, kk := range kw.Keyword {
  1081. arr = append(arr, ViewKeyWord{
  1082. Keyword: []string{kk},
  1083. Exclude: kw.Exclude,
  1084. })
  1085. }
  1086. for _, kk := range kw.Appended {
  1087. arr = append(arr, ViewKeyWord{
  1088. Keyword: []string{kk},
  1089. Exclude: kw.Exclude,
  1090. })
  1091. }
  1092. } else {
  1093. arr = append(arr, kw)
  1094. }
  1095. }
  1096. }
  1097. return
  1098. }
  1099. // //关键词 附加词 排除词 省份订阅包 - 普通用户
  1100. func getKeyWordArrFromDbResultByFree(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
  1101. if a_items == nil {
  1102. return
  1103. }
  1104. for _, v := range a_items {
  1105. kw := ViewKeyWord{}
  1106. b, e := json.Marshal(v)
  1107. if e != nil {
  1108. log.Println(e.Error())
  1109. }
  1110. json.Unmarshal(b, &kw)
  1111. if kw.MatchWay == 1 {
  1112. for _, kk := range kw.Keyword {
  1113. arr = append(arr, ViewKeyWord{
  1114. Keyword: []string{kk},
  1115. Exclude: kw.Exclude,
  1116. })
  1117. }
  1118. for _, kk := range kw.Appended {
  1119. arr = append(arr, ViewKeyWord{
  1120. Keyword: []string{kk},
  1121. Exclude: kw.Exclude,
  1122. })
  1123. }
  1124. } else {
  1125. arr = append(arr, kw)
  1126. }
  1127. }
  1128. return
  1129. }
  1130. // 地区格式化
  1131. func getStringArrFromDbResult(area map[string]interface{}, i int) (arr []string) {
  1132. if area == nil {
  1133. return
  1134. }
  1135. var eareArr []string
  1136. var cityArr []string
  1137. for k, v := range area {
  1138. if len(v.([]interface{})) > 0 {
  1139. cityArr = append(cityArr, common.ObjArrToStringArr(v.([]interface{}))...)
  1140. } else {
  1141. eareArr = append(eareArr, k)
  1142. }
  1143. }
  1144. if i == 1 {
  1145. arr = eareArr
  1146. } else {
  1147. arr = cityArr
  1148. }
  1149. return
  1150. }
  1151. // IsInTsGuide 是否进入向导
  1152. func (s *subscribePush) IsInTsGuide(userid string) bool {
  1153. if userid == "" {
  1154. return false
  1155. }
  1156. data, ok := IC.Mgo.FindById("user", userid, `{"o_jy":1,"i_ts_guide":1,"":1,"i_member_status":1,"i_vip_status":1}`)
  1157. if ok {
  1158. //付费用户无免费订阅,不进入订阅向导页面
  1159. if common.IntAll((*data)["i_member_status"]) > 0 || common.IntAll((*data)["i_vip_status"]) > 0 {
  1160. return false
  1161. }
  1162. o_jy, _ := (*data)["o_jy"].(map[string]interface{})
  1163. i_ts_guide := common.IntAll((*data)["i_ts_guide"])
  1164. if i_ts_guide == 2 || (i_ts_guide == 0 && len(o_jy) == 0) {
  1165. return true
  1166. }
  1167. }
  1168. return false
  1169. }