push.go 37 KB

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