push.go 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499
  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", "source"}
  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. Source int64
  67. }
  68. // 查询参数
  69. type SubPushQueryParam struct {
  70. Mgo_bidding mongodb.MongodbSim //
  71. Bidding string //
  72. Bidding_back string //
  73. UserId string //用户id
  74. PageNum int //页面
  75. PageSize int //每页数量
  76. SelectTime string //时间
  77. Area string //区域
  78. City string //城市
  79. Buyerclass string //采购单位行业
  80. Subtype string //信息类型 二级分类
  81. Subscopeclass string //信息行业
  82. Key string //订阅词
  83. Export bool //导出
  84. EntId string //企业id
  85. Price string //价格
  86. FileExists string //是否有附件;默认全部;1:有附件;-1:无附件
  87. EntUserId string //商机管理用户id
  88. DeptId string //商机管理用户部门id
  89. BaseServiceMysql *mysql.Mysql
  90. NewUserId int64
  91. IsEnt bool
  92. SelectInfoIds []string
  93. BuySubject int64
  94. }
  95. // 关键词参数
  96. type KeyParam struct {
  97. UserId string //用户id
  98. EntUserId string //商机管理用户id
  99. DeptId string //商机管理用户部门id
  100. NewUserId int64
  101. IsEnt bool
  102. VipPower int64
  103. EntId string //企业id
  104. MemberPower int64
  105. PowerSource int64
  106. UserPower int64
  107. }
  108. func (spqp *SubPushQueryParam) IsEmpty() bool {
  109. return (spqp.SelectTime == "" || spqp.SelectTime == "all") && spqp.Area == "" && spqp.City == "" && spqp.Buyerclass == "" && spqp.Subscopeclass == "" && spqp.Subtype == "" && spqp.Key == "" && spqp.Price == "" && spqp.FileExists == ""
  110. }
  111. type subscribePush struct {
  112. ModuleFlag string
  113. }
  114. func NewSubscribePush(module ...string) *subscribePush {
  115. m := ""
  116. if len(module) > 0 {
  117. m = module[0]
  118. }
  119. return &subscribePush{m}
  120. }
  121. // 从pushcache_2_a中取
  122. func (s *subscribePush) GetTodayCache(userId string) (*SubPush, error) {
  123. pc_a, err := redis.GetNewBytes("pushcache_2_b", s.todayKey(userId))
  124. if err != nil {
  125. return nil, err
  126. }
  127. if pc_a == nil {
  128. return nil, nil
  129. }
  130. var p *SubPush
  131. if err := json.Unmarshal(*pc_a, &p); err != nil {
  132. return nil, err
  133. }
  134. return p, nil
  135. }
  136. // 往pushcache_2_a中放
  137. func (s *subscribePush) PutTodayCache(userId string, pc_a *SubPush) {
  138. redis.Put("pushcache_2_b", s.todayKey(userId), pc_a, oneDay)
  139. }
  140. // 获取redis key
  141. func (s *subscribePush) todayKey(userId string) string {
  142. return fmt.Sprintf("%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, userId)
  143. }
  144. func (s *subscribePush) allKey(userId string) string {
  145. return fmt.Sprintf("all_%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, userId)
  146. }
  147. // 历史推送记录中单条信息格式化
  148. func (s *subscribePush) InfoFormat(p *PushCa, info *map[string]interface{}) *bxsubscribe.SubscribeInfo {
  149. area := common.ObjToString((*info)["area"])
  150. if area == "A" {
  151. area = "全国"
  152. }
  153. industry := common.ObjToString((*info)["s_subscopeclass"])
  154. scs := strings.Split(industry, ",")
  155. if len(scs) > 0 {
  156. industry = scs[0]
  157. if industry != "" {
  158. iss := strings.Split(industry, "_")
  159. if len(iss) > 0 {
  160. industry = iss[0]
  161. }
  162. }
  163. }
  164. infotype := common.ObjToString((*info)["subtype"])
  165. if infotype == "" {
  166. infotype = common.ObjToString((*info)["toptype"])
  167. }
  168. _id := p.InfoId
  169. if _id == "" {
  170. _id = common.ObjToString((*info)["_id"])
  171. }
  172. return &bxsubscribe.SubscribeInfo{
  173. XId: encrypt.EncodeArticleId2ByCheck(_id),
  174. Title: common.InterfaceToStr((*info)["title"]),
  175. Area: area,
  176. BuyerClass: common.InterfaceToStr((*info)["buyerclass"]),
  177. Subtype: infotype,
  178. Industry: industry,
  179. PublishTime: common.Int64All((*info)["publishtime"]),
  180. CaIndex: p.Index,
  181. CaDate: p.Date,
  182. CaIsvisit: int64(p.Visit),
  183. CaIsvip: int64(p.Isvip),
  184. CaType: int64(p.Type),
  185. MatchKeys: p.Keys,
  186. Budget: common.InterfaceToStr((*info)["budget"]),
  187. BidAmount: common.InterfaceToStr((*info)["bidamount"]),
  188. Buyer: common.InterfaceToStr((*info)["buyer"]),
  189. ProjectName: common.InterfaceToStr((*info)["projectname"]),
  190. Winner: common.InterfaceToStr((*info)["s_winner"]),
  191. BidOpenTime: common.Int64All((*info)["bidopentime"]),
  192. CaFileExists: p.FileExists,
  193. Source: p.Source,
  194. }
  195. }
  196. func (s *subscribePush) Datas(spqp *SubPushQueryParam) (hasNextPage bool, total int64, result []*bxsubscribe.SubscribeInfo) {
  197. 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)
  198. if spqp.UserId == "" {
  199. return
  200. }
  201. if spqp.PageNum < 1 {
  202. spqp.PageNum = 1
  203. }
  204. if spqp.PageSize < 1 || spqp.PageSize > pageSize {
  205. if !spqp.Export {
  206. spqp.PageSize = pageSize
  207. } else { //数据导出查询20000条限制
  208. if spqp.PageSize < 1 || spqp.PageSize > 20000 {
  209. spqp.PageSize = 20000
  210. }
  211. }
  212. }
  213. starttime, endtime := int64(0), int64(0)
  214. if len(strings.Split(spqp.SelectTime, "_")) == 2 {
  215. st := strings.Split(spqp.SelectTime, "_")[0]
  216. et := strings.Split(spqp.SelectTime, "_")[1]
  217. if st != "" && et != "" {
  218. starttime, _ = strconv.ParseInt(st, 0, 64)
  219. endtime, _ = strconv.ParseInt(et, 0, 64)
  220. if endtime > 0 {
  221. etTime := time.Unix(endtime, 0)
  222. endtime = time.Date(etTime.Year(), etTime.Month(), etTime.Day(), 23, 59, 59, 0, time.Local).Unix()
  223. }
  224. }
  225. }
  226. nowFormat := date.NowFormat(date.Date_Short_Layout)
  227. start := (spqp.PageNum - 1) * spqp.PageSize
  228. end := start + spqp.PageSize
  229. //时间是今天,没有别的过滤条件--首先读取当前推送缓存数据 其次查询数据库
  230. 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 == "" {
  231. logx.Info("a1:", s.todayKey(spqp.UserId))
  232. subPush := &SubPush{}
  233. var err error
  234. if spqp.IsEnt == false {
  235. subPush, err = s.GetTodayCache(spqp.UserId)
  236. }
  237. if err != nil {
  238. logx.Info(spqp.UserId, "GetTodayCache Error", err)
  239. }
  240. if err != nil || subPush == nil || subPush.Date != nowFormat || len(subPush.Datas) == 0 {
  241. list, countSearch := s.getDatasFromMysql(spqp, starttime, endtime, spqp.PageSize, false)
  242. subPush = &SubPush{
  243. Date: nowFormat,
  244. Datas: list,
  245. Count: countSearch,
  246. }
  247. if spqp.IsEnt == false {
  248. s.PutTodayCache(spqp.UserId, subPush)
  249. }
  250. }
  251. length := len(subPush.Datas)
  252. if end > length {
  253. end = length
  254. }
  255. if start < length {
  256. result = subPush.Datas[start:end]
  257. }
  258. total = int64(length)
  259. //全部,没有过滤条件 之前缓存500
  260. } else if spqp.IsEmpty() && (spqp.PageNum-1)*spqp.PageSize < 500 && len(spqp.SelectInfoIds) == 0 && !spqp.Export { //全部,没有过滤条件 之前缓存5页*50条=250 非数据导出
  261. logx.Info("a2:", s.allKey(spqp.UserId))
  262. allCache := &SubPush{}
  263. var err error
  264. if spqp.IsEnt == false {
  265. allCache, err = s.GetAllCache(spqp.UserId)
  266. }
  267. if err != nil {
  268. logx.Info(spqp.UserId, "GetAllCache Error", err)
  269. }
  270. if err != nil || allCache == nil || allCache.Date != nowFormat || len(allCache.Datas) == 0 {
  271. spqp.PageNum = 1
  272. logx.Info(1111)
  273. list, countSearch := s.getDatasFromMysql(spqp, starttime, endtime, AllSubPushCacheSize, true)
  274. allCache = &SubPush{
  275. Date: nowFormat,
  276. Datas: list,
  277. Count: countSearch,
  278. }
  279. if spqp.IsEnt == false {
  280. s.PutAllCache(spqp.UserId, allCache)
  281. }
  282. }
  283. length := len(allCache.Datas)
  284. if end > length {
  285. end = length
  286. }
  287. if start < length {
  288. result = allCache.Datas[start:end]
  289. }
  290. total = allCache.Count
  291. } else {
  292. logx.Info("a4")
  293. result, total = s.getDatasFromMysql(spqp, starttime, endtime, spqp.PageSize, true)
  294. }
  295. logx.Info("-------------------------------------------------", len(result))
  296. log.Println(spqp.IsEmpty() && (spqp.PageNum-1)*spqp.PageSize <= 250)
  297. if result == nil {
  298. result = []*bxsubscribe.SubscribeInfo{}
  299. }
  300. hasNextPage = len(result) >= spqp.PageSize
  301. return
  302. }
  303. func (s *subscribePush) getDatasFromMysql(spqp *SubPushQueryParam, starttime, endtime int64, size int, isLimit bool) (result []*bxsubscribe.SubscribeInfo, count int64) {
  304. querys := []string{}
  305. userStr := " "
  306. leftJoinStr := " "
  307. var (
  308. searchSql, findSql string
  309. )
  310. querys = append(querys, " 1=1 ")
  311. if spqp.SelectInfoIds != nil && len(spqp.SelectInfoIds) > 0 {
  312. 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, "','")))
  313. logx.Info("searchSql", searchSql)
  314. //查询总数
  315. count = spqp.BaseServiceMysql.CountBySql(fmt.Sprintf("select count(a.id)" + searchSql))
  316. findSql = "select a.id,a.date,a.infoid,a.isvisit,a.matchkeys,a.type,b.isvalidfile as attachment_count"
  317. findSql = "select a.id,a.date,a.infoid,a.isvisit,a.matchkeys,a.type,b.isvalidfile as attachment_count"
  318. } else {
  319. if spqp.IsEnt {
  320. if spqp.BuySubject == 1 {
  321. userStr = fmt.Sprintf(" a.entid='%s' and (a.source =2 or a.source =1) ", spqp.EntId)
  322. } else {
  323. userStr = fmt.Sprintf(" a.entid='%s' ", spqp.EntId)
  324. }
  325. } else {
  326. userStr = fmt.Sprintf(" a.userid='%s'", common.If(s.ModuleFlag == "eType", spqp.EntUserId, common.InterfaceToStr(spqp.NewUserId)))
  327. }
  328. codeMap, err := IC.CodeLib.CodeTransformation(context.Background(), &codeservice.Request{})
  329. if codeMap.Data == nil || err != nil {
  330. logx.Error("代码表获取失败")
  331. return result, count
  332. }
  333. //时间
  334. logx.Info("starttime,endtime", starttime, endtime)
  335. if starttime > 0 && endtime > 0 {
  336. userStr += fmt.Sprintf(" and a.date>=%d and date<=%d", starttime, endtime)
  337. } else if starttime > 0 && endtime == 0 {
  338. userStr += fmt.Sprintf(" and a.date>=%d", starttime)
  339. } else if starttime == 0 && endtime > 0 {
  340. userStr += fmt.Sprintf(" and a.date<=%d", endtime)
  341. }
  342. if spqp.Area != "" || spqp.City != "" {
  343. var sqlAreaCity = ""
  344. //城市
  345. city := []string{}
  346. for _, v := range strings.Split(spqp.City, ",") {
  347. if codeMap.Data.City[v] != "" {
  348. city = append(city, fmt.Sprint(codeMap.Data.City[v]))
  349. } else {
  350. city = append(city, "-1")
  351. }
  352. }
  353. if len(city) == 1 {
  354. city = append(city, "9999")
  355. }
  356. if len(city) > 0 {
  357. sqlAreaCity = fmt.Sprintf("b.city_code in (%s)", strings.Join(city, ","))
  358. }
  359. //区域
  360. var sqlArea = ""
  361. area := []string{}
  362. for _, v := range strings.Split(spqp.Area, ",") {
  363. if codeMap.Data.Area[v] != "" {
  364. area = append(area, fmt.Sprint(codeMap.Data.Area[v]))
  365. } else {
  366. area = append(area, "-1")
  367. }
  368. }
  369. if len(area) == 1 {
  370. area = append(area, "9999")
  371. }
  372. if len(area) > 0 {
  373. sqlArea = fmt.Sprintf("b.area_code in (%s)", strings.Join(area, ","))
  374. }
  375. if sqlAreaCity != "" && sqlArea != "" {
  376. sqlAreaCity = "( " + sqlAreaCity + " or " + sqlArea + " )"
  377. } else if sqlAreaCity == "" && sqlArea != "" {
  378. sqlAreaCity = sqlArea
  379. }
  380. if sqlAreaCity != "" {
  381. querys = append(querys, sqlAreaCity)
  382. }
  383. }
  384. //采购单位行业
  385. if spqp.Buyerclass != "" {
  386. buyerclass := []string{}
  387. for _, v := range strings.Split(spqp.Buyerclass, ",") {
  388. if codeMap.Data.Buyerclass[v] != "" {
  389. buyerclass = append(buyerclass, fmt.Sprint(codeMap.Data.Buyerclass[v]))
  390. }
  391. }
  392. if len(buyerclass) == 1 {
  393. buyerclass = append(buyerclass, "9999")
  394. }
  395. if len(buyerclass) > 0 {
  396. querys = append(querys, fmt.Sprintf("b.buyerclass_code in (%s)", strings.Join(buyerclass, ",")))
  397. }
  398. }
  399. //信息类型
  400. if spqp.Subtype != "" {
  401. subtype := []string{}
  402. for _, v := range strings.Split(spqp.Subtype, ",") {
  403. if codeMap.Data.Subtype[v] != "" {
  404. subtype = append(subtype, fmt.Sprint(codeMap.Data.Subtype[v]))
  405. }
  406. }
  407. if len(subtype) == 1 {
  408. subtype = append(subtype, "9999")
  409. }
  410. if len(subtype) > 0 {
  411. querys = append(querys, fmt.Sprintf("b.subtype_code in (%s)", strings.Join(subtype, ",")))
  412. }
  413. }
  414. //信息行业
  415. if spqp.Subscopeclass != "" {
  416. find_in_set := []string{}
  417. for _, v := range strings.Split(spqp.Subscopeclass, ",") {
  418. if codeMap.Data.Subscopeclass[v] != "" {
  419. find_in_set = append(find_in_set, codeMap.Data.Subscopeclass[v])
  420. }
  421. }
  422. if len(find_in_set) > 0 {
  423. leftJoinStr = fmt.Sprintf(" STRAIGHT_JOIN %s t on t.infoid = b.infoid and t.labelcode=2 ", BidTags)
  424. querys = append(querys, fmt.Sprintf(" t.labelvalues in (%s)", strings.Join(find_in_set, ",")))
  425. }
  426. }
  427. //关键词
  428. if spqp.Key != "" {
  429. find_in_set := []string{}
  430. for _, v := range strings.Split(spqp.Key, ",") {
  431. find_in_set = append(find_in_set, fmt.Sprintf("find_in_set('%s',replace(replace(a.matchkeys,'+',','),' ',','))", v))
  432. }
  433. if len(find_in_set) == 1 {
  434. querys = append(querys, find_in_set[0])
  435. } else if len(find_in_set) > 1 {
  436. querys = append(querys, fmt.Sprintf("(%s)", strings.Join(find_in_set, " or ")))
  437. }
  438. }
  439. //价格- 预算和中标金额
  440. if spqp.Price != "" && strings.Contains(spqp.Price, "-") {
  441. minPriceStr, maxPriceStr := strings.Split(spqp.Price, "-")[0], strings.Split(spqp.Price, "-")[1]
  442. minPrice := common.Int64All(common.Float64All(minPriceStr) * 10000) //换成元
  443. maxPrice := common.Int64All(common.Float64All(maxPriceStr) * 10000) //换成元
  444. if minPriceStr != "" && maxPriceStr != "" {
  445. 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))
  446. } else if minPriceStr != "" {
  447. querys = append(querys, fmt.Sprintf("(b.bidamount>=%d or (b.budget>=%d and b.bidamount is null))", minPrice, minPrice))
  448. } else if maxPriceStr != "" {
  449. querys = append(querys, fmt.Sprintf("(b.bidamount<=%d or (b.budget<=%d and b.bidamount is null))", maxPrice, maxPrice))
  450. }
  451. }
  452. //附件
  453. if spqp.FileExists != "" {
  454. if spqp.FileExists == "1" {
  455. querys = append(querys, fmt.Sprintf("b.isvalidfile =1 "))
  456. } else if spqp.FileExists == "-1" {
  457. querys = append(querys, fmt.Sprintf("b.isvalidfile =0 "))
  458. }
  459. }
  460. searchSql = fmt.Sprintf(" from %s a STRAIGHT_JOIN %s b ON %s and a.infoid = b.infoid %s where %s"+
  461. " order by a.id desc", aboutDbMsg[s.ModuleFlag].MysqlTable, Baseinfo, userStr, leftJoinStr, strings.Join(querys, " and "))
  462. logx.Info("searchSql", searchSql)
  463. //查询总数
  464. logx.Info(fmt.Sprintf("select count(a.id) " + searchSql))
  465. count = spqp.BaseServiceMysql.CountBySql(fmt.Sprintf("select /*+ HASH_JOIN(a,b)*/ count(a.id) " + searchSql))
  466. logx.Info("count:", count, "---", s.ModuleFlag)
  467. findSql = "select a.id,a.date,a.infoid,a.isvisit,a.matchkeys,a.type,b.isvalidfile as attachment_count"
  468. if s.ModuleFlag == "eType" {
  469. findSql += ", IF(a.source is NULL,1,a.source) as source "
  470. }
  471. }
  472. if s.ModuleFlag != MemberFlag && s.ModuleFlag != EntnicheFlag {
  473. findSql += ",a.isvip"
  474. }
  475. findSql += searchSql
  476. if isLimit {
  477. findSql += fmt.Sprintf(" limit %d,%d", (spqp.PageNum-1)*size, size)
  478. }
  479. logx.Info("findSql", findSql)
  480. logx.Info(spqp.NewUserId, "subscribePush query sql:", findSql)
  481. list := spqp.BaseServiceMysql.SelectBySql(findSql)
  482. if list != nil && len(*list) > 0 {
  483. pushCas := s.GetJyPushs(*list)
  484. if !spqp.Export {
  485. result = s.GetInfoByIds(spqp.Mgo_bidding, spqp.Bidding, spqp.Bidding_back, pushCas)
  486. } else {
  487. result = s.GetOnlyExportInfo(pushCas)
  488. }
  489. } else {
  490. result = []*bxsubscribe.SubscribeInfo{}
  491. }
  492. logx.Info("result", result)
  493. return
  494. }
  495. // GetOnlyInfoId 获取信息id
  496. func (s *subscribePush) GetOnlyExportInfo(pushCas []*PushCa) []*bxsubscribe.SubscribeInfo {
  497. array := make([]*bxsubscribe.SubscribeInfo, len(pushCas))
  498. for k, v := range pushCas {
  499. array[k] = &bxsubscribe.SubscribeInfo{XId: encrypt.EncodeArticleId2ByCheck(v.InfoId), MatchKeys: v.Keys}
  500. }
  501. return array
  502. }
  503. // 根据id取内容
  504. func (s *subscribePush) GetInfoByIds(Mgo_bidding mongodb.MongodbSim, bidding, bidding_back string, pushCas []*PushCa) []*bxsubscribe.SubscribeInfo {
  505. array := make([]*bxsubscribe.SubscribeInfo, len(pushCas))
  506. if len(pushCas) == 0 {
  507. return array
  508. }
  509. m := map[string]bool{}
  510. ids := []string{}
  511. for _, v := range pushCas {
  512. if m[v.InfoId] {
  513. continue
  514. }
  515. m[v.InfoId] = true
  516. ids = append(ids, v.InfoId)
  517. }
  518. infos := map[string]map[string]interface{}{}
  519. //redis
  520. es_ids := []string{}
  521. for _, v := range ids {
  522. //剑鱼程序未找到赋值 位置;猜测在推送程序中
  523. info_i := redis.Get("pushcache_1", fmt.Sprintf("info_%s", v))
  524. if info_i != nil {
  525. info_m, _ := info_i.(map[string]interface{})
  526. info_m["_id"] = v
  527. infos[v] = info_m
  528. } else {
  529. es_ids = append(es_ids, v)
  530. }
  531. }
  532. //elasticsearch
  533. if len(es_ids) > 0 {
  534. list := elastic.Get("bidding", "bidding", fmt.Sprintf(query, strings.Join(es_ids, `","`), len(es_ids)))
  535. if list != nil {
  536. for _, v := range *list {
  537. _id := common.ObjToString(v["_id"])
  538. infos[_id] = v
  539. }
  540. }
  541. }
  542. //mongodb bidding
  543. mgo_ids := []primitive.ObjectID{}
  544. for _, v := range es_ids {
  545. if infos[v] == nil {
  546. _id, _ := primitive.ObjectIDFromHex(v)
  547. mgo_ids = append(mgo_ids, _id)
  548. }
  549. }
  550. if len(mgo_ids) > 0 {
  551. list, ok := Mgo_bidding.Find(bidding, map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_ids}}, nil, mongodb_fields, false, -1, -1)
  552. if ok && *list != nil {
  553. for _, v := range *list {
  554. _id := mongodb.BsonIdToSId(v["_id"])
  555. v["_id"] = _id
  556. infos[_id] = v
  557. }
  558. }
  559. }
  560. //mongodb bidding_back
  561. mgo_back_ids := []primitive.ObjectID{}
  562. for _, v := range mgo_ids {
  563. if infos[mongodb.BsonIdToSId(v)] == nil {
  564. mgo_back_ids = append(mgo_back_ids, v)
  565. }
  566. }
  567. if len(mgo_back_ids) > 0 {
  568. list, ok := Mgo_bidding.Find(bidding_back, map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_back_ids}}, nil, mongodb_fields, false, -1, -1)
  569. if ok && *list != nil {
  570. for _, v := range *list {
  571. _id := mongodb.BsonIdToSId(v["_id"])
  572. v["_id"] = _id
  573. infos[_id] = v
  574. }
  575. }
  576. }
  577. for k, v := range pushCas {
  578. info := infos[v.InfoId]
  579. info["Visit"] = v.Visit
  580. if info == nil {
  581. info = map[string]interface{}{}
  582. }
  583. array[k] = s.InfoFormat(v, &info)
  584. }
  585. return array
  586. }
  587. // 获取历史推送
  588. func (s *subscribePush) GetJyPushs(datas []map[string]interface{}) (pushCas []*PushCa) {
  589. pushCas = []*PushCa{}
  590. for _, v := range datas {
  591. keys := []string{}
  592. if matchkeys := common.ObjToString(v["matchkeys"]); matchkeys != "" {
  593. keys = strings.Split(matchkeys, " ")
  594. }
  595. pushCas = append(pushCas, &PushCa{
  596. Date: common.Int64All(v["date"]),
  597. InfoId: common.ObjToString(v["infoid"]),
  598. Visit: common.IntAll(v["isvisit"]),
  599. Index: common.Int64All(v["id"]),
  600. Keys: keys,
  601. Type: common.IntAll(v["type"]),
  602. Isvip: common.IntAll(v["isvip"]),
  603. FileExists: common.IntAll(v["attachment_count"]) > 0,
  604. Source: common.Int64All(v["source"]),
  605. })
  606. }
  607. return
  608. }
  609. // 查看全部列表缓存
  610. func (s *subscribePush) PutAllCache(userId string, datas *SubPush) {
  611. log.Println(s.allKey(userId), datas, oneDay)
  612. redis.Put("pushcache_2_a", s.allKey(userId), datas, oneDay)
  613. }
  614. func (s *subscribePush) GetAllCache(userId string) (*SubPush, error) {
  615. return s.GetCache("pushcache_2_a", s.allKey(userId))
  616. }
  617. func (s *subscribePush) GetCache(code, key string) (*SubPush, error) {
  618. pc_a, err := redis.GetNewBytes(code, key)
  619. if err != nil {
  620. return nil, err
  621. }
  622. if pc_a == nil {
  623. return nil, nil
  624. }
  625. var p *SubPush
  626. if err := json.Unmarshal(*pc_a, &p); err != nil {
  627. return nil, err
  628. }
  629. logx.Info("redis数据", p)
  630. return p, nil
  631. }
  632. // 是否收藏
  633. func (s *subscribePush) MakeCollection(userId string, list []*bxsubscribe.SubscribeInfo) {
  634. if list == nil || len(list) == 0 {
  635. return
  636. }
  637. param := []interface{}{userId}
  638. wh := []string{}
  639. for _, v := range list {
  640. array := encrypt.DecodeArticleId2ByCheck(v.XId)
  641. if len(array) == 1 && array[0] != "" {
  642. param = append(param, array[0])
  643. wh = append(wh, "?")
  644. }
  645. }
  646. if len(wh) > 0 {
  647. result := IC.MainMysql.SelectBySql(`select bid from bdcollection where userid=? and bid in (`+strings.Join(wh, ",")+`)`, param...)
  648. bid_map := map[string]bool{}
  649. if result != nil {
  650. for _, v := range *result {
  651. bid_map[encrypt.EncodeArticleId2ByCheck(common.ObjToString(v["bid"]))] = true
  652. }
  653. }
  654. for _, v := range list {
  655. if bid_map[v.XId] {
  656. v.Collection = 1
  657. }
  658. }
  659. }
  660. }
  661. // 仅移动端首页使用,历史推送7天信息
  662. func (s *subscribePush) sevenDayKey(userId string) string {
  663. return fmt.Sprintf("7day_subpush_%s", userId)
  664. }
  665. func (s *subscribePush) PutSevenDayCache(userId string, datas []*bxsubscribe.SubscribeInfo) {
  666. redis.Put("pushcache_2_a", s.sevenDayKey(userId), SubPush{Datas: datas}, 7*24*60*60)
  667. }
  668. // 从pushcache_2_a中取
  669. func (s *subscribePush) GetSevenDayCache(userId string) ([]*bxsubscribe.SubscribeInfo, error) {
  670. allPush, _ := s.GetCache("pushcache_2_a", s.sevenDayKey(userId))
  671. if allPush != nil && allPush.Datas != nil && len(allPush.Datas) > 0 {
  672. return allPush.Datas, nil
  673. }
  674. return nil, nil
  675. }
  676. // 历史推送记录中单条信息格式化
  677. func InfoFormats(info map[string]interface{}, tmp map[string]interface{}) map[string]interface{} {
  678. area := common.ObjToString(info["area"])
  679. if area == "A" {
  680. area = "全国"
  681. }
  682. industry := common.ObjToString(info["s_subscopeclass"])
  683. scs := strings.Split(industry, ",")
  684. if len(scs) > 0 {
  685. industry = scs[0]
  686. if industry != "" {
  687. iss := strings.Split(industry, "_")
  688. if len(iss) > 0 {
  689. industry = iss[0]
  690. }
  691. }
  692. }
  693. infotype := common.ObjToString(info["subtype"])
  694. if infotype == "" {
  695. infotype = common.ObjToString(info["toptype"])
  696. }
  697. if infotype == "" {
  698. infotype = common.ObjToString(info["type"])
  699. if infotype == "tender" {
  700. infotype = "招标"
  701. } else if infotype == "bid" {
  702. infotype = "中标"
  703. }
  704. }
  705. info["type"] = infotype
  706. return info
  707. }
  708. // UpdateUserPushUnread 更新app未读标识为已读
  709. func UpdateUserPushUnread(userid string, vt string) {
  710. if vt == MemberFlag {
  711. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_member_apppushunread": 0}})
  712. } else if vt == EntnicheFlag {
  713. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_entniche_apppushunread": 0}})
  714. } else {
  715. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_apppushunread": 0}})
  716. }
  717. }
  718. func (s *subscribePush) SetRead(newUserId, id int64, userId, entUserId, entId string, isEnt bool) error {
  719. if id <= 0 {
  720. return nil
  721. }
  722. if newUserId == 0 {
  723. return nil
  724. }
  725. if isEnt {
  726. IC.BaseServiceMysql.UpdateOrDeleteBySql(fmt.Sprintf("update %s set isvisit=1 where entid=? and id=?", aboutDbMsg[s.ModuleFlag].MysqlTable), entId, id)
  727. } else {
  728. if s.ModuleFlag == "eType" {
  729. //商机管理
  730. IC.BaseServiceMysql.UpdateOrDeleteBySql(fmt.Sprintf("update %s set isvisit=1 where userid=? and id=?", aboutDbMsg[s.ModuleFlag].MysqlTable), entUserId, id)
  731. } else {
  732. //其他
  733. IC.BaseServiceMysql.UpdateOrDeleteBySql(fmt.Sprintf("update %s set isvisit=1 where userid=? and id=?", aboutDbMsg[s.ModuleFlag].MysqlTable), newUserId, id)
  734. }
  735. }
  736. if !isEnt {
  737. todaySubPush, err := s.GetTodayCache(userId)
  738. //当天数据处理
  739. if err == nil && todaySubPush != nil {
  740. for _, v := range todaySubPush.Datas {
  741. if v.CaIndex == id {
  742. v.CaIsvisit = 1
  743. break
  744. }
  745. }
  746. s.PutTodayCache(userId, todaySubPush)
  747. }
  748. //全部数据处理
  749. allSubPush, err := s.GetAllCache(userId)
  750. if err == nil && allSubPush != nil {
  751. for _, v := range allSubPush.Datas {
  752. if v.CaIndex == id {
  753. v.CaIsvisit = 1
  754. break
  755. }
  756. }
  757. s.PutAllCache(userId, allSubPush)
  758. }
  759. }
  760. return nil
  761. }
  762. // 获取用户信息
  763. func (s *subscribePush) UserInfo(userId string) (*map[string]interface{}, int64) {
  764. 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}`)
  765. if !ok || user == nil {
  766. return nil, 0
  767. }
  768. return user, common.Int64All((*user)["l_firstpushtime"])
  769. }
  770. // 是否有订阅词
  771. func GetKeySet(t string, u *map[string]interface{}, data []string) (bool, []string) {
  772. var industry_ = []string{}
  773. if u != nil {
  774. if t == SubFreeFlag {
  775. o_jy, _ := (*u)["o_jy"].(map[string]interface{})
  776. a_key, _ := o_jy["a_key"].([]interface{})
  777. return len(a_key) > 0, industry_
  778. } else {
  779. var obj map[string]interface{}
  780. if t == SubVipFlag {
  781. obj, _ = (*u)["o_vipjy"].(map[string]interface{})
  782. } else if t == MemberFlag {
  783. obj, _ = (*u)["o_member_jy"].(map[string]interface{})
  784. } else if t == EntnicheFlag {
  785. if len(data) > 0 {
  786. return true, data
  787. } else {
  788. return false, data
  789. }
  790. }
  791. if obj != nil {
  792. if buyerclassObj, ok := obj["a_buyerclass"].([]interface{}); ok {
  793. industry_ = common.ObjArrToStringArr(buyerclassObj)
  794. }
  795. itmes, _ := obj["a_items"].([]interface{})
  796. for _, v := range itmes {
  797. item, _ := v.(map[string]interface{})
  798. keys, _ := item["a_key"].([]interface{})
  799. if len(keys) > 0 {
  800. return true, industry_
  801. }
  802. }
  803. }
  804. }
  805. }
  806. return false, industry_
  807. }
  808. const (
  809. INDEX = "bidding"
  810. TYPE = "bidding"
  811. bidField = `"_id","title","publishtime","toptype","subtype","type","area","city","s_subscopeclass","buyerclass","budget","bidamount","filetext","spidercode","site"`
  812. bidTime = `{"range":{"publishtime":{"gt":%d}}}`
  813. bidSort = `{"publishtime":"desc"}`
  814. findfields = `"title"`
  815. )
  816. // 首次访问推送页面 默认生成推送数据
  817. // 默认匹配es 7天内数据
  818. func (s *subscribePush) DefaultDatas(spqp *SubPushQueryParam) (hasNextPage bool, total int64, result []*bxsubscribe.SubscribeInfo) {
  819. if spqp.UserId == "" {
  820. return false, 0, nil
  821. }
  822. t1 := time.Now()
  823. log.Println("userId:", spqp.UserId)
  824. log.Println("newUserId:", spqp.NewUserId)
  825. //用户信息
  826. bsp := s.getUserInfo(spqp)
  827. logx.Info("获取用户信息耗时:", time.Since(t1))
  828. t2 := time.Now()
  829. if len(bsp.Keyword) > 0 {
  830. logx.Info(time.Since(t1), "--bsp:", bsp)
  831. //获取查询语句
  832. qstr := s.getDefaultDatasSQL(bsp)
  833. list := elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSort, bidField, 0, bsp.Size, 0, false)
  834. //logx.Info(time.Since(t1), "count:", len(*list))
  835. if list != nil && len(*list) > 0 {
  836. total = int64(len(*list))
  837. result = s.listManager(spqp, *list, bsp.Keyword)
  838. if len(result) > pageSize {
  839. result = result[:pageSize]
  840. hasNextPage = true
  841. }
  842. }
  843. }
  844. logx.Info("请求耗时:", time.Since(t2))
  845. return
  846. }
  847. // 保存推送表
  848. func (s *subscribePush) listManager(spqp *SubPushQueryParam, list []map[string]interface{}, keyword []ViewKeyWord) (resultList []*bxsubscribe.SubscribeInfo) {
  849. t2 := time.Now()
  850. now := time.Now().Unix()
  851. length := len(list)
  852. resultList = make([]*bxsubscribe.SubscribeInfo, length)
  853. pushInsert := []interface{}{}
  854. for i := length - 1; i >= 0; i-- {
  855. v := list[i]
  856. title := strings.Replace(common.ObjToString(v["title"]), "\n", "", -1)
  857. infoid := common.InterfaceToStr(v["_id"])
  858. matchkeys := getKeys(title, keyword)
  859. matchkey := strings.Join(matchkeys, " ")
  860. redisKey := fmt.Sprintf("pushinfo_%s_%s", spqp.UserId, common.ObjToString(v["_id"]))
  861. entid := spqp.EntId
  862. entUserId := spqp.EntUserId
  863. deptid := spqp.DeptId
  864. switch s.ModuleFlag {
  865. case "eType":
  866. pushInsert = append(pushInsert, entid, deptid, entUserId, common.InterfaceToStr(infoid), matchkey, now, 1)
  867. case "mType":
  868. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId), common.InterfaceToStr(infoid), matchkey, now)
  869. case "vType":
  870. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId), common.InterfaceToStr(infoid), matchkey, now, 1)
  871. case "fType":
  872. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId), common.InterfaceToStr(infoid), matchkey, now, 0)
  873. }
  874. redis.Put("pushcache_2_a", redisKey, 1, 86400)
  875. resultList[i] = s.InfoFormat(&PushCa{
  876. InfoId: infoid,
  877. Date: time.Now().Unix(),
  878. Keys: matchkeys,
  879. FileExists: v["filetext"] != nil,
  880. }, &v)
  881. }
  882. id := int64(0)
  883. switch s.ModuleFlag {
  884. case "eType":
  885. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, ennicheInsertCollKey, pushInsert)
  886. case "mType":
  887. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, memberInsertCollKey, pushInsert)
  888. default:
  889. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, subscribeInsertCollKey, pushInsert)
  890. }
  891. for i := length - 1; i >= 0; i-- {
  892. resultList[i].CaIndex = id
  893. id++
  894. }
  895. log.Println("数据处理耗时:", time.Since(t2))
  896. return
  897. }
  898. // 获取匹配得关键词
  899. func getKeys(title string, keywords []ViewKeyWord) (str []string) {
  900. if len(keywords) > 0 {
  901. L:
  902. for _, v := range keywords {
  903. for _, vk := range v.Keyword {
  904. if strings.Contains(title, vk) {
  905. str = append(str, v.Keyword...)
  906. break L
  907. }
  908. }
  909. for _, va := range v.Appended {
  910. if strings.Contains(title, va) {
  911. str = append(str, v.Appended...)
  912. break L
  913. }
  914. }
  915. }
  916. }
  917. return
  918. }
  919. // 获取查询语句
  920. func (s *subscribePush) getDefaultDatasSQL(bsp *ViewCondition) (str string) {
  921. query := `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match": %d}}}`
  922. query_bool_should := `{"bool":{"should":[%s],"minimum_should_match": 1}}`
  923. multi_match := `{"multi_match": {"query": %s,"type": "phrase", "fields": [%s]}}`
  924. query_bool_must_and := `{"bool":{"must":[%s]%s}}`
  925. bools := []string{}
  926. musts := []string{}
  927. //发布时间最新7天(正式环境需要修改)
  928. musts = append(musts, fmt.Sprintf(bidTime, time.Now().AddDate(0, 0, -7).Unix()))
  929. //省份
  930. areaCity := []string{}
  931. if len(bsp.Area) > 0 {
  932. areaquery := `{"terms":{"area":[`
  933. for k, v := range bsp.Area {
  934. if k > 0 {
  935. areaquery += `,`
  936. }
  937. areaquery += `"` + v + `"`
  938. }
  939. areaquery += `]}}`
  940. areaCity = append(areaCity, areaquery)
  941. }
  942. //城市
  943. if len(bsp.City) > 0 {
  944. areaquery := `{"terms":{"city":[`
  945. for k, v := range bsp.City {
  946. if k > 0 {
  947. areaquery += `,`
  948. }
  949. areaquery += `"` + v + `"`
  950. }
  951. areaquery += `]}}`
  952. areaCity = append(areaCity, areaquery)
  953. }
  954. if len(areaCity) > 0 {
  955. musts = append(musts, fmt.Sprintf(query_bool_should, strings.Join(areaCity, ",")))
  956. }
  957. if len(bsp.Subtype) > 0 {
  958. subquery := `{"terms":{"subtype":[`
  959. for k, v := range bsp.Subtype {
  960. if k > 0 {
  961. subquery += `,`
  962. }
  963. subquery += `"` + v + `"`
  964. }
  965. subquery += `]}}`
  966. musts = append(musts, subquery)
  967. }
  968. if len(bsp.Buyerclass) > 0 {
  969. Buyerclass := `{"terms":{"buyerclass":[`
  970. for k, v := range bsp.Buyerclass {
  971. if k > 0 {
  972. Buyerclass += `,`
  973. }
  974. Buyerclass += `"` + v + `"`
  975. }
  976. Buyerclass += `]}}`
  977. musts = append(musts, Buyerclass)
  978. }
  979. boolsNum := 0 //should
  980. if len(bsp.Keyword) > 0 {
  981. boolsNum = 1
  982. if bsp.SelectType == "" || bsp.SelectType == "2" {
  983. bsp.SelectType = "detail\", \"title"
  984. } else {
  985. bsp.SelectType = "title"
  986. }
  987. multi_match = fmt.Sprintf(multi_match, "%s", "\""+bsp.SelectType+"\"")
  988. for _, v := range bsp.Keyword {
  989. shoulds := []string{}
  990. must_not := []string{}
  991. //附加词
  992. for _, vv := range v.Keyword {
  993. vv = strings.TrimSpace(vv)
  994. if vv == "" {
  995. continue
  996. }
  997. shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
  998. }
  999. for _, vv := range v.Appended {
  1000. vv = strings.TrimSpace(vv)
  1001. if vv == "" {
  1002. continue
  1003. }
  1004. shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
  1005. }
  1006. //排除词
  1007. for _, vv := range v.Exclude {
  1008. vv = strings.TrimSpace(vv)
  1009. if vv == "" {
  1010. continue
  1011. }
  1012. must_not = append(must_not, fmt.Sprintf(multi_match, "\""+vv+"\""))
  1013. }
  1014. //添加
  1015. if len(shoulds) > 0 {
  1016. notStr := ""
  1017. if len(must_not) > 0 {
  1018. notStr = fmt.Sprintf(`,"must_not":[%s]`, strings.Join(must_not, ","))
  1019. }
  1020. bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(shoulds, ","), notStr))
  1021. }
  1022. }
  1023. }
  1024. qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum)
  1025. logx.Info("----", qstr)
  1026. return qstr
  1027. }
  1028. /*已选条件--关键词*/
  1029. type ViewKeyWord struct {
  1030. Keyword []string `json:"key"` //关键词
  1031. Appended []string `json:"appendkey"` //附加词
  1032. Exclude []string `json:"notkey"` //排除词
  1033. MatchWay int `json:"matchway"` //匹配模式
  1034. }
  1035. /*已选条件*/
  1036. type ViewCondition struct {
  1037. Area []string //地区-省份
  1038. City []string //地区-城市
  1039. Buyerclass []string //采购行业
  1040. Keyword []ViewKeyWord //关键词
  1041. SelectType string //筛选(正文 or 标题)
  1042. Subtype []string //信息类型
  1043. Size int //数量
  1044. }
  1045. // 获取用户信息
  1046. func (s *subscribePush) getUserInfo(spqp *SubPushQueryParam) (vc *ViewCondition) {
  1047. var isPayBool = false
  1048. var tmpInfo = struct {
  1049. Items []interface{}
  1050. BuyerClass []interface{}
  1051. SubType []interface{}
  1052. Area map[string]interface{}
  1053. SelectType string
  1054. }{}
  1055. switch s.ModuleFlag {
  1056. case "mType":
  1057. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_member_jy":1,"i_member_status":1}`)
  1058. if !ok || userMap == nil || len(*userMap) == 0 {
  1059. return &ViewCondition{}
  1060. }
  1061. //大会员
  1062. if common.IntAll((*userMap)["i_member_status"]) > 0 {
  1063. isPayBool = true
  1064. o_member_jy, _ := (*userMap)["o_member_jy"].(map[string]interface{})
  1065. tmpInfo.Items, _ = o_member_jy["a_items"].([]interface{})
  1066. tmpInfo.BuyerClass, _ = o_member_jy["a_buyerclass"].([]interface{})
  1067. tmpInfo.SubType, _ = o_member_jy["a_infotype"].([]interface{})
  1068. tmpInfo.Area, _ = o_member_jy["o_area"].(map[string]interface{})
  1069. }
  1070. case "vType":
  1071. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_vipjy":1,"i_vip_status":1}`)
  1072. if !ok || userMap == nil || len(*userMap) == 0 {
  1073. return &ViewCondition{}
  1074. }
  1075. if common.IntAll((*userMap)["i_vip_status"]) > 0 {
  1076. isPayBool = true
  1077. o_vipjy, _ := (*userMap)["o_vipjy"].(map[string]interface{})
  1078. tmpInfo.Items, _ = o_vipjy["a_items"].([]interface{})
  1079. tmpInfo.BuyerClass, _ = o_vipjy["a_buyerclass"].([]interface{})
  1080. tmpInfo.SubType, _ = o_vipjy["a_infotype"].([]interface{})
  1081. tmpInfo.Area, _ = o_vipjy["o_area"].(map[string]interface{})
  1082. }
  1083. case "eType":
  1084. //商机管理
  1085. entUserId, _ := strconv.Atoi(spqp.EntUserId)
  1086. entId, _ := strconv.Atoi(spqp.EntId)
  1087. entInfo, deptId := (&ms.MatchJob{}).Start(entId, entUserId)
  1088. if entInfo != nil && len(entInfo) > 0 {
  1089. spqp.DeptId = strconv.Itoa(deptId)
  1090. isPayBool = true
  1091. tmpInfo.Items, _ = entInfo["a_items"].([]interface{})
  1092. tmpInfo.BuyerClass, _ = entInfo["a_buyerclass"].([]interface{})
  1093. tmpInfo.SubType, _ = entInfo["a_infotype"].([]interface{})
  1094. tmpInfo.Area, _ = entInfo["o_area"].(map[string]interface{})
  1095. }
  1096. default:
  1097. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_jy":1}`)
  1098. if !ok || userMap == nil || len(*userMap) == 0 {
  1099. return &ViewCondition{}
  1100. }
  1101. o_jy, _ := (*userMap)["o_jy"].(map[string]interface{})
  1102. if o_jy["a_key"] != nil {
  1103. tmpInfo.Items, _ = o_jy["a_key"].([]interface{})
  1104. //信息类型
  1105. tmpInfo.SubType, _ = o_jy["a_infotype"].([]interface{})
  1106. //省份
  1107. tmpInfo.Area, _ = o_jy["o_area"].(map[string]interface{})
  1108. if common.IntAllDef(o_jy["i_ppstatus"], 0) == 1 && o_jy["o_area_p"] != nil {
  1109. tmpInfo.Area, _ = o_jy["o_area_p"].(map[string]interface{})
  1110. }
  1111. }
  1112. }
  1113. vc = &ViewCondition{
  1114. Buyerclass: common.ObjArrToStringArr(tmpInfo.BuyerClass),
  1115. Subtype: common.ObjArrToStringArr(tmpInfo.SubType),
  1116. Area: getStringArrFromDbResult(tmpInfo.Area, 1),
  1117. City: getStringArrFromDbResult(tmpInfo.Area, 2),
  1118. SelectType: "1",
  1119. }
  1120. //付费用户
  1121. if isPayBool {
  1122. vc.Size = IC.C.DefaulCount.Pay
  1123. vc.Keyword = getKeyWordArrFromDbResult(tmpInfo.Items, "", -1)
  1124. } else {
  1125. vc.Size = IC.C.DefaulCount.Free
  1126. vc.Keyword = getKeyWordArrFromDbResultByFree(tmpInfo.Items, "", -1)
  1127. //vc.Keyword = getKeyWordArrFromDbResult(tmpInfo.Items, "", -1)
  1128. }
  1129. return
  1130. }
  1131. // 关键词 附加词 排除词
  1132. func getKeyWordArrFromDbResult(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
  1133. if a_items == nil {
  1134. return
  1135. }
  1136. for _, v := range a_items {
  1137. vm, _ := v.(map[string]interface{})
  1138. if item != "" && index >= 0 && item != common.ObjToString(vm["s_item"]) {
  1139. continue
  1140. }
  1141. kwsArr := vm["a_key"]
  1142. for i, k := range kwsArr.([]interface{}) {
  1143. if item != "" && index >= 0 && i != index {
  1144. continue
  1145. }
  1146. kw := ViewKeyWord{}
  1147. b, e := json.Marshal(k)
  1148. if e != nil {
  1149. log.Println(e.Error())
  1150. }
  1151. json.Unmarshal(b, &kw)
  1152. if kw.MatchWay == 1 {
  1153. for _, kk := range kw.Keyword {
  1154. arr = append(arr, ViewKeyWord{
  1155. Keyword: []string{kk},
  1156. Exclude: kw.Exclude,
  1157. })
  1158. }
  1159. for _, kk := range kw.Appended {
  1160. arr = append(arr, ViewKeyWord{
  1161. Keyword: []string{kk},
  1162. Exclude: kw.Exclude,
  1163. })
  1164. }
  1165. } else {
  1166. arr = append(arr, kw)
  1167. }
  1168. }
  1169. }
  1170. return
  1171. }
  1172. // //关键词 附加词 排除词 省份订阅包 - 普通用户
  1173. func getKeyWordArrFromDbResultByFree(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
  1174. if a_items == nil {
  1175. return
  1176. }
  1177. for _, v := range a_items {
  1178. kw := ViewKeyWord{}
  1179. b, e := json.Marshal(v)
  1180. if e != nil {
  1181. log.Println(e.Error())
  1182. }
  1183. json.Unmarshal(b, &kw)
  1184. if kw.MatchWay == 1 {
  1185. for _, kk := range kw.Keyword {
  1186. arr = append(arr, ViewKeyWord{
  1187. Keyword: []string{kk},
  1188. Exclude: kw.Exclude,
  1189. })
  1190. }
  1191. for _, kk := range kw.Appended {
  1192. arr = append(arr, ViewKeyWord{
  1193. Keyword: []string{kk},
  1194. Exclude: kw.Exclude,
  1195. })
  1196. }
  1197. } else {
  1198. arr = append(arr, kw)
  1199. }
  1200. }
  1201. return
  1202. }
  1203. // 地区格式化
  1204. func getStringArrFromDbResult(area map[string]interface{}, i int) (arr []string) {
  1205. if area == nil {
  1206. return
  1207. }
  1208. var eareArr []string
  1209. var cityArr []string
  1210. for k, v := range area {
  1211. if len(v.([]interface{})) > 0 {
  1212. cityArr = append(cityArr, common.ObjArrToStringArr(v.([]interface{}))...)
  1213. } else {
  1214. eareArr = append(eareArr, k)
  1215. }
  1216. }
  1217. if i == 1 {
  1218. arr = eareArr
  1219. } else {
  1220. arr = cityArr
  1221. }
  1222. return
  1223. }
  1224. // IsInTsGuide 是否进入向导
  1225. func (s *subscribePush) IsInTsGuide(userid string) bool {
  1226. if userid == "" {
  1227. return false
  1228. }
  1229. data, ok := IC.Mgo.FindById("user", userid, `{"o_jy":1,"i_ts_guide":1,"":1,"i_member_status":1,"i_vip_status":1}`)
  1230. if ok {
  1231. //付费用户无免费订阅,不进入订阅向导页面
  1232. if common.IntAll((*data)["i_member_status"]) > 0 || common.IntAll((*data)["i_vip_status"]) > 0 {
  1233. return false
  1234. }
  1235. o_jy, _ := (*data)["o_jy"].(map[string]interface{})
  1236. i_ts_guide := common.IntAll((*data)["i_ts_guide"])
  1237. if i_ts_guide == 2 || (i_ts_guide == 0 && len(o_jy) == 0) {
  1238. return true
  1239. }
  1240. }
  1241. return false
  1242. }
  1243. func (s *subscribePush) Keys(spqp *KeyParam) (result []*bxsubscribe.Items) {
  1244. keyData := map[string][]interface{}{}
  1245. if !spqp.IsEnt {
  1246. //个人关键词查找
  1247. //fType:普通用户;vType:超级订阅用户;mType:大会员用户;eType:商机管理用户
  1248. mData, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_jy":1,"o_vipjy":1,"o_member_jy":1}`)
  1249. if s.ModuleFlag == "vType" {
  1250. //从user表中取 o_vipjy.a_items
  1251. if mData == nil || len(*mData) == 0 || !ok {
  1252. return nil
  1253. }
  1254. o_vipjy := common.ObjToMap((*mData)["o_vipjy"])
  1255. if (*o_vipjy)["a_items"] != nil {
  1256. a_items := common.ObjArrToMapArr((*o_vipjy)["a_items"].([]interface{}))
  1257. for _, v := range a_items {
  1258. if v["a_key"] != nil {
  1259. a_key_arr := v["a_key"].([]interface{})
  1260. keyData[common.InterfaceToStr(v["s_item"])] = a_key_arr
  1261. }
  1262. }
  1263. }
  1264. } else if s.ModuleFlag == "mType" {
  1265. //从user表中取 o_member_jy.a_items
  1266. if mData == nil || len(*mData) == 0 || !ok {
  1267. return nil
  1268. }
  1269. o_memeberjy := common.ObjToMap((*mData)["o_member_jy"])
  1270. if (*o_memeberjy)["o_area"] != nil {
  1271. a_items := common.ObjArrToMapArr((*o_memeberjy)["a_items"].([]interface{}))
  1272. for _, v := range a_items {
  1273. if v["a_key"] != nil {
  1274. a_key_arr := v["a_key"].([]interface{})
  1275. keyData[common.InterfaceToStr(v["s_item"])] = a_key_arr
  1276. }
  1277. }
  1278. }
  1279. } else if s.ModuleFlag == "eType" {
  1280. //entniche_rule表,查询条件:{i_entid:123,i_userid:456},取 o_entniche.a_items
  1281. res_, _ := IC.Mgo.FindOneByField("entniche_rule", map[string]interface{}{
  1282. "i_userid": common.Int64All(spqp.EntUserId),
  1283. "i_entid": common.Int64All(spqp.EntId),
  1284. }, `{"o_entniche":1}`)
  1285. o_entniche := &map[string]interface{}{}
  1286. if res_ != nil {
  1287. o_entniche = common.ObjToMap((*res_)["o_entniche"])
  1288. }
  1289. if (*o_entniche)["a_items"] != nil {
  1290. a_item := common.ObjArrToMapArr((*o_entniche)["a_items"].([]interface{}))
  1291. for _, v := range a_item {
  1292. if v["a_key"] != nil {
  1293. a_key_arr := v["a_key"].([]interface{})
  1294. keyData[common.InterfaceToStr(v["s_item"])] = a_key_arr
  1295. }
  1296. }
  1297. }
  1298. } else {
  1299. if mData == nil || len(*mData) == 0 || !ok {
  1300. return nil
  1301. }
  1302. o_jy, _ := (*mData)["o_jy"].(map[string]interface{})
  1303. //免费用户
  1304. a_key, _ := o_jy["a_key"].([]interface{})
  1305. if len(a_key) > 0 {
  1306. for _, v := range a_key {
  1307. if keyData["其他"] != nil {
  1308. keyData["其他"] = append(keyData["其他"], v)
  1309. } else {
  1310. keyData["其他"] = []interface{}{v}
  1311. }
  1312. }
  1313. }
  1314. }
  1315. log.Println(keyData)
  1316. if (spqp.VipPower == 1 || spqp.MemberPower == 1) || (spqp.UserPower == 1 && spqp.PowerSource == 0) {
  1317. //1、mysql entniche_user_rule表中获取自己的分发规则id
  1318. data := IC.MainMysql.SelectBySql(`select rule_id from entniche_user_rule where user_id =? and dept_id =?`, spqp.EntUserId, spqp.DeptId)
  1319. if data == nil && len(*data) == 0 {
  1320. MapToarr(keyData, s.ModuleFlag)
  1321. }
  1322. ruleId := common.ObjToString((*data)[0]["rule_id"])
  1323. //3、entniche_distribute表,查询条件:{_id:ObjectId(1结果中的分发规则id),i_status:0},取 o_entniche.a_items,这个查到的是分类名称,然后到上面1的结果中获取这个分类下的词
  1324. res, _ := IC.Mgo.FindById("entniche_distribute", ruleId, nil)
  1325. entItem := (*res)["a_items"].([]interface{})
  1326. if (*res)["a_items"] == nil {
  1327. MapToarr(keyData, s.ModuleFlag)
  1328. }
  1329. //2、entniche_rule表, 企业订阅关键词查询条件: {i_entid:123,i_deptid:0},取 o_entniche.a_items
  1330. res_, _ := IC.Mgo.FindOneByField("entniche_rule", map[string]interface{}{
  1331. "i_deptid": int64(0),
  1332. "i_entid": common.Int64All(spqp.EntId),
  1333. }, `{"o_entniche":1}`)
  1334. o_entniche := &map[string]interface{}{}
  1335. if res_ != nil {
  1336. o_entniche = common.ObjToMap((*res_)["o_entniche"])
  1337. }
  1338. entnicheRule := map[string][]interface{}{}
  1339. if (*o_entniche)["a_items"] != nil {
  1340. a_item := common.ObjArrToMapArr((*o_entniche)["a_items"].([]interface{}))
  1341. for _, v := range a_item {
  1342. if v["a_key"] != nil {
  1343. a_key_arr := v["a_key"].([]interface{})
  1344. entnicheRule[common.InterfaceToStr(v["s_item"])] = a_key_arr
  1345. }
  1346. }
  1347. }
  1348. for _, value := range entItem {
  1349. v := common.InterfaceToStr(value)
  1350. if entnicheRule[v] != nil {
  1351. if keyData[v] != nil {
  1352. //第一次搜索存在
  1353. //去重
  1354. keyData[v] = MergeArray(keyData[v], entnicheRule[v])
  1355. } else {
  1356. //第一次搜索不存在
  1357. keyData[v] = entnicheRule[v]
  1358. }
  1359. }
  1360. }
  1361. }
  1362. } else {
  1363. //企业关键词查找
  1364. res_, _ := IC.Mgo.FindOneByField("entniche_rule", map[string]interface{}{
  1365. "i_deptid": int64(0),
  1366. "i_entid": common.Int64All(spqp.EntId),
  1367. }, `{"o_entniche":1}`)
  1368. o_entniche := &map[string]interface{}{}
  1369. if res_ != nil {
  1370. o_entniche = common.ObjToMap((*res_)["o_entniche"])
  1371. }
  1372. if (*o_entniche)["a_items"] != nil {
  1373. a_item := common.ObjArrToMapArr((*o_entniche)["a_items"].([]interface{}))
  1374. for _, v := range a_item {
  1375. if v["a_key"] != nil {
  1376. a_key_arr := v["a_key"].([]interface{})
  1377. keyData[common.InterfaceToStr(v["s_item"])] = a_key_arr
  1378. }
  1379. }
  1380. }
  1381. }
  1382. return MapToarr(keyData, s.ModuleFlag)
  1383. }
  1384. //关键词处理
  1385. func KeyHandle(a_items map[string]interface{}) []interface{} {
  1386. keyArr := []interface{}{}
  1387. if a_items["a_key"] != nil {
  1388. a_key_arr := common.ObjArrToMapArr(a_items["a_key"].([]interface{}))
  1389. for _, vv := range a_key_arr {
  1390. for _, v := range vv["key"].([]interface{}) {
  1391. keyArr = append(keyArr, v)
  1392. }
  1393. }
  1394. }
  1395. return keyArr
  1396. }
  1397. func MapToarr(data map[string][]interface{}, userType string) []*bxsubscribe.Items {
  1398. result := []*bxsubscribe.Items{}
  1399. for k, v := range data {
  1400. log.Println(common.ObjArrToStringArr(v))
  1401. keyArr := []*bxsubscribe.Keys{}
  1402. for _, m := range common.ObjArrToMapArr(v) {
  1403. keys := &bxsubscribe.Keys{}
  1404. if m["notkey"] != nil {
  1405. keys.Notkey = common.ObjArrToStringArr(m["notkey"].([]interface{}))
  1406. }
  1407. if m["key"] != nil {
  1408. keys.Key = common.ObjArrToStringArr(m["key"].([]interface{}))
  1409. }
  1410. if m["matchway"] != nil {
  1411. keys.Matchway = common.Int64All(m["matchway"])
  1412. }
  1413. if m["appendKey"] != nil {
  1414. keys.AppendKey = common.ObjArrToStringArr(m["appendKey"].([]interface{}))
  1415. }
  1416. keyArr = append(keyArr, keys)
  1417. }
  1418. if userType == "ftype" {
  1419. k = ""
  1420. }
  1421. result = append(result, &bxsubscribe.Items{
  1422. AKey: keyArr,
  1423. SItem: k,
  1424. })
  1425. }
  1426. return result
  1427. }
  1428. func MergeArray(dest []interface{}, src []interface{}) (result []interface{}) {
  1429. result = make([]interface{}, len(dest)+len(src))
  1430. //将第一个数组传入result
  1431. copy(result, dest)
  1432. //将第二个数组接在尾部,也就是 len(dest):
  1433. copy(result[len(dest):], src)
  1434. return
  1435. }