push.go 38 KB

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