push.go 38 KB

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