push.go 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492
  1. package model
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. IC "jyBXSubscribe/rpc/init"
  6. ms "jyBXSubscribe/rpc/model/service"
  7. "jyBXSubscribe/rpc/type/bxsubscribe"
  8. "jyBXSubscribe/rpc/util"
  9. "log"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "go.mongodb.org/mongo-driver/bson"
  15. "github.com/gogf/gf/v2/util/gconv"
  16. "app.yhyue.com/moapp/jybase/common"
  17. "app.yhyue.com/moapp/jybase/date"
  18. "app.yhyue.com/moapp/jybase/encrypt"
  19. elastic "app.yhyue.com/moapp/jybase/es"
  20. P "app.yhyue.com/moapp/jybase/mapping"
  21. "app.yhyue.com/moapp/jybase/mongodb"
  22. "app.yhyue.com/moapp/jybase/mysql"
  23. "app.yhyue.com/moapp/jybase/redis"
  24. "github.com/zeromicro/go-zero/core/logx"
  25. "go.mongodb.org/mongo-driver/bson/primitive"
  26. )
  27. const (
  28. pageSize = 100
  29. AllSubPushCacheSize = 200
  30. query = `{"query":{"terms":{"_id":["%s"]}},"_source":["_id","area","city", "publishtime", "s_subscopeclass", "subtype", "title", "toptype", "type", "buyerclass","bidamount","budget","projectname","buyer","bidopentime","s_winner","filetext","spidercode","site","buyertel","buyerperson","agency","agencyperson","agencytel","winnerperson","winnertel","signendtime","bidendtime","entidlist","isValidFile"],"from":0,"size":%d}`
  31. query1 = `{"query":{"terms":{"_id":["%s"]}},"_source":["_id","area","city", "publishtime", "s_subscopeclass", "subtype", "title", "toptype", "type", "buyerclass","bidamount","budget","projectname","buyer","bidopentime","s_winner","filetext","spidercode","site","buyertel","buyerperson","agency","agencyperson","agencytel","winnerperson","winnertel","signendtime","bidendtime","entidlist","isValidFile", "detail"],"from":0,"size":%d}`
  32. query2 = `{"query":{"terms":{"_id":["%s"]}},"_source":["_id","title", "detail"],"from":0,"size":%d}`
  33. mongodb_fields = `{"_id":1,"area":1,"publishtime":1,"s_subscopeclass":1,"subtype":1,"title":1,"toptype":1,"type":1, "city":1,"buyerclass":1,"budget":1,"bidamount":1,"s_winner":1,"bidopentime":1,"buyer":1,"projectname":1,"filetext":1,"spidercode":1,"site":1,"buyertel":1,"buyerperson":1,"agency":1,"agencyperson":1,"agencytel":1,"winnerperson":1,"winnertel":1,"signendtime":1,"bidendtime":1,"entidlist":1,"isValidFile":1}`
  34. mongodb_fields1 = `{"_id":1,"area":1,"publishtime":1,"s_subscopeclass":1,"subtype":1,"title":1,"toptype":1,"type":1, "city":1,"buyerclass":1,"budget":1,"bidamount":1,"s_winner":1,"bidopentime":1,"buyer":1,"projectname":1,"filetext":1,"spidercode":1,"site":1,"buyertel":1,"buyerperson":1,"agency":1,"agencyperson":1,"agencytel":1,"winnerperson":1,"winnertel":1,"signendtime":1,"bidendtime":1,"entidlist":1,"isValidFile":1, "detail": 1}`
  35. SubFreeFlag = "fType"
  36. SubVipFlag = "vType"
  37. MemberFlag = "mType"
  38. EntnicheFlag = "eType"
  39. oneDay = 24 * 60 * 60
  40. )
  41. var (
  42. ennicheInsertCollKey = []string{"infoid", "matchkeys", "date", "area", "city", "district", "buyerclass", "toptype", "subtype", "subscopeclass", "budget", "bidamount", "attachment_count", "userid", "entid", "deptid", "source", "product"}
  43. subscribeInsertCollKey = []string{"infoid", "matchkeys", "date", "area", "city", "district", "buyerclass", "toptype", "subtype", "subscopeclass", "budget", "bidamount", "attachment_count", "userid", "isvip"}
  44. memberInsertCollKey = []string{"infoid", "matchkeys", "date", "area", "city", "district", "buyerclass", "toptype", "subtype", "subscopeclass", "budget", "bidamount", "attachment_count", "userid"}
  45. )
  46. var aboutDbMsg map[string]*AboutDbMsg = map[string]*AboutDbMsg{
  47. SubFreeFlag: &AboutDbMsg{"push.pushsubscribe", "subpush"},
  48. SubVipFlag: &AboutDbMsg{"push.pushsubscribe", "subpush"},
  49. MemberFlag: &AboutDbMsg{"push.pushmember", "memberpush"},
  50. EntnicheFlag: &AboutDbMsg{"push.pushentniche", "entnichepush"},
  51. }
  52. type AboutDbMsg struct {
  53. MysqlTable string
  54. RedisKeyFlag string
  55. }
  56. type SubPush struct {
  57. Date string
  58. Datas []*bxsubscribe.SubscribeInfo
  59. Count int64
  60. }
  61. type PushCa struct {
  62. Date int64
  63. InfoId string
  64. Visit int
  65. Index int64
  66. Keys []string
  67. MatchWays string
  68. Type int
  69. Isvip int
  70. FileExists bool
  71. Source int64
  72. Title string
  73. SourceAll string
  74. }
  75. // 查询参数
  76. type SubPushQueryParam struct {
  77. Mgo_bidding mongodb.MongodbSim //
  78. Bidding string //
  79. Bidding_back string //
  80. UserId string //用户id
  81. PageNum int //页面
  82. PageSize int //每页数量
  83. SelectTime string //时间
  84. Area string //区域
  85. City string //城市
  86. Buyerclass string //采购单位行业
  87. Subtype string //信息类型 二级分类
  88. Subscopeclass string //信息行业
  89. Key string //订阅词
  90. Export bool //导出
  91. EntId string //企业id
  92. Price string //价格
  93. FileExists string //是否有附件;默认全部;1:有附件;-1:无附件
  94. EntUserId string //商机管理用户id
  95. DeptId string //商机管理用户部门id
  96. IsRead string //是否已读
  97. Source string //信息来源
  98. Staffs []string //分发人员
  99. BaseServiceMysql *mysql.Mysql
  100. NewUserId int64
  101. IsEnt bool
  102. SelectInfoIds []string
  103. BuySubject int64
  104. UserType string
  105. PositionType int64
  106. IsPayUser bool // 是否是付费用户
  107. NotReturnCount int64
  108. Item string
  109. SelectKeys []string //关键词
  110. District string
  111. SubPushInactive int // 订阅活跃标记
  112. }
  113. // 关键词参数
  114. type KeyParam struct {
  115. UserId string //用户id
  116. EntUserId string //商机管理用户id
  117. DeptId string //商机管理用户部门id
  118. NewUserId int64
  119. IsEnt bool
  120. VipPower int64
  121. EntId string //企业id
  122. MemberPower int64
  123. PowerSource int64
  124. UserPower int64
  125. PositionType int64
  126. }
  127. func (spqp *SubPushQueryParam) IsEmpty() bool {
  128. return (spqp.SelectTime == "" || spqp.SelectTime == "all") && spqp.Area == "" && spqp.District == "" && spqp.City == "" && spqp.Buyerclass == "" && spqp.Subscopeclass == "" && spqp.Subtype == "" && spqp.Key == "" && spqp.Item == "" && spqp.Price == "" && spqp.FileExists == "" && len(spqp.Staffs) == 0 && spqp.Source == "" && spqp.IsRead == ""
  129. }
  130. type subscribePush struct {
  131. ModuleFlag string
  132. }
  133. func NewSubscribePush(module ...string) *subscribePush {
  134. m := ""
  135. if len(module) > 0 {
  136. m = module[0]
  137. }
  138. return &subscribePush{m}
  139. }
  140. // 从pushcache_2_a中取
  141. func (s *subscribePush) GetTodayCache(userId, userType string) (*SubPush, error) {
  142. pc_a, err := redis.GetNewBytes("pushcache_2_b", s.todayKey(userId, userType))
  143. if err != nil {
  144. return nil, err
  145. }
  146. if pc_a == nil {
  147. return nil, nil
  148. }
  149. var p *SubPush
  150. if err := json.Unmarshal(*pc_a, &p); err != nil {
  151. return nil, err
  152. }
  153. return p, nil
  154. }
  155. // 往pushcache_2_a中放
  156. func (s *subscribePush) PutTodayCache(userId, userType string, pc_a *SubPush) {
  157. redis.Put("pushcache_2_b", s.todayKey(userId, userType), pc_a, oneDay)
  158. }
  159. // 获取redis key
  160. func (s *subscribePush) todayKey(userId, userType string) string {
  161. if s.ModuleFlag == EntnicheFlag {
  162. switch userType {
  163. case SubVipFlag:
  164. return fmt.Sprintf("%s_%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, "vip", userId)
  165. case MemberFlag:
  166. return fmt.Sprintf("%s_%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, "member", userId)
  167. case SubFreeFlag:
  168. return fmt.Sprintf("%s_%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, "free", userId)
  169. }
  170. }
  171. return fmt.Sprintf("%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, userId)
  172. }
  173. func (s *subscribePush) allKey(userId, userType string) string {
  174. if s.ModuleFlag == EntnicheFlag {
  175. switch userType {
  176. case SubVipFlag:
  177. return fmt.Sprintf("all_%s_%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, "vip", userId)
  178. case MemberFlag:
  179. return fmt.Sprintf("all_%s_%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, "member", userId)
  180. case SubFreeFlag:
  181. return fmt.Sprintf("all_%s_%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, "free", userId)
  182. }
  183. }
  184. return fmt.Sprintf("all_%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, userId)
  185. }
  186. // 历史推送记录中单条信息格式化
  187. func (s *subscribePush) InfoFormat(p *PushCa, info *map[string]interface{}, isPay, isDetail bool) *bxsubscribe.SubscribeInfo {
  188. area := common.ObjToString((*info)["area"])
  189. if area == "A" {
  190. area = "全国"
  191. }
  192. industry := common.ObjToString((*info)["s_subscopeclass"])
  193. scs := strings.Split(industry, ",")
  194. if len(scs) > 0 {
  195. industry = scs[0]
  196. if industry != "" {
  197. iss := strings.Split(industry, "_")
  198. if len(iss) > 0 {
  199. industry = iss[0]
  200. }
  201. }
  202. }
  203. infotype := common.ObjToString((*info)["subtype"])
  204. if infotype == "" {
  205. infotype = common.ObjToString((*info)["toptype"])
  206. }
  207. _id := p.InfoId
  208. if _id == "" {
  209. _id = common.ObjToString((*info)["_id"])
  210. }
  211. isValidFile, _ := (*info)["isValidFile"].(bool)
  212. formatInfo := &bxsubscribe.SubscribeInfo{
  213. XId: encrypt.EncodeArticleId2ByCheck(_id),
  214. Title: common.InterfaceToStr((*info)["title"]),
  215. Area: area,
  216. City: common.InterfaceToStr((*info)["city"]),
  217. BuyerClass: common.InterfaceToStr((*info)["buyerclass"]),
  218. Subtype: infotype,
  219. Industry: industry,
  220. PublishTime: common.Int64All((*info)["publishtime"]),
  221. CaIndex: p.Index,
  222. CaDate: p.Date,
  223. CaIsvisit: int64(p.Visit),
  224. CaIsvip: int64(p.Isvip),
  225. CaType: int64(p.Type),
  226. MatchKeys: p.Keys,
  227. Budget: common.Float64All((*info)["budget"]),
  228. BidAmount: common.Float64All((*info)["bidamount"]),
  229. Buyer: common.InterfaceToStr((*info)["buyer"]),
  230. ProjectName: common.InterfaceToStr((*info)["projectname"]),
  231. Winner: common.InterfaceToStr((*info)["s_winner"]),
  232. BidOpenTime: common.Int64All((*info)["bidopentime"]),
  233. CaFileExists: p.FileExists,
  234. Source: p.Source,
  235. Site: common.InterfaceToStr((*info)["site"]),
  236. SpiderCode: common.InterfaceToStr((*info)["spidercode"]),
  237. Toptype: common.InterfaceToStr((*info)["toptype"]),
  238. IsValidFile: isValidFile,
  239. SourceAll: p.SourceAll,
  240. FiletextSearch: common.If(p.MatchWays == "3", true, false).(bool),
  241. Detail: common.InterfaceToStr(common.If(isDetail, (*info)["detail"], "")),
  242. }
  243. // 免费用户返回精简列表字段
  244. if !isPay {
  245. return formatInfo
  246. }
  247. winnerList := common.InterfaceToStr((*info)["s_winner"]) //中标企业名称集合
  248. if winnerList != "" && len(strings.Split(winnerList, ",")) > 0 {
  249. for wk, wv := range strings.Split(winnerList, ",") {
  250. var (
  251. winnerId = ""
  252. )
  253. if (*info)["entidlist"] != nil {
  254. if entIdList := common.ObjArrToStringArr((*info)["entidlist"].([]interface{})); len(entIdList) > wk { //中标企业id集合
  255. winnerId = entIdList[wk]
  256. }
  257. }
  258. formatInfo.WinnerInfo = append(formatInfo.WinnerInfo, &bxsubscribe.WinnerInfo{
  259. Winner: wv, //中标企业 需要单独处理
  260. WinnerTel: common.ObjToString((*info)["winnertel"]), //中标企业联系电话
  261. WinnerPerson: common.ObjToString((*info)["winnerperson"]), //中标企业联系人
  262. WinnerId: common.If(winnerId != "" && len([]rune(winnerId)) > 12, encrypt.EncodeArticleId2ByCheck(winnerId), "").(string), //中标企业加密id 存在winnerId 异常的情况
  263. })
  264. }
  265. }
  266. // 付费用户返回详细列表字段
  267. formatInfo.BuyerTel = common.ObjToString((*info)["buyertel"])
  268. formatInfo.BuyerPerson = common.ObjToString((*info)["buyerperson"])
  269. formatInfo.Agency = common.ObjToString((*info)["agency"])
  270. formatInfo.AgencyPerson = common.ObjToString((*info)["agencyperson"])
  271. formatInfo.AgencyTel = common.ObjToString((*info)["agencytel"])
  272. formatInfo.SignendTime = common.Int64All((*info)["signendtime"])
  273. formatInfo.BidendTime = common.Int64All((*info)["bidendtime"])
  274. return formatInfo
  275. }
  276. func (s *subscribePush) Datas(spqp *SubPushQueryParam, bsp *ViewCondition) (hasNextPage bool, total int64, result []*bxsubscribe.SubscribeInfo) {
  277. logx.Info(spqp.UserId, spqp.NewUserId, s.ModuleFlag, "subscribePush query param:", "SelectTime:", spqp.SelectTime, "Area:", spqp.Area, "District:", spqp.District, "City:", spqp.City, "Subtype:", spqp.Subtype, "Subscopeclass:", spqp.Subscopeclass, "Buyerclass:", spqp.Buyerclass, "Key:", spqp.Key, "PageNum:", spqp.PageNum, "Price:", spqp.Price, "FileExists:", spqp.FileExists)
  278. if spqp.UserId == "" {
  279. return
  280. }
  281. if spqp.PageNum < 1 {
  282. spqp.PageNum = 1
  283. }
  284. if spqp.PageSize < 1 || spqp.PageSize > pageSize {
  285. if !spqp.Export {
  286. spqp.PageSize = pageSize
  287. } else { //数据导出查询20000条限制
  288. if spqp.PageSize < 1 || spqp.PageSize > 20000 {
  289. spqp.PageSize = 20000
  290. }
  291. }
  292. }
  293. starttime, endtime := int64(0), int64(0)
  294. if len(strings.Split(spqp.SelectTime, "_")) == 2 {
  295. st := strings.Split(spqp.SelectTime, "_")[0]
  296. et := strings.Split(spqp.SelectTime, "_")[1]
  297. if st != "" && et != "" {
  298. starttime, _ = strconv.ParseInt(st, 0, 64)
  299. endtime, _ = strconv.ParseInt(et, 0, 64)
  300. if endtime > 0 {
  301. etTime := time.Unix(endtime, 0)
  302. endtime = time.Date(etTime.Year(), etTime.Month(), etTime.Day(), 23, 59, 59, 0, time.Local).Unix()
  303. }
  304. }
  305. }
  306. //不活跃用户处理
  307. if spqp.UserType == "fType" && spqp.PositionType == 0 && spqp.SubPushInactive == 1 {
  308. if spqp.Export {
  309. spqp.PageSize = 500
  310. }
  311. result, total = s.inactiveQuery(spqp, bsp)
  312. hasNextPage = len(result) >= spqp.PageSize
  313. return
  314. }
  315. nowFormat := date.NowFormat(date.Date_Short_Layout)
  316. start := (spqp.PageNum - 1) * spqp.PageSize
  317. end := start + spqp.PageSize
  318. //时间是今天,没有别的过滤条件--首先读取当前推送缓存数据 其次查询数据库
  319. if nowFormat == date.FormatDateByInt64(&starttime, date.Date_Short_Layout) && spqp.Area == "" && spqp.City == "" && spqp.District == "" && spqp.Buyerclass == "" && spqp.Subscopeclass == "" && spqp.Subtype == "" && spqp.Key == "" && spqp.Item == "" && spqp.Price == "" && spqp.FileExists == "" && len(spqp.Staffs) == 0 && spqp.Source == "" && spqp.IsRead == "" && len(spqp.SelectInfoIds) == 0 {
  320. subPush := &SubPush{}
  321. var err error
  322. if spqp.IsEnt == false {
  323. subPush, err = s.GetTodayCache(spqp.UserId, spqp.UserType)
  324. }
  325. // 返回信息补正文
  326. if subPush != nil && len(subPush.Datas) > 0 {
  327. if strings.Contains(strings.Join(bsp.SelectType, ","), "detail") {
  328. getDetail(spqp.Mgo_bidding, spqp.Bidding, spqp.Bidding_back, subPush)
  329. } else {
  330. for _, data := range subPush.Datas {
  331. data.Detail = "" // 删掉正文
  332. }
  333. }
  334. }
  335. if err != nil {
  336. logx.Info(spqp.UserId, "GetTodayCache Error", err)
  337. }
  338. if err != nil || subPush == nil || subPush.Date != nowFormat || len(subPush.Datas) == 0 {
  339. list, countSearch := s.getDatasFromMysql(spqp, starttime, endtime, spqp.PageSize, false,
  340. common.If(strings.Contains(strings.Join(bsp.SelectType, ","), "detail"), true, false).(bool))
  341. subPush = &SubPush{
  342. Date: nowFormat,
  343. Datas: list,
  344. Count: countSearch,
  345. }
  346. if spqp.IsEnt == false && spqp.NotReturnCount == 0 {
  347. s.PutTodayCache(spqp.UserId, spqp.UserType, subPush)
  348. }
  349. }
  350. length := len(subPush.Datas)
  351. if end > length {
  352. end = length
  353. }
  354. if start < length {
  355. result = subPush.Datas[start:end]
  356. } else {
  357. result = subPush.Datas
  358. }
  359. total = int64(length)
  360. //全部,没有过滤条件 之前缓存500
  361. } else if spqp.IsEmpty() && (spqp.PageNum-1)*spqp.PageSize < 200 && len(spqp.SelectInfoIds) == 0 && !spqp.Export { //全部,没有过滤条件 之前缓存5页*50条=250 非数据导出
  362. allCache := &SubPush{}
  363. var err error
  364. if !spqp.IsEnt {
  365. allCache, err = s.GetAllCache(spqp.UserId, spqp.UserType)
  366. }
  367. if err != nil {
  368. logx.Info(spqp.UserId, "GetAllCache Error", err)
  369. }
  370. // 返回信息补正文
  371. if allCache != nil && len(allCache.Datas) > 0 {
  372. if strings.Contains(strings.Join(bsp.SelectType, ","), "detail") {
  373. getDetail(spqp.Mgo_bidding, spqp.Bidding, spqp.Bidding_back, allCache)
  374. } else {
  375. for _, data := range allCache.Datas {
  376. data.Detail = "" // 删掉正文
  377. }
  378. }
  379. }
  380. if err != nil || allCache == nil || allCache.Date != nowFormat || len(allCache.Datas) == 0 {
  381. list, countSearch := []*bxsubscribe.SubscribeInfo{}, int64(0)
  382. if spqp.IsEnt {
  383. list, countSearch = s.getDatasFromMysql(spqp, starttime, endtime, spqp.PageSize, true, common.If(strings.Contains(strings.Join(bsp.SelectType, ","), "detail"), true, false).(bool))
  384. } else {
  385. spqp.PageNum = 1
  386. list, countSearch = s.getDatasFromMysql(spqp, starttime, endtime, AllSubPushCacheSize, true, common.If(strings.Contains(strings.Join(bsp.SelectType, ","), "detail"), true, false).(bool))
  387. }
  388. allCache = &SubPush{
  389. Date: nowFormat,
  390. Datas: list,
  391. Count: countSearch,
  392. }
  393. if spqp.IsEnt == false && spqp.NotReturnCount == 0 {
  394. s.PutAllCache(spqp.UserId, spqp.UserType, allCache)
  395. }
  396. }
  397. length := len(allCache.Datas)
  398. if end > length {
  399. end = length
  400. }
  401. if start < length {
  402. result = allCache.Datas[start:end]
  403. } else {
  404. result = allCache.Datas
  405. }
  406. total = allCache.Count
  407. } else {
  408. if strings.Contains(strings.Join(bsp.SelectType, ","), "detail") {
  409. result, total = s.getDatasFromMysql(spqp, starttime, endtime, spqp.PageSize, true, true)
  410. } else {
  411. result, total = s.getDatasFromMysql(spqp, starttime, endtime, spqp.PageSize, true, false)
  412. }
  413. }
  414. if result == nil {
  415. result = []*bxsubscribe.SubscribeInfo{}
  416. }
  417. hasNextPage = len(result) >= spqp.PageSize
  418. return
  419. }
  420. func (s *subscribePush) inactiveQuery(spqp *SubPushQueryParam, bsp *ViewCondition) ([]*bxsubscribe.SubscribeInfo, int64) {
  421. list := &[]map[string]interface{}{}
  422. count := int64(0)
  423. if len(spqp.SelectInfoIds) > 0 {
  424. //通过infoId查数据
  425. list = elastic.Get("bidding", "bidding", fmt.Sprintf(query, strings.Join(spqp.SelectInfoIds, `","`), len(spqp.SelectInfoIds)))
  426. count = gconv.Int64(len(*list))
  427. } else {
  428. if len(bsp.Keyword) == 0 || spqp.PageNum*spqp.PageSize > 500 {
  429. return []*bxsubscribe.SubscribeInfo{}, int64(0)
  430. }
  431. //通过条件查询
  432. starttime := int64(0)
  433. endtime := int64(0)
  434. if len(strings.Split(spqp.SelectTime, "_")) == 2 {
  435. st := strings.Split(spqp.SelectTime, "_")[0]
  436. et := strings.Split(spqp.SelectTime, "_")[1]
  437. if st == "" {
  438. starttime = time.Now().AddDate(0, 0, -15).Unix()
  439. } else {
  440. starttime, _ = strconv.ParseInt(st, 0, 64)
  441. if starttime < time.Now().AddDate(0, 0, -15).Unix() {
  442. starttime = time.Now().AddDate(0, 0, -15).Unix()
  443. }
  444. }
  445. if et == "" {
  446. endtime = time.Now().Unix()
  447. } else {
  448. endtime, _ = strconv.ParseInt(et, 0, 64)
  449. if endtime < time.Now().AddDate(0, 0, -15).Unix() {
  450. endtime = time.Now().AddDate(0, 0, -15).Unix()
  451. }
  452. }
  453. } else {
  454. starttime = time.Now().AddDate(0, 0, -15).Unix()
  455. endtime = time.Now().Unix()
  456. }
  457. qstr := s.getFreeDatasSQL(bsp, starttime, endtime, (spqp.PageNum-1)*spqp.PageSize, spqp.PageSize)
  458. //list = elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSort, bidField, 0, 4500, 0, false)
  459. count, list = elastic.GetWithCount(INDEX, TYPE, "", qstr)
  460. }
  461. if count > 500 {
  462. count = 500
  463. }
  464. log.Println(count, list)
  465. //数据清洗
  466. size := spqp.PageSize
  467. if spqp.PageSize == 0 {
  468. size = len(spqp.SelectInfoIds)
  469. }
  470. array := make([]*bxsubscribe.SubscribeInfo, len(*list))
  471. for i, m := range *list {
  472. if i == size {
  473. break
  474. }
  475. formatInfo := &bxsubscribe.SubscribeInfo{}
  476. infoid := common.InterfaceToStr(m["_id"])
  477. matchkeys := getKeys(common.InterfaceToStr(m["title"]), bsp.Keyword)
  478. if len(spqp.SelectInfoIds) > 0 {
  479. formatInfo = &bxsubscribe.SubscribeInfo{XId: encrypt.EncodeArticleId2ByCheck(infoid), MatchKeys: matchkeys}
  480. } else {
  481. industry := common.ObjToString(m["s_subscopeclass"])
  482. scs := strings.Split(industry, ",")
  483. if len(scs) > 0 {
  484. industry = scs[0]
  485. if industry != "" {
  486. iss := strings.Split(industry, "_")
  487. if len(iss) > 0 {
  488. industry = iss[0]
  489. }
  490. }
  491. }
  492. infotype := common.ObjToString(m["subtype"])
  493. if infotype == "" {
  494. infotype = common.ObjToString(m["toptype"])
  495. }
  496. area := common.If(m["area"] == nil, "", common.If(common.ObjToString(m["area"]) == "A", "全国", common.ObjToString(m["area"])))
  497. formatInfo = &bxsubscribe.SubscribeInfo{
  498. XId: encrypt.EncodeArticleId2ByCheck(infoid),
  499. Title: common.InterfaceToStr(m["title"]),
  500. Area: gconv.String(area),
  501. City: common.InterfaceToStr(m["city"]),
  502. BuyerClass: common.InterfaceToStr(m["buyerclass"]),
  503. Subtype: infotype,
  504. Industry: industry,
  505. PublishTime: common.Int64All(m["publishtime"]),
  506. CaDate: gconv.Int64(m["publishtime"]),
  507. CaIsvisit: 0,
  508. CaIsvip: 0,
  509. CaType: 0,
  510. MatchKeys: matchkeys,
  511. Budget: common.Float64All(m["budget"]),
  512. BidAmount: common.Float64All(m["bidamount"]),
  513. Buyer: common.InterfaceToStr(m["buyer"]),
  514. ProjectName: common.InterfaceToStr(m["projectname"]),
  515. Winner: common.InterfaceToStr(m["s_winner"]),
  516. BidOpenTime: common.Int64All(m["bidopentime"]),
  517. CaFileExists: m["filetext"] != nil,
  518. Source: 1,
  519. Site: common.InterfaceToStr(m["site"]),
  520. SpiderCode: common.InterfaceToStr(m["spidercode"]),
  521. Toptype: common.InterfaceToStr(m["toptype"]),
  522. IsValidFile: m["filetext"] != nil,
  523. SourceAll: "1",
  524. }
  525. }
  526. array[i] = formatInfo
  527. }
  528. return array, count
  529. }
  530. var topTypeMap = map[string]string{
  531. "招标预告": "预告",
  532. "招标公告": "招标",
  533. "招标结果": "结果",
  534. "招标信用信息": "其它",
  535. }
  536. func (s *subscribePush) getDatasFromMysql(spqp *SubPushQueryParam, starttime, endtime int64, size int, isLimit, isDetail bool) (result []*bxsubscribe.SubscribeInfo, count int64) {
  537. start := time.Now().Unix()
  538. querys := []string{}
  539. userStr := " 1=1 "
  540. var (
  541. countSql, findSql string
  542. list []map[string]interface{}
  543. )
  544. querys = append(querys, " ")
  545. if spqp.SelectInfoIds != nil && len(spqp.SelectInfoIds) > 0 {
  546. var (
  547. selectInfoIds []string
  548. )
  549. for _, sId := range spqp.SelectInfoIds {
  550. selectInfoIds = append(selectInfoIds, sId)
  551. if len(selectInfoIds) == 50 {
  552. findSelectSql := fmt.Sprintf("select a.id,a.date,a.infoid,a.isvisit,REPLACE(a.matchkeys,'+',' ') as matchkeys,a.type,a.attachment_count from %s a where %s order by a.date desc,a.id desc", aboutDbMsg[s.ModuleFlag].MysqlTable, fmt.Sprintf("a.id in ('%s')", strings.Join(selectInfoIds, "','")))
  553. logx.Info(spqp.NewUserId, "subscribePush info ids query sql:", findSelectSql)
  554. list = append(list, *spqp.BaseServiceMysql.SelectBySql(findSelectSql)...)
  555. selectInfoIds = []string{}
  556. }
  557. }
  558. if len(selectInfoIds) > 0 {
  559. findSelectSql := fmt.Sprintf("select a.id,a.date,a.infoid,a.isvisit,REPLACE(a.matchkeys,'+',' ') as matchkeys,a.type,a.attachment_count from %s a where %s order by a.date desc,a.id desc", aboutDbMsg[s.ModuleFlag].MysqlTable, fmt.Sprintf("a.id in ('%s')", strings.Join(selectInfoIds, "','")))
  560. logx.Info(spqp.NewUserId, "subscribePush info ids query sql:", findSelectSql)
  561. list = append(list, *spqp.BaseServiceMysql.SelectBySql(findSelectSql)...)
  562. selectInfoIds = []string{}
  563. }
  564. //countSql = fmt.Sprintf("select count(1) as count from %s a where %s", aboutDbMsg[s.ModuleFlag].MysqlTable, fmt.Sprintf("a.id in ('%s')", strings.Join(spqp.SelectInfoIds, "','")))
  565. //logx.Info("countSql", countSql)
  566. //findSql = fmt.Sprintf("select a.id,a.date,a.infoid,a.isvisit,REPLACE(a.matchkeys,'+',' ') as matchkeys,a.type,a.attachment_count from %s a where %s order by a.date desc,a.id desc", aboutDbMsg[s.ModuleFlag].MysqlTable, fmt.Sprintf("a.id in ('%s')", strings.Join(spqp.SelectInfoIds, "','")))
  567. ////查询总数
  568. //count = spqp.BaseServiceMysql.CountBySql(countSql)
  569. } else {
  570. //公共查询条件
  571. //时间
  572. if starttime > 0 && endtime > 0 {
  573. querys = append(querys, fmt.Sprintf(" a.date>=%d and a.date<=%d", starttime, endtime))
  574. } else if starttime > 0 && endtime == 0 {
  575. querys = append(querys, fmt.Sprintf(" a.date>=%d", starttime))
  576. } else if starttime == 0 && endtime > 0 {
  577. querys = append(querys, fmt.Sprintf(" a.date<=%d", endtime))
  578. } else {
  579. querys = append(querys, " a.date>0")
  580. }
  581. var regionArr = []string{}
  582. if spqp.Area != "" || spqp.City != "" || spqp.District != "" {
  583. //城市
  584. city := []string{}
  585. for _, v := range strings.Split(spqp.City, ",") {
  586. if P.BidCodeMapping.City[v] != "" {
  587. city = append(city, fmt.Sprint(P.BidCodeMapping.City[v]))
  588. }
  589. }
  590. if len(city) > 0 {
  591. regionArr = append(regionArr, fmt.Sprintf(" a.city in (%s) ", strings.Join(city, ",")))
  592. }
  593. //区域
  594. area := []string{}
  595. for _, v := range strings.Split(spqp.Area, ",") {
  596. if P.BidCodeMapping.Area[v] != "" {
  597. area = append(area, fmt.Sprint(P.BidCodeMapping.Area[v]))
  598. }
  599. }
  600. if len(area) > 0 {
  601. regionArr = append(regionArr, fmt.Sprintf(" a.area in (%s) ", strings.Join(area, ",")))
  602. }
  603. //区域
  604. district := []string{}
  605. if spqp.District != "" {
  606. for _, v := range strings.Split(spqp.District, ",") {
  607. cityName := strings.Split(v, "_")[0]
  608. districtName := strings.Split(v, "_")[1]
  609. if P.BidCodeMapping.District[cityName][districtName] != "" {
  610. district = append(district, fmt.Sprint(P.BidCodeMapping.District[cityName][districtName]))
  611. }
  612. }
  613. }
  614. if len(district) > 0 {
  615. regionArr = append(regionArr, fmt.Sprintf(" a.district in (%s) ", strings.Join(district, ",")))
  616. }
  617. if len(regionArr) > 0 {
  618. querys = append(querys, fmt.Sprintf("(%s)", strings.Join(regionArr, "or")))
  619. }
  620. }
  621. //采购单位行业
  622. if spqp.Buyerclass != "" {
  623. buyerclass := []string{}
  624. for _, v := range strings.Split(spqp.Buyerclass, ",") {
  625. if fmt.Sprint(P.BidCodeMapping.Buyerclass[v]) != "" {
  626. buyerclass = append(buyerclass, fmt.Sprint(P.BidCodeMapping.Buyerclass[v]))
  627. }
  628. }
  629. if len(buyerclass) == 1 {
  630. buyerclass = append(buyerclass, "9999")
  631. }
  632. if len(buyerclass) > 0 {
  633. querys = append(querys, fmt.Sprintf("a.buyerclass in (%s)", strings.Join(buyerclass, ",")))
  634. }
  635. }
  636. //信息类型
  637. if spqp.Subtype != "" {
  638. var topType []string
  639. typeInt := 0
  640. stype := strings.Split(spqp.Subtype, ",")
  641. for _, v := range stype {
  642. if tType := topTypeMap[v]; tType != "" {
  643. topType = append(topType, tType)
  644. typeInt += 1
  645. continue
  646. }
  647. }
  648. var subtype []string
  649. var toptype []string
  650. //subtype里都是二级级信息类型
  651. if typeInt == 0 {
  652. for _, v := range stype {
  653. subtype = append(subtype, P.BidCodeMapping.Subtype[v])
  654. }
  655. if len(subtype) == 1 {
  656. subtype = append(subtype, "9999")
  657. }
  658. } else if typeInt == len(stype) { // subtype里边 都是一级信息类型
  659. for _, v := range topType {
  660. toptype = append(toptype, P.BidCodeMapping.Toptype[v])
  661. }
  662. if len(topType) == 1 {
  663. toptype = append(toptype, "9999")
  664. }
  665. } else {
  666. for _, v := range stype {
  667. if P.BidCodeMapping.Subtype[v] != "" {
  668. subtype = append(subtype, P.BidCodeMapping.Subtype[v])
  669. }
  670. }
  671. if len(subtype) == 1 {
  672. subtype = append(subtype, "9999")
  673. }
  674. for _, v := range topType {
  675. toptype = append(toptype, P.BidCodeMapping.Toptype[v])
  676. }
  677. if len(subtype) == 1 {
  678. toptype = append(toptype, "9999")
  679. }
  680. }
  681. if len(subtype) > 0 && len(toptype) > 0 {
  682. s1 := fmt.Sprintf("(%s or %s)", fmt.Sprintf("a.subtype in (%s)", strings.Join(subtype, ",")),
  683. fmt.Sprintf("a.toptype in (%s)", strings.Join(toptype, ",")))
  684. querys = append(querys, s1)
  685. } else if len(subtype) > 0 {
  686. querys = append(querys, fmt.Sprintf("a.subtype in (%s)", strings.Join(subtype, ",")))
  687. } else if len(toptype) > 0 {
  688. querys = append(querys, fmt.Sprintf("a.toptype in (%s)", strings.Join(toptype, ",")))
  689. }
  690. }
  691. //信息行业
  692. if spqp.Subscopeclass != "" {
  693. find_in_set := []string{}
  694. for _, v := range strings.Split(spqp.Subscopeclass, ",") {
  695. find_in_set = append(find_in_set, fmt.Sprintf("find_in_set('%s',a.subscopeclass)", P.BidCodeMapping.Subscopeclass[v]))
  696. }
  697. if len(find_in_set) == 1 {
  698. querys = append(querys, find_in_set[0])
  699. } else if len(find_in_set) > 1 {
  700. querys = append(querys, fmt.Sprintf("(%s)", strings.Join(find_in_set, " or ")))
  701. }
  702. }
  703. //关键词
  704. find_in_set := []string{}
  705. if spqp.IsEnt {
  706. if spqp.Key != "" {
  707. for _, v := range strings.Split(spqp.Key, ",") {
  708. find_in_set = append(find_in_set, fmt.Sprintf("find_in_set('%s',replace(a.matchkeys,' ',','))", v))
  709. }
  710. }
  711. if spqp.Item != "" {
  712. for _, v := range strings.Split(spqp.Item, ",") {
  713. find_in_set = append(find_in_set, fmt.Sprintf("find_in_set('%s',replace(a.matchitems,' ',','))", v))
  714. }
  715. }
  716. } else {
  717. if spqp.Key != "" {
  718. for _, v := range strings.Split(spqp.Key, ",") {
  719. find_in_set = append(find_in_set, fmt.Sprintf("find_in_set('%s',replace(a.matchkeys,' ',','))", v))
  720. }
  721. }
  722. if spqp.Item != "" {
  723. //通过分类名搜索
  724. keyArr := s.ItemToKey(spqp)
  725. for _, v := range strings.Split(keyArr, ",") {
  726. find_in_set = append(find_in_set, fmt.Sprintf("find_in_set('%s',replace(a.matchkeys,' ',','))", v))
  727. }
  728. }
  729. }
  730. if len(find_in_set) == 1 {
  731. querys = append(querys, find_in_set[0])
  732. } else if len(find_in_set) > 1 {
  733. querys = append(querys, fmt.Sprintf("(%s)", strings.Join(find_in_set, " or ")))
  734. }
  735. //价格- 预算和中标金额
  736. if spqp.Price != "" && strings.Contains(spqp.Price, "-") {
  737. minPriceStr, maxPriceStr := strings.Split(spqp.Price, "-")[0], strings.Split(spqp.Price, "-")[1]
  738. minPrice := common.Int64All(common.Float64All(minPriceStr) * 10000) //换成元
  739. maxPrice := common.Int64All(common.Float64All(maxPriceStr) * 10000) //换成元
  740. if minPriceStr != "" && maxPriceStr != "" {
  741. querys = append(querys, fmt.Sprintf("((a.bidamount>=%d and a.bidamount<=%d) or (a.budget>=%d and a.budget<=%d and a.bidamount is null))", minPrice, maxPrice, minPrice, maxPrice))
  742. } else if minPriceStr != "" {
  743. querys = append(querys, fmt.Sprintf("(a.bidamount>=%d or (a.budget>=%d and a.bidamount is null))", minPrice, minPrice))
  744. } else if maxPriceStr != "" {
  745. querys = append(querys, fmt.Sprintf("(a.bidamount<=%d or (a.budget<=%d and a.bidamount is null))", maxPrice, maxPrice))
  746. }
  747. }
  748. //附件
  749. if spqp.FileExists != "" {
  750. if spqp.FileExists == "1" {
  751. querys = append(querys, fmt.Sprintf("a.attachment_count is not null"))
  752. } else if spqp.FileExists == "-1" {
  753. querys = append(querys, fmt.Sprintf("a.attachment_count is null"))
  754. }
  755. }
  756. // 是否已读
  757. if spqp.IsRead != "" {
  758. if spqp.IsRead == "0" {
  759. querys = append(querys, " a.isvisit IS NULL")
  760. } else if spqp.IsRead == "1" {
  761. querys = append(querys, " a.isvisit=1")
  762. }
  763. }
  764. // 信息来源
  765. if spqp.Source == "1" || spqp.Source == "2" || spqp.Source == "3" {
  766. querys = append(querys, " a.source="+spqp.Source)
  767. }
  768. if spqp.IsEnt {
  769. var staffs []string
  770. userStr += fmt.Sprintf(" and a.entid='%s' ", spqp.EntId)
  771. //判断是企业管理员还是部门管理员 部门管理员获取所有子部门
  772. userEnt := EntInfo(common.IntAll(spqp.EntId), common.IntAll(spqp.EntUserId))
  773. if !(userEnt.Role_admin_system || userEnt.Role_admin_department) {
  774. result = []*bxsubscribe.SubscribeInfo{}
  775. return
  776. }
  777. if userEnt.Role_admin_department { //
  778. // 部门管理员 获取所有部门和子部门员工
  779. users := GetDisUsers(common.IntAll(spqp.EntId), userEnt.Dept.Id)
  780. if users != nil && len(*users) > 0 {
  781. for _, v := range *users {
  782. if len(spqp.Staffs) > 0 {
  783. for _, vv := range spqp.Staffs {
  784. if fmt.Sprintf("%d", v.Id) == vv {
  785. staffs = append(staffs, common.InterfaceToStr(v.Id))
  786. }
  787. }
  788. } else {
  789. staffs = append(staffs, common.InterfaceToStr(v.Id))
  790. }
  791. }
  792. } else {
  793. log.Printf("部门管理员为获取到部门员工:%s", spqp.EntUserId)
  794. result = []*bxsubscribe.SubscribeInfo{}
  795. return
  796. }
  797. } else if len(spqp.Staffs) > 0 {
  798. staffs = spqp.Staffs
  799. }
  800. // 无查询分配人员、是否已读
  801. if spqp.IsRead == "" && len(staffs) == 0 {
  802. //查询数量(需要去重)
  803. countSql = fmt.Sprintf("select count(1) from %s a where %s %s ", aboutDbMsg[s.ModuleFlag].MysqlTable, userStr, strings.Join(querys, " and "))
  804. //列表查询
  805. findSql = fmt.Sprintf("select a.id,a.infoid,a.matchways,REPLACE(a.matchkeys,'+',' ') as matchkeys,a.attachment_count, IF(a.source is NULL,1,a.source) as source from %s a where %s %s order by a.date desc,a.id desc",
  806. aboutDbMsg[s.ModuleFlag].MysqlTable, userStr, strings.Join(querys, " and "))
  807. } else {
  808. //查询分配人员或是否已读
  809. staffQuery := " and 1=1 "
  810. if len(spqp.Staffs) > 0 {
  811. staffQuery += fmt.Sprintf(" and a.userid in ('%s') ", strings.Join(staffs, "','"))
  812. } else if len(staffs) > 0 {
  813. staffQuery += fmt.Sprintf(" and a.userid in (0,'%s') ", strings.Join(staffs, "','"))
  814. }
  815. countSql = fmt.Sprintf("select count(1) from %s a where %s %s %s ", aboutDbMsg[s.ModuleFlag].MysqlTable, userStr, strings.Join(querys, " and "), staffQuery)
  816. //列表查询
  817. findSql = fmt.Sprintf("select a.id,a.infoid,a.matchways,REPLACE(a.matchkeys,'+',' ') as matchkeys,a.attachment_count,IF(a.source is NULL,1,a.source) as source from %s a where %s %s %s order by a.date desc,a.id desc ", aboutDbMsg[s.ModuleFlag].MysqlTable, userStr, strings.Join(querys, " and "), staffQuery)
  818. }
  819. } else {
  820. // 是否已读
  821. if spqp.IsRead != "" {
  822. if spqp.IsRead == "0" {
  823. querys = append(querys, " a.isvisit IS NULL")
  824. } else if spqp.IsRead == "1" {
  825. querys = append(querys, " a.isvisit=1")
  826. }
  827. }
  828. // 信息来源
  829. if spqp.Source == "1" || spqp.Source == "2" || spqp.Source == "3" {
  830. querys = append(querys, " a.source="+spqp.Source)
  831. }
  832. if spqp.PositionType == 1 {
  833. //企业主体是企业的个人查询
  834. if spqp.UserType == SubVipFlag {
  835. userStr += fmt.Sprintf(" and a.userid='%s' and ( a.product=1 or a.product=3 or a.source>1 ) ", common.If(s.ModuleFlag == EntnicheFlag, spqp.EntUserId, common.InterfaceToStr(spqp.NewUserId)))
  836. } else if spqp.UserType == MemberFlag {
  837. userStr += fmt.Sprintf(" and a.userid='%s' and ( a.product=2 or a.product=3 or a.source>1 ) ", common.If(s.ModuleFlag == EntnicheFlag, spqp.EntUserId, common.InterfaceToStr(spqp.NewUserId)))
  838. } else if spqp.UserType == EntnicheFlag {
  839. userStr += fmt.Sprintf(" and a.userid='%s' and ( a.product is null or a.product=3 or a.source>1 ) ", common.If(s.ModuleFlag == EntnicheFlag, spqp.EntUserId, common.InterfaceToStr(spqp.NewUserId)))
  840. } else {
  841. userStr += fmt.Sprintf(" and a.userid='%s' ", common.If(s.ModuleFlag == EntnicheFlag, spqp.EntUserId, common.InterfaceToStr(spqp.NewUserId)))
  842. }
  843. } else {
  844. if s.ModuleFlag == EntnicheFlag {
  845. //老商机管理个人订阅查询
  846. userStr += fmt.Sprintf(" and a.userid='%s' and a.product is null", common.If(s.ModuleFlag == EntnicheFlag, spqp.EntUserId, common.InterfaceToStr(spqp.NewUserId)))
  847. } else {
  848. //个人订阅查询
  849. userStr += fmt.Sprintf(" and a.userid='%s'", common.If(s.ModuleFlag == EntnicheFlag, spqp.EntUserId, common.InterfaceToStr(spqp.NewUserId)))
  850. }
  851. }
  852. //查询数量
  853. countSql = fmt.Sprintf("select count(1) as count from %s a where %s %s", aboutDbMsg[s.ModuleFlag].MysqlTable, userStr, strings.Join(querys, " and "))
  854. //列表查询语句
  855. findSql = "select a.id,a.date,a.infoid,a.matchways,a.isvisit,REPLACE(a.matchkeys,'+',' ') as matchkeys,a.type,a.attachment_count"
  856. if s.ModuleFlag == EntnicheFlag {
  857. findSql += ", IF(a.source is NULL,1,a.source) as source "
  858. }
  859. if s.ModuleFlag != MemberFlag && s.ModuleFlag != EntnicheFlag {
  860. findSql += ",a.isvip"
  861. }
  862. findSql = fmt.Sprintf("%s from %s a where %s %s "+
  863. " order by a.date desc,a.id desc", findSql, aboutDbMsg[s.ModuleFlag].MysqlTable, userStr, strings.Join(querys, " and "))
  864. }
  865. //查询总数
  866. logx.Info("countSql", countSql)
  867. if spqp.NotReturnCount == 0 {
  868. count = spqp.BaseServiceMysql.CountBySql(countSql)
  869. }
  870. log.Println("数据总数查询", count)
  871. if isLimit {
  872. findSql += fmt.Sprintf(" limit %d,%d", (spqp.PageNum-1)*size, size)
  873. }
  874. list = *spqp.BaseServiceMysql.SelectBySql(findSql)
  875. logx.Info(spqp.NewUserId, "subscribePush query sql:", findSql)
  876. }
  877. end1 := time.Now().Unix()
  878. log.Println("mysql查询用时:", end1-start)
  879. if list != nil && len(list) > 0 {
  880. pushCas := s.GetJyPushs(list)
  881. if !spqp.Export {
  882. result = s.GetInfoByIds(spqp.Mgo_bidding, spqp.Bidding, spqp.Bidding_back, pushCas, spqp.IsPayUser, isDetail)
  883. } else {
  884. result = s.GetOnlyExportInfo(pushCas)
  885. }
  886. } else {
  887. result = []*bxsubscribe.SubscribeInfo{}
  888. }
  889. end2 := time.Now().Unix()
  890. log.Println("处理数据用时:", end2-end1)
  891. log.Println("总用时用时:", end2-start)
  892. return
  893. }
  894. // GetOnlyInfoId 获取信息id
  895. func (s *subscribePush) GetOnlyExportInfo(pushCas []*PushCa) []*bxsubscribe.SubscribeInfo {
  896. array := make([]*bxsubscribe.SubscribeInfo, len(pushCas))
  897. for k, v := range pushCas {
  898. array[k] = &bxsubscribe.SubscribeInfo{XId: encrypt.EncodeArticleId2ByCheck(v.InfoId), MatchKeys: v.Keys}
  899. }
  900. return array
  901. }
  902. // 根据id取内容
  903. func (s *subscribePush) GetInfoByIds(Mgo_bidding mongodb.MongodbSim, bidding, bidding_back string, pushCas []*PushCa, isPay, isDetail bool) []*bxsubscribe.SubscribeInfo {
  904. array := make([]*bxsubscribe.SubscribeInfo, len(pushCas))
  905. if len(pushCas) == 0 {
  906. return array
  907. }
  908. m := map[string]bool{}
  909. ids := []string{}
  910. for _, v := range pushCas {
  911. if m[v.InfoId] {
  912. continue
  913. }
  914. m[v.InfoId] = true
  915. ids = append(ids, v.InfoId)
  916. }
  917. infos := getInfosByIds(Mgo_bidding, bidding, bidding_back, isDetail, ids)
  918. for k, v := range pushCas {
  919. info := infos[v.InfoId]
  920. if info == nil {
  921. info = map[string]interface{}{}
  922. }
  923. array[k] = s.InfoFormat(v, &info, isPay, isDetail)
  924. }
  925. return array
  926. }
  927. func getDetail(Mgo_bidding mongodb.MongodbSim, bidding, bidding_back string, subPush *SubPush) {
  928. var ids []string
  929. for _, data := range subPush.Datas {
  930. id := encrypt.DecodeArticleId2ByCheck(data.XId)
  931. ids = append(ids, id[0])
  932. }
  933. infos := getInfosByIds(Mgo_bidding, bidding, bidding_back, true, ids)
  934. for _, data := range subPush.Datas {
  935. id := encrypt.DecodeArticleId2ByCheck(data.XId)
  936. if infos[id[0]] == nil {
  937. continue
  938. }
  939. data.Detail = common.ObjToString(infos[id[0]]["detail"])
  940. }
  941. }
  942. func getInfosByIds(Mgo_bidding mongodb.MongodbSim, bidding, bidding_back string, isDetail bool, ids []string) map[string]map[string]interface{} {
  943. infos := map[string]map[string]interface{}{}
  944. //redis
  945. pool := make(chan bool, 3)
  946. wait := &sync.WaitGroup{}
  947. lock := &sync.Mutex{}
  948. es_ids := []string{}
  949. for _, vv := range ids {
  950. pool <- true
  951. wait.Add(1)
  952. go func(v string) {
  953. defer func() {
  954. <-pool
  955. wait.Done()
  956. }()
  957. //剑鱼程序未找到赋值 位置;猜测在推送程序中
  958. info_i := redis.Get("pushcache_1", fmt.Sprintf("info_%s", v))
  959. lock.Lock()
  960. defer lock.Unlock()
  961. if info_i != nil {
  962. info_m, _ := info_i.(map[string]interface{})
  963. info_m["_id"] = v
  964. infos[v] = info_m
  965. } else {
  966. es_ids = append(es_ids, v)
  967. }
  968. }(vv)
  969. }
  970. wait.Wait()
  971. //elasticsearch
  972. if len(es_ids) > 0 {
  973. list := elastic.Get("bidding", "bidding", fmt.Sprintf(common.If(isDetail, query1, query).(string), strings.Join(es_ids, `","`), len(es_ids)))
  974. if list != nil {
  975. for _, v := range *list {
  976. _id := common.ObjToString(v["_id"])
  977. infos[_id] = v
  978. }
  979. }
  980. }
  981. //mongodb bidding
  982. mgo_ids := []primitive.ObjectID{}
  983. for _, v := range es_ids {
  984. if infos[v] == nil {
  985. _id, _ := primitive.ObjectIDFromHex(v)
  986. mgo_ids = append(mgo_ids, _id)
  987. }
  988. }
  989. if len(mgo_ids) > 0 {
  990. list, ok := Mgo_bidding.Find(bidding, map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_ids}}, nil, common.If(isDetail, mongodb_fields1, mongodb_fields), false, -1, -1)
  991. if ok && *list != nil {
  992. for _, v := range *list {
  993. _id := mongodb.BsonIdToSId(v["_id"])
  994. v["_id"] = _id
  995. infos[_id] = v
  996. }
  997. }
  998. }
  999. //mongodb bidding_back
  1000. mgo_back_ids := []primitive.ObjectID{}
  1001. for _, v := range mgo_ids {
  1002. if infos[mongodb.BsonIdToSId(v)] == nil {
  1003. mgo_back_ids = append(mgo_back_ids, v)
  1004. }
  1005. }
  1006. if len(mgo_back_ids) > 0 {
  1007. list, ok := Mgo_bidding.Find(bidding_back, map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_back_ids}}, nil, common.If(isDetail, mongodb_fields1, mongodb_fields), false, -1, -1)
  1008. if ok && *list != nil {
  1009. for _, v := range *list {
  1010. _id := mongodb.BsonIdToSId(v["_id"])
  1011. v["_id"] = _id
  1012. infos[_id] = v
  1013. }
  1014. }
  1015. }
  1016. return infos
  1017. }
  1018. // 获取历史推送
  1019. func (s *subscribePush) GetJyPushs(datas []map[string]interface{}) (pushCas []*PushCa) {
  1020. pushCas = []*PushCa{}
  1021. for _, v := range datas {
  1022. keys := []string{}
  1023. if matchkeys := common.ObjToString(v["matchkeys"]); matchkeys != "" {
  1024. keys = strings.Split(matchkeys, " ")
  1025. }
  1026. pushCas = append(pushCas, &PushCa{
  1027. Date: common.Int64All(v["date"]),
  1028. InfoId: common.ObjToString(v["infoid"]),
  1029. Visit: common.IntAll(v["isvisit"]),
  1030. Index: common.Int64All(v["id"]),
  1031. Keys: keys,
  1032. Type: common.IntAll(v["type"]),
  1033. Isvip: common.IntAll(v["isvip"]),
  1034. FileExists: common.IntAll(v["attachment_count"]) > 0,
  1035. Source: common.Int64All(v["source"]),
  1036. SourceAll: common.ObjToString(v["sourceAll"]),
  1037. MatchWays: common.ObjToString(v["matchways"]),
  1038. })
  1039. }
  1040. return
  1041. }
  1042. // 查看全部列表缓存
  1043. func (s *subscribePush) PutAllCache(userId, userType string, datas *SubPush) {
  1044. //log.Println("pushcache_2_a", s.allKey(userId, userType), datas, oneDay)
  1045. redis.Put("pushcache_2_a", s.allKey(userId, userType), datas, oneDay)
  1046. }
  1047. func (s *subscribePush) GetAllCache(userId, userType string) (*SubPush, error) {
  1048. return s.GetCache("pushcache_2_a", s.allKey(userId, userType))
  1049. }
  1050. func (s *subscribePush) GetCache(code, key string) (*SubPush, error) {
  1051. pc_a, err := redis.GetNewBytes(code, key)
  1052. if err != nil {
  1053. return nil, err
  1054. }
  1055. if pc_a == nil {
  1056. return nil, nil
  1057. }
  1058. var p *SubPush
  1059. if err := json.Unmarshal(*pc_a, &p); err != nil {
  1060. return nil, err
  1061. }
  1062. return p, nil
  1063. }
  1064. // 是否收藏
  1065. func (s *subscribePush) MakeCollection(userId string, list []*bxsubscribe.SubscribeInfo) {
  1066. if list == nil || len(list) == 0 {
  1067. return
  1068. }
  1069. param := []interface{}{userId}
  1070. wh := []string{}
  1071. for _, v := range list {
  1072. array := encrypt.DecodeArticleId2ByCheck(v.XId)
  1073. if len(array) == 1 && array[0] != "" {
  1074. param = append(param, array[0])
  1075. wh = append(wh, "?")
  1076. }
  1077. }
  1078. if len(wh) > 0 {
  1079. result := IC.MainMysql.SelectBySql(`select bid from bdcollection where userid=? and bid in (`+strings.Join(wh, ",")+`)`, param...)
  1080. bid_map := map[string]bool{}
  1081. if result != nil {
  1082. for _, v := range *result {
  1083. bid_map[encrypt.EncodeArticleId2ByCheck(common.ObjToString(v["bid"]))] = true
  1084. }
  1085. }
  1086. for _, v := range list {
  1087. if bid_map[v.XId] {
  1088. v.Collection = 1
  1089. }
  1090. }
  1091. }
  1092. }
  1093. // 仅移动端首页使用,历史推送7天信息
  1094. func (s *subscribePush) sevenDayKey(userId string) string {
  1095. return fmt.Sprintf("7day_subpush_%s", userId)
  1096. }
  1097. func (s *subscribePush) PutSevenDayCache(userId string, datas []*bxsubscribe.SubscribeInfo) {
  1098. redis.Put("pushcache_2_a", s.sevenDayKey(userId), SubPush{Datas: datas}, 7*24*60*60)
  1099. }
  1100. // 从pushcache_2_a中取
  1101. func (s *subscribePush) GetSevenDayCache(userId string) ([]*bxsubscribe.SubscribeInfo, error) {
  1102. allPush, _ := s.GetCache("pushcache_2_a", s.sevenDayKey(userId))
  1103. if allPush != nil && allPush.Datas != nil && len(allPush.Datas) > 0 {
  1104. return allPush.Datas, nil
  1105. }
  1106. return nil, nil
  1107. }
  1108. // 历史推送记录中单条信息格式化
  1109. func InfoFormats(info map[string]interface{}, tmp map[string]interface{}) map[string]interface{} {
  1110. area := common.ObjToString(info["area"])
  1111. if area == "A" {
  1112. area = "全国"
  1113. }
  1114. industry := common.ObjToString(info["s_subscopeclass"])
  1115. scs := strings.Split(industry, ",")
  1116. if len(scs) > 0 {
  1117. industry = scs[0]
  1118. if industry != "" {
  1119. iss := strings.Split(industry, "_")
  1120. if len(iss) > 0 {
  1121. industry = iss[0]
  1122. }
  1123. }
  1124. }
  1125. infotype := common.ObjToString(info["subtype"])
  1126. if infotype == "" {
  1127. infotype = common.ObjToString(info["toptype"])
  1128. }
  1129. if infotype == "" {
  1130. infotype = common.ObjToString(info["type"])
  1131. if infotype == "tender" {
  1132. infotype = "招标"
  1133. } else if infotype == "bid" {
  1134. infotype = "中标"
  1135. }
  1136. }
  1137. info["type"] = infotype
  1138. return info
  1139. }
  1140. // UpdateUserPushUnread 更新app未读标识为已读
  1141. func UpdateUserPushUnread(userid string, vt string) {
  1142. if vt == MemberFlag {
  1143. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_member_apppushunread": 0}})
  1144. } else if vt == EntnicheFlag {
  1145. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_entniche_apppushunread": 0}})
  1146. } else {
  1147. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_apppushunread": 0}})
  1148. }
  1149. }
  1150. func (s *subscribePush) SetRead(newUserId, id int64, userId, entUserId, entId string, isEnt bool, userType string) error {
  1151. if id <= 0 && newUserId == 0 {
  1152. return nil
  1153. }
  1154. if newUserId == 0 {
  1155. return nil
  1156. }
  1157. IC.BaseServiceMysql.UpdateOrDeleteBySql(fmt.Sprintf("update %s set isvisit=1,visittime=now() where userid=? and id=?", aboutDbMsg[s.ModuleFlag].MysqlTable), common.If(s.ModuleFlag == EntnicheFlag, entUserId, newUserId), id)
  1158. if s.ModuleFlag == EntnicheFlag {
  1159. userId = entUserId
  1160. }
  1161. todaySubPush, err := s.GetTodayCache(userId, userType)
  1162. //当天数据处理
  1163. if err == nil && todaySubPush != nil {
  1164. for _, v := range todaySubPush.Datas {
  1165. if v.CaIndex == id {
  1166. v.CaIsvisit = 1
  1167. break
  1168. }
  1169. }
  1170. s.PutTodayCache(userId, userType, todaySubPush)
  1171. }
  1172. //全部数据处理
  1173. allSubPush, err := s.GetAllCache(userId, userType)
  1174. if err == nil && allSubPush != nil {
  1175. for _, v := range allSubPush.Datas {
  1176. if v.CaIndex == id {
  1177. v.CaIsvisit = 1
  1178. break
  1179. }
  1180. }
  1181. s.PutAllCache(userId, userType, allSubPush)
  1182. }
  1183. return nil
  1184. }
  1185. // UserInfo 获取用户信息
  1186. func (s *subscribePush) UserInfo(baseUserId int64) (*map[string]interface{}, int64) {
  1187. user, ok := IC.Mgo.FindOneByField("user", map[string]interface{}{"base_user_id": baseUserId}, `{"i_ts_guide":1,"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}`)
  1188. if !ok || user == nil {
  1189. return nil, 0
  1190. }
  1191. return user, common.Int64All((*user)["l_firstpushtime"])
  1192. }
  1193. // GetKeySet 是否有订阅词
  1194. func GetKeySet(t string, u *map[string]interface{}, data []string) (bool, []string) {
  1195. var industry_ = []string{}
  1196. if u != nil {
  1197. if t == SubFreeFlag {
  1198. o_jy, _ := (*u)["o_jy"].(map[string]interface{})
  1199. a_key, _ := o_jy["a_key"].([]interface{})
  1200. return len(a_key) > 0, industry_
  1201. } else {
  1202. var obj map[string]interface{}
  1203. if t == SubVipFlag {
  1204. obj, _ = (*u)["o_vipjy"].(map[string]interface{})
  1205. } else if t == MemberFlag {
  1206. obj, _ = (*u)["o_member_jy"].(map[string]interface{})
  1207. } else if t == EntnicheFlag {
  1208. if len(data) > 0 {
  1209. return true, data
  1210. } else {
  1211. return false, data
  1212. }
  1213. }
  1214. if obj != nil {
  1215. if buyerclassObj, ok := obj["a_buyerclass"].([]interface{}); ok {
  1216. industry_ = common.ObjArrToStringArr(buyerclassObj)
  1217. }
  1218. itmes, _ := obj["a_items"].([]interface{})
  1219. for _, v := range itmes {
  1220. item, _ := v.(map[string]interface{})
  1221. keys, _ := item["a_key"].([]interface{})
  1222. if len(keys) > 0 {
  1223. return true, industry_
  1224. }
  1225. }
  1226. }
  1227. }
  1228. }
  1229. return false, industry_
  1230. }
  1231. const (
  1232. INDEX = "bidding"
  1233. TYPE = "bidding"
  1234. bidField = `"_id","title","publishtime","toptype","subtype","type","area","city","s_subscopeclass","buyerclass","budget","bidamount","filetext","spidercode","site","buyer","bidopentime","buyertel","buyerperson","agency","agencyperson","agencytel","s_winner","winnerperson","winnertel","signendtime","bidendtime","entidlist"`
  1235. bidField1 = `"_id","title","publishtime","toptype","subtype","type","area","city","s_subscopeclass","buyerclass","budget","bidamount","filetext","spidercode","site","buyer","bidopentime","buyertel","buyerperson","agency","agencyperson","agencytel","s_winner","winnerperson","winnertel","signendtime","bidendtime","entidlist","detail"`
  1236. bidTime = `{"range":{"publishtime":{"gt":%d}}}`
  1237. bidSort = `{"publishtime":"desc"}`
  1238. findfields = `"title"`
  1239. )
  1240. // 首次访问推送页面 默认生成推送数据
  1241. // 默认匹配es 7天内数据
  1242. func (s *subscribePush) DefaultDatas(spqp *SubPushQueryParam, bsp *ViewCondition, userType string) (hasNextPage bool, total int64, result []*bxsubscribe.SubscribeInfo) {
  1243. if spqp.UserId == "" {
  1244. return false, 0, nil
  1245. }
  1246. logx.Info("userId:", spqp.UserId, "newUserId:", spqp.NewUserId)
  1247. t1 := time.Now()
  1248. if len(bsp.Keyword) > 0 {
  1249. logx.Info("--bsp:", bsp)
  1250. //获取查询语句
  1251. qstr := s.getDefaultDatasSQL(bsp)
  1252. // 查询方式包含有正文,返回结果添加正文
  1253. list := elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSort, common.ObjToString(common.If(strings.Contains(strings.Join(bsp.SelectType, ","), "detail"), bidField1, bidField)), 0, bsp.Size, 500, false)
  1254. logx.Info(time.Since(t1), "list count:", len(*list))
  1255. if list != nil && len(*list) > 0 {
  1256. var mlist []map[string]interface{}
  1257. esM := listHistory(spqp)
  1258. if len(esM) > 0 {
  1259. for _, m := range *list {
  1260. if !esM[common.ObjToString(m["_id"])] {
  1261. mlist = append(mlist, m)
  1262. }
  1263. }
  1264. } else {
  1265. mlist = *list
  1266. }
  1267. logx.Info(time.Since(t1), "mlist count:", len(mlist))
  1268. total = int64(len(mlist))
  1269. result = s.listManager(spqp, mlist, bsp.Keyword)
  1270. if len(result) > pageSize {
  1271. result = result[:pageSize]
  1272. hasNextPage = true
  1273. }
  1274. }
  1275. }
  1276. if spqp.SubPushInactive == -1 && spqp.PositionType == 0 && (userType == "vType" || userType == "fType") {
  1277. IC.Mgo.UpdateById("user", spqp.UserId, bson.M{"$set": bson.M{"subpush_inactive": -2}})
  1278. }
  1279. logx.Info("请求耗时:", time.Since(t1))
  1280. return
  1281. }
  1282. // 历史订阅消息
  1283. func listHistory(spqp *SubPushQueryParam) map[string]bool {
  1284. m := make(map[string]bool)
  1285. sql := "SELECT infoid FROM push.pushsubscribe where userid = ? order by date desc, id desc limit 1000;"
  1286. info := spqp.BaseServiceMysql.SelectBySql(sql, spqp.NewUserId)
  1287. for _, m1 := range *info {
  1288. m[common.ObjToString(m1["infoid"])] = true
  1289. }
  1290. return m
  1291. }
  1292. // 保存推送表
  1293. func (s *subscribePush) listManager(spqp *SubPushQueryParam, list []map[string]interface{}, keyword []ViewKeyWord) (resultList []*bxsubscribe.SubscribeInfo) {
  1294. now := time.Now().Unix()
  1295. length := len(list)
  1296. resultList = make([]*bxsubscribe.SubscribeInfo, length)
  1297. pushInsert := []interface{}{}
  1298. var product interface{}
  1299. if spqp.UserType == SubVipFlag {
  1300. product = 1
  1301. } else if spqp.UserType == MemberFlag {
  1302. product = 2
  1303. }
  1304. for i := length - 1; i >= 0; i-- {
  1305. v := list[i]
  1306. title := strings.Replace(common.ObjToString(v["title"]), " ", "", -1)
  1307. infoid := common.InterfaceToStr(v["_id"])
  1308. matchkeys := getKeys(title, keyword)
  1309. matchkey := strings.Join(matchkeys, " ")
  1310. subscopeclassStr := ""
  1311. area := common.If(v["area"] == nil, nil, common.If(common.ObjToString(v["area"]) == "A", 0, common.If(P.BidCodeMapping.Area[common.ObjToString(v["area"])] != "", P.BidCodeMapping.Area[common.ObjToString(v["area"])], 0)))
  1312. city := common.If(P.BidCodeMapping.City[common.ObjToString(v["city"])] == "", nil, P.BidCodeMapping.City[common.ObjToString(v["city"])])
  1313. cityName := common.ObjToString(v["city"])
  1314. district := ""
  1315. districtName := common.ObjToString(v["city"])
  1316. if cityName != "" && districtName != "" {
  1317. district = gconv.String(common.If(P.BidCodeMapping.District[cityName][districtName] == "", nil, P.BidCodeMapping.District[cityName][districtName]))
  1318. }
  1319. subtype := common.If(P.BidCodeMapping.Subtype[common.ObjToString(v["subtype"])] == "", nil, P.BidCodeMapping.Subtype[common.ObjToString(v["subtype"])])
  1320. toptype := common.If(P.BidCodeMapping.Toptype[common.ObjToString(v["toptype"])] == "", nil, P.BidCodeMapping.Toptype[common.ObjToString(v["toptype"])])
  1321. buyerclass := common.If(P.BidCodeMapping.Buyerclass[common.ObjToString(v["buyerclass"])] == "", nil, P.BidCodeMapping.Buyerclass[common.ObjToString(v["buyerclass"])])
  1322. attachment_count := 0
  1323. if v["isValidFile"] != nil {
  1324. isValidFile, _ := v["isValidFile"].(bool)
  1325. attachment_count = common.If(isValidFile, 1, 0).(int)
  1326. }
  1327. bidamount := common.If(v["bidamount"] == nil, nil, v["bidamount"])
  1328. budget := common.If(v["budget"] == nil, nil, v["budget"])
  1329. if s_subscopeclass := common.ObjToString(v["s_subscopeclass"]); s_subscopeclass != "" {
  1330. subscopeclass := []string{}
  1331. for _, v := range strings.Split(s_subscopeclass, ",") {
  1332. if subscopeclass_mapping, ok := P.BidCodeMapping.Subscopeclass[v]; ok {
  1333. subscopeclass = append(subscopeclass, fmt.Sprint(subscopeclass_mapping))
  1334. }
  1335. }
  1336. if len(subscopeclass) > 0 {
  1337. subscopeclassStr = strings.Join(subscopeclass, ",")
  1338. }
  1339. }
  1340. entid := spqp.EntId
  1341. entUserId := spqp.EntUserId
  1342. deptid := spqp.DeptId
  1343. //公共字段处理
  1344. pushInsert = append(pushInsert, common.InterfaceToStr(infoid), matchkey, now, area, city, district, buyerclass, toptype, subtype, subscopeclassStr, budget, bidamount, attachment_count)
  1345. switch s.ModuleFlag {
  1346. case EntnicheFlag:
  1347. pushInsert = append(pushInsert, entUserId, entid, deptid, 1, product)
  1348. case MemberFlag:
  1349. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId))
  1350. case SubVipFlag:
  1351. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId), 1)
  1352. case SubFreeFlag:
  1353. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId), 0)
  1354. }
  1355. redis.Put("pushcache_2_a", fmt.Sprintf("pushinfo_%s_%s", spqp.UserId, common.ObjToString(v["_id"])), 1, 86400)
  1356. redis.Put("pushcache_2_c", fmt.Sprintf("inactiveChange_%s_%s", spqp.UserId, common.ObjToString(v["_id"])), 1, 86400)
  1357. resultList[i] = s.InfoFormat(&PushCa{
  1358. InfoId: infoid,
  1359. Date: time.Now().Unix(),
  1360. Keys: matchkeys,
  1361. FileExists: v["filetext"] != nil,
  1362. }, &v, spqp.IsPayUser, false)
  1363. }
  1364. id := int64(0)
  1365. switch s.ModuleFlag {
  1366. case EntnicheFlag:
  1367. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, ennicheInsertCollKey, pushInsert)
  1368. case MemberFlag:
  1369. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, memberInsertCollKey, pushInsert)
  1370. default:
  1371. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, subscribeInsertCollKey, pushInsert)
  1372. }
  1373. for i := length - 1; i >= 0; i-- {
  1374. resultList[i].CaIndex = id
  1375. id++
  1376. }
  1377. return
  1378. }
  1379. // 获取匹配得关键词
  1380. func getKeys(title string, keywords []ViewKeyWord) (str []string) {
  1381. if len(keywords) > 0 {
  1382. L:
  1383. for _, v := range keywords {
  1384. for _, vk := range v.Keyword {
  1385. if strings.Contains(title, vk) {
  1386. str = append(str, v.Keyword...)
  1387. break L
  1388. }
  1389. }
  1390. for _, va := range v.Appended {
  1391. if strings.Contains(title, va) {
  1392. str = append(str, v.Appended...)
  1393. break L
  1394. }
  1395. }
  1396. }
  1397. }
  1398. return
  1399. }
  1400. // 获取查询语句
  1401. func (s *subscribePush) getFreeDatasSQL(bsp *ViewCondition, startTime, endTime int64, startNumb, size int) (str string) {
  1402. query := `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match": %d}},"_source":[%s],"sort": [{"publishtime": "desc"}],"from":%d,"size":%d}`
  1403. query_bool_should := `{"bool":{"should":[%s],"minimum_should_match": 1}}`
  1404. multi_match := `{"multi_match": {"query": %s,"type": "phrase", "fields": [%s]}}`
  1405. query_bool_must_and := `{"bool":{"must":[%s]%s}}`
  1406. query_bool_must_and_district := `{"bool":{"must":[{"terms":{"city":["%s"]}},{"terms":{"district":["%s"]}}]}}`
  1407. publishtime := `{"range":{"publishtime":{"gt":%d,"lt":%d}}}`
  1408. bools := []string{}
  1409. musts := []string{}
  1410. //发布时间最新15天(正式环境需要修改)
  1411. musts = append(musts, fmt.Sprintf(publishtime, startTime, endTime))
  1412. //省份
  1413. areaCity := []string{}
  1414. if len(bsp.Area) > 0 {
  1415. areaquery := `{"terms":{"area":[`
  1416. for k, v := range bsp.Area {
  1417. if k > 0 {
  1418. areaquery += `,`
  1419. }
  1420. areaquery += `"` + v + `"`
  1421. }
  1422. areaquery += `]}}`
  1423. areaCity = append(areaCity, areaquery)
  1424. }
  1425. //城市
  1426. if len(bsp.City) > 0 {
  1427. areaquery := `{"terms":{"city":[`
  1428. for k, v := range bsp.City {
  1429. if k > 0 {
  1430. areaquery += `,`
  1431. }
  1432. areaquery += `"` + v + `"`
  1433. }
  1434. areaquery += `]}}`
  1435. areaCity = append(areaCity, areaquery)
  1436. }
  1437. //区域处理
  1438. if len(bsp.District) > 0 {
  1439. for _, v := range bsp.District {
  1440. cityName := strings.Split(v, "_")[0]
  1441. districtName := strings.Split(v, "_")[1]
  1442. areaCity = append(areaCity, fmt.Sprintf(query_bool_must_and_district, cityName, districtName))
  1443. }
  1444. }
  1445. if len(areaCity) > 0 {
  1446. musts = append(musts, fmt.Sprintf(query_bool_should, strings.Join(areaCity, ",")))
  1447. }
  1448. if len(bsp.Subtype) > 0 {
  1449. subquery := `{"terms":{"subtype":[`
  1450. for k, v := range bsp.Subtype {
  1451. if k > 0 {
  1452. subquery += `,`
  1453. }
  1454. subquery += `"` + v + `"`
  1455. }
  1456. subquery += `]}}`
  1457. musts = append(musts, subquery)
  1458. }
  1459. if len(bsp.Buyerclass) > 0 {
  1460. Buyerclass := `{"terms":{"buyerclass":[`
  1461. for k, v := range bsp.Buyerclass {
  1462. if k > 0 {
  1463. Buyerclass += `,`
  1464. }
  1465. Buyerclass += `"` + v + `"`
  1466. }
  1467. Buyerclass += `]}}`
  1468. musts = append(musts, Buyerclass)
  1469. }
  1470. /**
  1471. 100-500
  1472. 100-
  1473. -500
  1474. */
  1475. if bsp.Amount != "" {
  1476. at := strings.Split(bsp.Amount, "-")
  1477. if len(at) == 2 {
  1478. Bidamount := `{"range":{"bidamount":{` // "gte": %d, "lte": %d}}}
  1479. if at[0] != "" {
  1480. minPrice := common.Int64All(common.Float64All(at[0]) * 10000) //换成元
  1481. if minPrice >= 0 {
  1482. Bidamount += fmt.Sprintf("\"gte\": %d", minPrice)
  1483. }
  1484. }
  1485. if at[1] != "" {
  1486. maxPrice := common.Int64All(common.Float64All(at[1]) * 10000)
  1487. if maxPrice > 0 {
  1488. Bidamount += fmt.Sprintf(",\"lte\": %d", maxPrice)
  1489. }
  1490. }
  1491. Bidamount += `}}}`
  1492. musts = append(musts, Bidamount)
  1493. }
  1494. }
  1495. boolsNum := 0 //should
  1496. if len(bsp.Keyword) > 0 {
  1497. boolsNum = 1
  1498. stype := strings.Join(bsp.SelectType, "\",\"")
  1499. if strings.Contains(stype, "projectname/purchasing") {
  1500. stype = strings.Replace(stype, "projectname/purchasing", "projectname,\",\"purchasing", -1)
  1501. }
  1502. multi_match = fmt.Sprintf(multi_match, "%s", "\""+stype+"\"")
  1503. for _, v := range bsp.Keyword {
  1504. shoulds := []string{}
  1505. must_not := []string{}
  1506. //附加词
  1507. for _, vv := range v.Keyword {
  1508. vv = strings.TrimSpace(vv)
  1509. if vv == "" {
  1510. continue
  1511. }
  1512. shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
  1513. }
  1514. for _, vv := range v.Appended {
  1515. vv = strings.TrimSpace(vv)
  1516. if vv == "" {
  1517. continue
  1518. }
  1519. shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
  1520. }
  1521. //排除词
  1522. for _, vv := range v.Exclude {
  1523. vv = strings.TrimSpace(vv)
  1524. if vv == "" {
  1525. continue
  1526. }
  1527. must_not = append(must_not, fmt.Sprintf(multi_match, "\""+vv+"\""))
  1528. }
  1529. //添加
  1530. if len(shoulds) > 0 {
  1531. notStr := ""
  1532. if len(must_not) > 0 {
  1533. notStr = fmt.Sprintf(`,"must_not":[%s]`, strings.Join(must_not, ","))
  1534. }
  1535. bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(shoulds, ","), notStr))
  1536. }
  1537. }
  1538. }
  1539. qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum, bidField, startNumb, size)
  1540. logx.Info("----", qstr)
  1541. return qstr
  1542. }
  1543. // 获取查询语句
  1544. func (s *subscribePush) getDefaultDatasSQL(bsp *ViewCondition) (str string) {
  1545. query := `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match": %d}}}`
  1546. query_bool_should := `{"bool":{"should":[%s],"minimum_should_match": 1}}`
  1547. multi_match := `{"multi_match": {"query": %s,"type": "phrase", "fields": [%s]}}`
  1548. query_bool_must_and := `{"bool":{"must":[%s]%s}}`
  1549. query_bool_must_and_district := `{"bool":{"must":[{"terms":{"city":["%s"]}},{"terms":{"district":["%s"]}}]}}`
  1550. bools := []string{}
  1551. musts := []string{}
  1552. //发布时间最新15天(正式环境需要修改)
  1553. musts = append(musts, fmt.Sprintf(bidTime, time.Now().AddDate(0, 0, -15).Unix()))
  1554. //省份
  1555. areaCity := []string{}
  1556. if len(bsp.Area) > 0 {
  1557. areaquery := `{"terms":{"area":[`
  1558. for k, v := range bsp.Area {
  1559. if k > 0 {
  1560. areaquery += `,`
  1561. }
  1562. areaquery += `"` + v + `"`
  1563. }
  1564. areaquery += `]}}`
  1565. areaCity = append(areaCity, areaquery)
  1566. }
  1567. //城市
  1568. if len(bsp.City) > 0 {
  1569. areaquery := `{"terms":{"city":[`
  1570. for k, v := range bsp.City {
  1571. if k > 0 {
  1572. areaquery += `,`
  1573. }
  1574. areaquery += `"` + v + `"`
  1575. }
  1576. areaquery += `]}}`
  1577. areaCity = append(areaCity, areaquery)
  1578. }
  1579. //区域处理
  1580. if len(bsp.District) > 0 {
  1581. for _, v := range bsp.District {
  1582. cityName := strings.Split(v, "_")[0]
  1583. districtName := strings.Split(v, "_")[1]
  1584. areaCity = append(areaCity, fmt.Sprintf(query_bool_must_and_district, cityName, districtName))
  1585. }
  1586. }
  1587. if len(areaCity) > 0 {
  1588. musts = append(musts, fmt.Sprintf(query_bool_should, strings.Join(areaCity, ",")))
  1589. }
  1590. if len(bsp.Subtype) > 0 {
  1591. subquery := `{"terms":{"subtype":[`
  1592. for k, v := range bsp.Subtype {
  1593. if k > 0 {
  1594. subquery += `,`
  1595. }
  1596. subquery += `"` + v + `"`
  1597. }
  1598. subquery += `]}}`
  1599. musts = append(musts, subquery)
  1600. }
  1601. if len(bsp.Buyerclass) > 0 {
  1602. Buyerclass := `{"terms":{"buyerclass":[`
  1603. for k, v := range bsp.Buyerclass {
  1604. if k > 0 {
  1605. Buyerclass += `,`
  1606. }
  1607. Buyerclass += `"` + v + `"`
  1608. }
  1609. Buyerclass += `]}}`
  1610. musts = append(musts, Buyerclass)
  1611. }
  1612. boolsNum := 0 //should
  1613. if len(bsp.Keyword) > 0 {
  1614. boolsNum = 1
  1615. stype := strings.Join(bsp.SelectType, "\",\"")
  1616. if strings.Contains(stype, "projectname/purchasing") {
  1617. stype = strings.Replace(stype, "projectname/purchasing", "projectname,\",\"purchasing", -1)
  1618. }
  1619. multi_match = fmt.Sprintf(multi_match, "%s", "\""+stype+"\"")
  1620. for _, v := range bsp.Keyword {
  1621. shoulds := []string{}
  1622. must_not := []string{}
  1623. //附加词
  1624. for _, vv := range v.Keyword {
  1625. vv = strings.TrimSpace(vv)
  1626. if vv == "" {
  1627. continue
  1628. }
  1629. shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
  1630. }
  1631. for _, vv := range v.Appended {
  1632. vv = strings.TrimSpace(vv)
  1633. if vv == "" {
  1634. continue
  1635. }
  1636. shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
  1637. }
  1638. //排除词
  1639. for _, vv := range v.Exclude {
  1640. vv = strings.TrimSpace(vv)
  1641. if vv == "" {
  1642. continue
  1643. }
  1644. must_not = append(must_not, fmt.Sprintf(multi_match, "\""+vv+"\""))
  1645. }
  1646. //添加
  1647. if len(shoulds) > 0 {
  1648. notStr := ""
  1649. if len(must_not) > 0 {
  1650. notStr = fmt.Sprintf(`,"must_not":[%s]`, strings.Join(must_not, ","))
  1651. }
  1652. bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(shoulds, ","), notStr))
  1653. }
  1654. }
  1655. }
  1656. qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum)
  1657. logx.Info("----", qstr)
  1658. return qstr
  1659. }
  1660. /*已选条件--关键词*/
  1661. type ViewKeyWord struct {
  1662. Keyword []string `json:"key"` //关键词
  1663. Appended []string `json:"appendkey"` //附加词
  1664. Exclude []string `json:"notkey"` //排除词
  1665. MatchWay int `json:"matchway"` //匹配模式
  1666. }
  1667. /*已选条件*/
  1668. type ViewCondition struct {
  1669. Area []string //地区-省份
  1670. City []string //地区-城市
  1671. District []string //区县
  1672. Buyerclass []string //采购行业
  1673. Keyword []ViewKeyWord //关键词
  1674. SelectType []string //筛选
  1675. Subtype []string //信息类型
  1676. Size int //数量
  1677. Amount string //金额
  1678. }
  1679. // 获取用户信息
  1680. func (s *subscribePush) GetUserInfo(spqp *SubPushQueryParam) (vc *ViewCondition) {
  1681. var isPayBool = false
  1682. var tmpInfo = struct {
  1683. Items []interface{}
  1684. BuyerClass []interface{}
  1685. SubType []interface{}
  1686. Area map[string]interface{}
  1687. District map[string]interface{}
  1688. SelectType []string
  1689. Amount string
  1690. }{}
  1691. switch s.ModuleFlag {
  1692. case MemberFlag:
  1693. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_member_jy":1,"i_member_status":1,"i_member_sub_status":1,"s_member_mainid": 1,"subpush_inactive":1}`)
  1694. spqp.SubPushInactive = common.IntAll((*userMap)["subpush_inactive"])
  1695. if !ok || userMap == nil || len(*userMap) == 0 {
  1696. return &ViewCondition{}
  1697. }
  1698. //大会员
  1699. if common.IntAll((*userMap)["i_member_status"]) > 0 {
  1700. isPayBool = true
  1701. if gconv.Int((*userMap)["i_member_sub_status"]) == 1 { // 子账号取主账号订阅设置
  1702. zid := gconv.String((*userMap)["s_member_mainid"])
  1703. userMap, _ = IC.Mgo.FindById("user", zid, `{"o_member_jy":1,"i_member_status":1,"subpush_inactive":1}`)
  1704. }
  1705. o_member_jy, _ := (*userMap)["o_member_jy"].(map[string]interface{})
  1706. tmpInfo.Items, _ = o_member_jy["a_items"].([]interface{})
  1707. tmpInfo.BuyerClass, _ = o_member_jy["a_buyerclass"].([]interface{})
  1708. tmpInfo.SubType, _ = o_member_jy["a_infotype"].([]interface{})
  1709. tmpInfo.Area, _ = o_member_jy["o_area"].(map[string]interface{})
  1710. tmpInfo.District, _ = o_member_jy["o_district"].(map[string]interface{})
  1711. if o_member_jy["i_matchmode"] != nil {
  1712. tmpInfo.SelectType = gconv.SliceStr(o_member_jy["i_matchmode"])
  1713. } else {
  1714. tmpInfo.SelectType = []string{"title"}
  1715. }
  1716. tmpInfo.Amount = common.ObjToString(o_member_jy["amount"])
  1717. }
  1718. case SubVipFlag:
  1719. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_vipjy":1,"i_vip_status":1,"subpush_inactive":1}`)
  1720. spqp.SubPushInactive = common.IntAll((*userMap)["subpush_inactive"])
  1721. if !ok || userMap == nil || len(*userMap) == 0 {
  1722. return &ViewCondition{}
  1723. }
  1724. if common.IntAll((*userMap)["i_vip_status"]) > 0 {
  1725. isPayBool = true
  1726. o_vipjy, _ := (*userMap)["o_vipjy"].(map[string]interface{})
  1727. tmpInfo.Items, _ = o_vipjy["a_items"].([]interface{})
  1728. tmpInfo.BuyerClass, _ = o_vipjy["a_buyerclass"].([]interface{})
  1729. tmpInfo.SubType, _ = o_vipjy["a_infotype"].([]interface{})
  1730. tmpInfo.Area, _ = o_vipjy["o_area"].(map[string]interface{})
  1731. tmpInfo.District, _ = o_vipjy["o_district"].(map[string]interface{})
  1732. if o_vipjy["i_matchmode"] != nil {
  1733. tmpInfo.SelectType = gconv.SliceStr(o_vipjy["i_matchmode"])
  1734. } else {
  1735. tmpInfo.SelectType = []string{"title"}
  1736. }
  1737. tmpInfo.Amount = common.ObjToString(o_vipjy["amount"])
  1738. }
  1739. case EntnicheFlag:
  1740. //商机管理
  1741. entUserId, _ := strconv.Atoi(spqp.EntUserId)
  1742. entId, _ := strconv.Atoi(spqp.EntId)
  1743. entInfo, deptId := (&ms.MatchJob{}).Start(entId, entUserId)
  1744. if entInfo != nil && len(entInfo) > 0 {
  1745. spqp.DeptId = strconv.Itoa(deptId)
  1746. if common.IntAll(entInfo["i_type"]) == 2 {
  1747. if entInfo["a_key"] != nil {
  1748. tmpInfo.Items, _ = entInfo["a_key"].([]interface{})
  1749. //信息类型
  1750. tmpInfo.SubType, _ = entInfo["a_infotype"].([]interface{})
  1751. //省份
  1752. tmpInfo.Area, _ = entInfo["o_area"].(map[string]interface{})
  1753. tmpInfo.District, _ = entInfo["o_district"].(map[string]interface{})
  1754. if entInfo["i_matchmode"] != nil {
  1755. tmpInfo.SelectType = gconv.SliceStr(entInfo["i_matchmode"])
  1756. } else {
  1757. tmpInfo.SelectType = []string{"title"}
  1758. }
  1759. tmpInfo.Amount = common.ObjToString(entInfo["amount"])
  1760. if common.IntAllDef(entInfo["i_ppstatus"], 0) == 1 && entInfo["o_area_p"] != nil {
  1761. tmpInfo.Area, _ = entInfo["o_area_p"].(map[string]interface{})
  1762. }
  1763. }
  1764. } else {
  1765. isPayBool = true
  1766. tmpInfo.Items, _ = entInfo["a_items"].([]interface{})
  1767. tmpInfo.BuyerClass, _ = entInfo["a_buyerclass"].([]interface{})
  1768. tmpInfo.SubType, _ = entInfo["a_infotype"].([]interface{})
  1769. tmpInfo.Area, _ = entInfo["o_area"].(map[string]interface{})
  1770. tmpInfo.District, _ = entInfo["o_district"].(map[string]interface{})
  1771. if entInfo["i_matchmode"] != nil {
  1772. tmpInfo.SelectType = gconv.SliceStr(entInfo["i_matchmode"])
  1773. } else {
  1774. tmpInfo.SelectType = []string{"title"}
  1775. }
  1776. tmpInfo.Amount = common.ObjToString(entInfo["amount"])
  1777. }
  1778. }
  1779. if spqp.IsEnt {
  1780. res_, _ := IC.Mgo.FindOneByField("entniche_rule", map[string]interface{}{
  1781. "i_userid": map[string]interface{}{
  1782. "$exists": false,
  1783. },
  1784. "i_entid": common.Int64All(spqp.EntId),
  1785. }, `{"o_entniche":1}`)
  1786. if res_ != nil && len(*res_) > 0 {
  1787. if m, ok := (*res_)["o_entniche"].(map[string]interface{}); ok {
  1788. if m["i_matchmode"] != nil {
  1789. tmpInfo.SelectType = gconv.SliceStr(m["i_matchmode"])
  1790. } else {
  1791. tmpInfo.SelectType = []string{"title"}
  1792. }
  1793. }
  1794. }
  1795. }
  1796. default:
  1797. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_jy":1,"subpush_inactive":1}`)
  1798. if !ok || userMap == nil || len(*userMap) == 0 {
  1799. return &ViewCondition{}
  1800. }
  1801. spqp.SubPushInactive = common.IntAll((*userMap)["subpush_inactive"])
  1802. o_jy, _ := (*userMap)["o_jy"].(map[string]interface{})
  1803. if o_jy["a_key"] != nil {
  1804. tmpInfo.Items, _ = o_jy["a_key"].([]interface{})
  1805. //信息类型
  1806. tmpInfo.SubType, _ = o_jy["a_infotype"].([]interface{})
  1807. //省份
  1808. tmpInfo.Area, _ = o_jy["o_area"].(map[string]interface{})
  1809. tmpInfo.District, _ = o_jy["o_district"].(map[string]interface{})
  1810. if o_jy["i_matchmode"] != nil {
  1811. tmpInfo.SelectType = gconv.SliceStr(o_jy["i_matchmode"])
  1812. } else {
  1813. tmpInfo.SelectType = []string{"title"}
  1814. }
  1815. tmpInfo.Amount = common.ObjToString(o_jy["amount"])
  1816. if common.IntAllDef(o_jy["i_ppstatus"], 0) == 1 && o_jy["o_area_p"] != nil {
  1817. tmpInfo.Area, _ = o_jy["o_area_p"].(map[string]interface{})
  1818. }
  1819. }
  1820. }
  1821. vc = &ViewCondition{
  1822. Buyerclass: common.ObjArrToStringArr(tmpInfo.BuyerClass),
  1823. Subtype: common.ObjArrToStringArr(tmpInfo.SubType),
  1824. Area: getStringArrFromDbResult(tmpInfo.Area, 1),
  1825. City: getStringArrFromDbResult(tmpInfo.Area, 2),
  1826. District: districtHandle(tmpInfo.District),
  1827. SelectType: tmpInfo.SelectType,
  1828. Amount: tmpInfo.Amount,
  1829. }
  1830. //付费用户
  1831. if isPayBool {
  1832. vc.Size = IC.C.DefaulCount.Pay
  1833. vc.Keyword = getKeyWordArrFromDbResult(tmpInfo.Items, "", -1)
  1834. } else {
  1835. vc.Size = IC.C.DefaulCount.Free
  1836. vc.Keyword = getKeyWordArrFromDbResultByFree(tmpInfo.Items, "", -1)
  1837. }
  1838. return
  1839. }
  1840. // 区县处理
  1841. func districtHandle(data map[string]interface{}) []string {
  1842. arr := []string{}
  1843. for k, v := range data {
  1844. for _, v1 := range gconv.SliceAny(v) {
  1845. arr = append(arr, fmt.Sprintf("%s_%s", k, v1))
  1846. }
  1847. }
  1848. return arr
  1849. } // 关键词 附加词 排除词
  1850. func getKeyWordArrFromDbResult(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
  1851. if a_items == nil {
  1852. return
  1853. }
  1854. for _, v := range a_items {
  1855. vm, _ := v.(map[string]interface{})
  1856. if item != "" && index >= 0 && item != common.ObjToString(vm["s_item"]) {
  1857. continue
  1858. }
  1859. kwsArr := vm["a_key"]
  1860. for i, k := range kwsArr.([]interface{}) {
  1861. if item != "" && index >= 0 && i != index {
  1862. continue
  1863. }
  1864. kw := ViewKeyWord{}
  1865. b, e := json.Marshal(k)
  1866. if e != nil {
  1867. log.Println(e.Error())
  1868. }
  1869. json.Unmarshal(b, &kw)
  1870. if kw.MatchWay == 1 {
  1871. for _, kk := range kw.Keyword {
  1872. arr = append(arr, ViewKeyWord{
  1873. Keyword: []string{kk},
  1874. Exclude: kw.Exclude,
  1875. })
  1876. }
  1877. for _, kk := range kw.Appended {
  1878. arr = append(arr, ViewKeyWord{
  1879. Keyword: []string{kk},
  1880. Exclude: kw.Exclude,
  1881. })
  1882. }
  1883. } else {
  1884. arr = append(arr, kw)
  1885. }
  1886. }
  1887. }
  1888. return
  1889. }
  1890. // //关键词 附加词 排除词 省份订阅包 - 普通用户
  1891. func getKeyWordArrFromDbResultByFree(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
  1892. if a_items == nil {
  1893. return
  1894. }
  1895. for _, v := range a_items {
  1896. kw := ViewKeyWord{}
  1897. b, e := json.Marshal(v)
  1898. if e != nil {
  1899. log.Println(e.Error())
  1900. }
  1901. json.Unmarshal(b, &kw)
  1902. if kw.MatchWay == 1 {
  1903. for _, kk := range kw.Keyword {
  1904. arr = append(arr, ViewKeyWord{
  1905. Keyword: []string{kk},
  1906. Exclude: kw.Exclude,
  1907. })
  1908. }
  1909. for _, kk := range kw.Appended {
  1910. arr = append(arr, ViewKeyWord{
  1911. Keyword: []string{kk},
  1912. Exclude: kw.Exclude,
  1913. })
  1914. }
  1915. } else {
  1916. arr = append(arr, kw)
  1917. }
  1918. }
  1919. return
  1920. }
  1921. // 地区格式化
  1922. func getStringArrFromDbResult(area map[string]interface{}, i int) (arr []string) {
  1923. if area == nil {
  1924. return
  1925. }
  1926. var eareArr []string
  1927. var cityArr []string
  1928. for k, v := range area {
  1929. if len(v.([]interface{})) > 0 {
  1930. cityArr = append(cityArr, common.ObjArrToStringArr(v.([]interface{}))...)
  1931. } else {
  1932. eareArr = append(eareArr, k)
  1933. }
  1934. }
  1935. if i == 1 {
  1936. arr = eareArr
  1937. } else {
  1938. arr = cityArr
  1939. }
  1940. return
  1941. }
  1942. // IsInTsGuide 是否进入向导
  1943. func (s *subscribePush) IsInTsGuide(userid string) bool {
  1944. if userid == "" {
  1945. return false
  1946. }
  1947. data, ok := IC.Mgo.FindById("user", userid, `{"o_jy":1,"i_ts_guide":1,"":1,"i_member_status":1,"i_vip_status":1}`)
  1948. if ok {
  1949. //付费用户无免费订阅,不进入订阅向导页面
  1950. if common.IntAll((*data)["i_member_status"]) > 0 || common.IntAll((*data)["i_vip_status"]) > 0 {
  1951. return false
  1952. }
  1953. o_jy, _ := (*data)["o_jy"].(map[string]interface{})
  1954. i_ts_guide := common.IntAll((*data)["i_ts_guide"])
  1955. if i_ts_guide == 2 || (i_ts_guide == 0 && len(o_jy) == 0) {
  1956. return true
  1957. }
  1958. }
  1959. return false
  1960. }
  1961. func (s *subscribePush) Keys(spqp *KeyParam) (result []*bxsubscribe.KeyItems) {
  1962. keyData := map[string][]interface{}{}
  1963. if spqp.IsEnt {
  1964. //企业关键词查找
  1965. res_, _ := IC.Mgo.Find("entniche_rule", map[string]interface{}{
  1966. "i_userid": map[string]interface{}{
  1967. "$exists": false,
  1968. },
  1969. "i_entid": common.Int64All(spqp.EntId),
  1970. }, "", `{"o_entniche":1}`, false, -1, -1)
  1971. o_entniche := map[string]interface{}{}
  1972. if res_ == nil || len(*res_) == 0 {
  1973. return MapToarr(keyData)
  1974. }
  1975. for _, ruleV := range *res_ {
  1976. o_entniche = common.StructToMapMore(ruleV["o_entniche"])
  1977. if o_entniche["a_items"] != nil {
  1978. a_item := common.ObjArrToMapArr(o_entniche["a_items"].([]interface{}))
  1979. for _, v := range a_item {
  1980. if v["a_key"] != nil {
  1981. a_key_arr := v["a_key"].([]interface{})
  1982. s_item := common.InterfaceToStr(v["s_item"])
  1983. if keyData[s_item] != nil {
  1984. //第一次搜索存在
  1985. //去重
  1986. keyData[s_item] = MergeArray(a_key_arr, keyData[s_item])
  1987. } else {
  1988. //第一次搜索不存在
  1989. keyData[s_item] = a_key_arr
  1990. }
  1991. }
  1992. }
  1993. }
  1994. }
  1995. } else {
  1996. //个人关键词查找
  1997. //fType:普通用户;vType:超级订阅用户;mType:大会员用户;eType:商机管理用户
  1998. types := 2
  1999. typeKey := ""
  2000. switch s.ModuleFlag {
  2001. case SubVipFlag:
  2002. types = 1
  2003. typeKey = "o_vipjy"
  2004. case MemberFlag:
  2005. types = 1
  2006. typeKey = "o_member_jy"
  2007. case EntnicheFlag:
  2008. types = 0
  2009. typeKey = "o_entniche"
  2010. case SubFreeFlag:
  2011. types = 2
  2012. typeKey = "o_jy"
  2013. }
  2014. if spqp.PositionType == 1 {
  2015. typeKey = "o_entniche"
  2016. }
  2017. o_entniche := &map[string]interface{}{}
  2018. if spqp.PositionType == 0 {
  2019. mData, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_jy":1,"o_vipjy":1,"o_member_jy":1,""i_member_sub_status":1,"s_member_mainid":1}`)
  2020. if mData == nil || len(*mData) == 0 || !ok {
  2021. return nil
  2022. }
  2023. if s.ModuleFlag == MemberFlag {
  2024. sub_status := common.Int64All((*mData)["i_member_sub_status"])
  2025. if sub_status == 1 {
  2026. //大会员子账号处理
  2027. mData, ok = IC.Mgo.FindById("user", common.InterfaceToStr((*mData)["s_member_mainid"]), `{"o_jy":1,"o_vipjy":1,"o_member_jy":1,""i_member_sub_status":1,"s_member_mainid":1}`)
  2028. if mData == nil || len(*mData) == 0 || !ok {
  2029. return nil
  2030. }
  2031. }
  2032. }
  2033. o_entniche = common.ObjToMap((*mData)[typeKey])
  2034. } else {
  2035. res_, _ := IC.Mgo.FindOneByField("entniche_rule", map[string]interface{}{
  2036. "i_userid": common.Int64All(spqp.EntUserId),
  2037. "i_entid": common.Int64All(spqp.EntId),
  2038. "i_type": types,
  2039. }, `{"o_entniche":1}`)
  2040. if res_ != nil {
  2041. o_entniche = common.ObjToMap((*res_)["o_entniche"])
  2042. }
  2043. }
  2044. if s.ModuleFlag == SubVipFlag {
  2045. //从user表中取 o_vipjy.a_items
  2046. if (*o_entniche)["a_items"] != nil {
  2047. a_items := common.ObjArrToMapArr((*o_entniche)["a_items"].([]interface{}))
  2048. for _, v := range a_items {
  2049. if v["a_key"] != nil {
  2050. a_key_arr := v["a_key"].([]interface{})
  2051. keyData[common.InterfaceToStr(v["s_item"])] = a_key_arr
  2052. }
  2053. }
  2054. }
  2055. } else if s.ModuleFlag == MemberFlag {
  2056. //从user表中取 o_member_jy.a_items
  2057. //o_memeberjy := common.ObjToMap((*mData)["o_member_jy"])
  2058. if (*o_entniche)["a_items"] != nil {
  2059. a_items := common.ObjArrToMapArr((*o_entniche)["a_items"].([]interface{}))
  2060. for _, v := range a_items {
  2061. if v["a_key"] != nil {
  2062. a_key_arr := v["a_key"].([]interface{})
  2063. keyData[common.InterfaceToStr(v["s_item"])] = a_key_arr
  2064. }
  2065. }
  2066. }
  2067. } else if s.ModuleFlag == EntnicheFlag {
  2068. res_, _ := IC.Mgo.FindOneByField("entniche_rule", map[string]interface{}{
  2069. "i_userid": common.Int64All(spqp.EntUserId),
  2070. "i_entid": common.Int64All(spqp.EntId),
  2071. "i_type": types,
  2072. }, `{"o_entniche":1}`)
  2073. o_entniche := &map[string]interface{}{}
  2074. if res_ != nil {
  2075. o_entniche = common.ObjToMap((*res_)["o_entniche"])
  2076. }
  2077. if (*o_entniche)["a_items"] != nil {
  2078. a_item := common.ObjArrToMapArr((*o_entniche)["a_items"].([]interface{}))
  2079. for _, v := range a_item {
  2080. if v["a_key"] != nil {
  2081. a_key_arr := v["a_key"].([]interface{})
  2082. keyData[common.InterfaceToStr(v["s_item"])] = a_key_arr
  2083. }
  2084. }
  2085. }
  2086. } else {
  2087. //免费用户
  2088. a_key, _ := (*o_entniche)["a_key"].([]interface{})
  2089. if len(a_key) > 0 {
  2090. for _, v := range a_key {
  2091. if keyData["未分类"] != nil {
  2092. keyData["未分类"] = append(keyData["未分类"], v)
  2093. } else {
  2094. keyData["未分类"] = []interface{}{v}
  2095. }
  2096. }
  2097. }
  2098. }
  2099. if spqp.PositionType == 1 && s.ModuleFlag != SubFreeFlag {
  2100. //1、mysql entniche_user_rule表中获取自己的分发规则id
  2101. data := IC.MainMysql.SelectBySql(`SELECT rule_id FROM entniche_user_rule a
  2102. INNER JOIN entniche_department b ON a.dept_id = b.id AND a.user_id =?
  2103. ORDER BY b.pid
  2104. LIMIT 1 `, spqp.EntUserId)
  2105. if data == nil || len(*data) == 0 {
  2106. return MapToarr(keyData)
  2107. }
  2108. ruleId := common.ObjToString((*data)[0]["rule_id"])
  2109. //3、entniche_distribute表,查询条件:{_id:ObjectId(1结果中的分发规则id),i_status:0},取 o_entniche.a_items,这个查到的是分类名称,然后到上面1的结果中获取这个分类下的词
  2110. res, _ := IC.Mgo.FindById("entniche_distribute", ruleId, nil)
  2111. if res == nil || len(*res) == 0 {
  2112. return MapToarr(keyData)
  2113. }
  2114. entItem := (*res)["a_items"].([]interface{})
  2115. if (*res)["a_items"] == nil {
  2116. return MapToarr(keyData)
  2117. }
  2118. //2、entniche_rule表, 企业订阅关键词查询条件: {i_entid:123,i_deptid:0},取 o_entniche.a_items
  2119. deptid := common.Int64All((*res)["i_deptid"])
  2120. ruleMap := map[string]interface{}{
  2121. "i_entid": common.Int64All(spqp.EntId),
  2122. }
  2123. if deptid == 0 {
  2124. ruleMap["i_deptid"] = map[string]interface{}{"$exists": false}
  2125. ruleMap["i_userid"] = map[string]interface{}{"$exists": false}
  2126. } else {
  2127. ruleMap["i_deptid"] = deptid
  2128. }
  2129. res_, _ := IC.Mgo.FindOneByField("entniche_rule", ruleMap, `{"o_entniche":1}`)
  2130. o_entniche := &map[string]interface{}{}
  2131. if res_ != nil {
  2132. o_entniche = common.ObjToMap((*res_)["o_entniche"])
  2133. }
  2134. entnicheRule := map[string][]interface{}{}
  2135. if (*o_entniche)["a_items"] != nil {
  2136. a_item := common.ObjArrToMapArr((*o_entniche)["a_items"].([]interface{}))
  2137. for _, v := range a_item {
  2138. if v["a_key"] != nil {
  2139. a_key_arr := v["a_key"].([]interface{})
  2140. entnicheRule[common.InterfaceToStr(v["s_item"])] = a_key_arr
  2141. }
  2142. }
  2143. }
  2144. for _, value := range entItem {
  2145. v := common.InterfaceToStr(value)
  2146. if entnicheRule[v] != nil {
  2147. if keyData[v] != nil {
  2148. //第一次搜索存在
  2149. //去重
  2150. keyData[v] = MergeArray(keyData[v], entnicheRule[v])
  2151. } else {
  2152. //第一次搜索不存在
  2153. keyData[v] = entnicheRule[v]
  2154. }
  2155. }
  2156. }
  2157. }
  2158. }
  2159. return MapToarr(keyData)
  2160. }
  2161. // 关键词处理
  2162. func KeyHandle(a_items map[string]interface{}) []interface{} {
  2163. keyArr := []interface{}{}
  2164. if a_items["a_key"] != nil {
  2165. a_key_arr := common.ObjArrToMapArr(a_items["a_key"].([]interface{}))
  2166. for _, vv := range a_key_arr {
  2167. for _, v := range vv["key"].([]interface{}) {
  2168. keyArr = append(keyArr, v)
  2169. }
  2170. }
  2171. }
  2172. return keyArr
  2173. }
  2174. func MapToarr(data map[string][]interface{}) []*bxsubscribe.KeyItems {
  2175. result := []*bxsubscribe.KeyItems{}
  2176. for k, v := range data {
  2177. keyArr := []*bxsubscribe.Key{}
  2178. for _, m := range common.ObjArrToMapArr(v) {
  2179. keys := &bxsubscribe.Key{}
  2180. if m["notkey"] != nil {
  2181. keys.Notkey = common.ObjArrToStringArr(m["notkey"].([]interface{}))
  2182. }
  2183. if m["key"] != nil {
  2184. keys.Key = common.ObjArrToStringArr(m["key"].([]interface{}))
  2185. }
  2186. if m["matchway"] != nil {
  2187. keys.Matchway = common.Int64All(m["matchway"])
  2188. }
  2189. if m["appendkey"] != nil {
  2190. keys.Appendkey = common.ObjArrToStringArr(m["appendkey"].([]interface{}))
  2191. }
  2192. keyArr = append(keyArr, keys)
  2193. }
  2194. result = append(result, &bxsubscribe.KeyItems{
  2195. AKey: keyArr,
  2196. SItem: k,
  2197. })
  2198. }
  2199. return result
  2200. }
  2201. func MergeArray(dest []interface{}, src []interface{}) (result []interface{}) {
  2202. data := map[string]interface{}{}
  2203. for _, v := range common.ObjArrToMapArr(dest) {
  2204. notkey := ""
  2205. key := ""
  2206. matchway := ""
  2207. appendkey := ""
  2208. if v["notkey"] != nil {
  2209. otkeyArr := common.ObjArrToStringArr(v["notkey"].([]interface{}))
  2210. for _, keyV := range otkeyArr {
  2211. if common.InterfaceToStr(keyV) != "" {
  2212. notkey += fmt.Sprintf(",%s", common.InterfaceToStr(keyV))
  2213. }
  2214. }
  2215. }
  2216. if v["key"] != nil {
  2217. keyArr := common.ObjArrToStringArr(v["key"].([]interface{}))
  2218. for _, keyV := range keyArr {
  2219. if common.InterfaceToStr(keyV) != "" {
  2220. key += fmt.Sprintf(",%s", common.InterfaceToStr(keyV))
  2221. }
  2222. }
  2223. }
  2224. if v["matchway"] != nil {
  2225. matchway = common.InterfaceToStr(v["matchway"])
  2226. }
  2227. if v["appendkey"] != nil {
  2228. appendkeyArr := common.ObjArrToStringArr(v["appendkey"].([]interface{}))
  2229. for _, keyV := range appendkeyArr {
  2230. if common.InterfaceToStr(keyV) != "" {
  2231. appendkey += fmt.Sprintf(",%s", common.InterfaceToStr(keyV))
  2232. }
  2233. }
  2234. }
  2235. k := fmt.Sprintf("%s_____%s_____%s_____%s", notkey, key, matchway, appendkey)
  2236. data[k] = v
  2237. }
  2238. for _, v := range common.ObjArrToMapArr(src) {
  2239. notkey := ""
  2240. key := ""
  2241. matchway := ""
  2242. appendkey := ""
  2243. if v["notkey"] != nil {
  2244. otkeyArr := common.ObjArrToStringArr(v["notkey"].([]interface{}))
  2245. for _, keyV := range otkeyArr {
  2246. if common.InterfaceToStr(keyV) != "" {
  2247. notkey += fmt.Sprintf(",%s", common.InterfaceToStr(keyV))
  2248. }
  2249. }
  2250. }
  2251. if v["key"] != nil {
  2252. keyArr := common.ObjArrToStringArr(v["key"].([]interface{}))
  2253. for _, keyV := range keyArr {
  2254. if common.InterfaceToStr(keyV) != "" {
  2255. key += fmt.Sprintf(",%s", common.InterfaceToStr(keyV))
  2256. }
  2257. }
  2258. }
  2259. if v["matchway"] != nil {
  2260. matchway = common.InterfaceToStr(v["matchway"])
  2261. }
  2262. if v["appendkey"] != nil {
  2263. appendkeyArr := common.ObjArrToStringArr(v["appendkey"].([]interface{}))
  2264. for _, keyV := range appendkeyArr {
  2265. if common.InterfaceToStr(keyV) != "" {
  2266. appendkey += fmt.Sprintf(",%s", common.InterfaceToStr(keyV))
  2267. }
  2268. }
  2269. }
  2270. k := fmt.Sprintf("%s_____%s_____%s_____%s", notkey, key, matchway, appendkey)
  2271. data[k] = v
  2272. }
  2273. for _, v := range data {
  2274. result = append(result, v)
  2275. }
  2276. return
  2277. }
  2278. func (s *subscribePush) ItemToKey(in *SubPushQueryParam) string {
  2279. moduleFlag := s.ModuleFlag
  2280. s.ModuleFlag = in.UserType
  2281. spqp := KeyParam{
  2282. UserId: in.UserId,
  2283. EntUserId: in.EntUserId,
  2284. DeptId: in.DeptId,
  2285. NewUserId: in.NewUserId,
  2286. IsEnt: in.IsEnt,
  2287. EntId: in.EntId,
  2288. PositionType: in.PositionType,
  2289. }
  2290. //所有关键词获取
  2291. keyItemsArr := s.Keys(&spqp)
  2292. s.ModuleFlag = moduleFlag
  2293. keyArr := []string{}
  2294. if len(keyItemsArr) > 0 {
  2295. for _, k1 := range keyItemsArr {
  2296. for _, k2 := range strings.Split(in.Item, ",") {
  2297. if k1.SItem == k2 {
  2298. if len(k1.AKey) > 0 {
  2299. for _, k3 := range k1.AKey {
  2300. key := ""
  2301. if len(k3.Key) > 0 {
  2302. key = strings.Join(k3.Key, " ")
  2303. }
  2304. if len(k3.Appendkey) > 0 {
  2305. if key != "" {
  2306. key += " " + strings.Join(k3.Appendkey, " ")
  2307. } else {
  2308. key = strings.Join(k3.Appendkey, " ")
  2309. }
  2310. }
  2311. if k3.Matchway == 1 {
  2312. //模糊处理
  2313. key = strings.ReplaceAll(key, " ", ",")
  2314. } else {
  2315. //精准处理
  2316. key = strings.ReplaceAll(key, " ", "+")
  2317. }
  2318. keyArr = append(keyArr, key)
  2319. }
  2320. }
  2321. }
  2322. }
  2323. }
  2324. }
  2325. return strings.Join(keyArr, ",")
  2326. }
  2327. func (s *SubPushQueryParam) ExportPushFormat() (ids, keyWords []string) {
  2328. if len(s.SelectInfoIds) > 0 {
  2329. for ik, id := range s.SelectInfoIds {
  2330. if xid := util.DecodeId(id); len(xid) > 0 {
  2331. ids = append(ids, xid)
  2332. if len(s.SelectKeys) > ik {
  2333. keyWords = append(keyWords, strings.ReplaceAll(s.SelectKeys[ik], " ", ","))
  2334. } else {
  2335. keyWords = append(keyWords, "")
  2336. }
  2337. }
  2338. }
  2339. }
  2340. return
  2341. }
  2342. // @Author jianghan
  2343. // @Description clickhouse获取推荐的列表数据
  2344. // @Date 2024/3/11
  2345. func (s *subscribePush) SubRecList(userId string, keyword []ViewKeyWord) (hasNextPage bool, total int64, resultList []*bxsubscribe.SubscribeInfo) {
  2346. sql := "select bitmapToArray(infoids) infoids, userid from jianyu.sub_recommend_list where userid = ?"
  2347. infos := IC.CkJy.SelectBySql(sql, userId)
  2348. if infos != nil && len(*infos) > 0 {
  2349. if ids, ok := (*infos)[0]["infoids"].([]uint64); ok && len(ids) > 0 {
  2350. length := len(ids)
  2351. resultList = make([]*bxsubscribe.SubscribeInfo, length)
  2352. esq := `{"query": {"bool": {"must": [{"terms": {"autoid": [` + strings.Join(gconv.Strings(ids), ",") + ` ]}}]}}}`
  2353. binfo := elastic.GetAllByNgram(INDEX, TYPE, esq, findfields, bidSort, bidField, 0, 100, length, false)
  2354. if binfo != nil && len(*binfo) > 0 {
  2355. for i, m := range *binfo {
  2356. title := strings.Replace(common.ObjToString(m["title"]), " ", "", -1)
  2357. matchkeys := getKeys(title, keyword)
  2358. resultList[i] = s.InfoFormat(&PushCa{
  2359. InfoId: mongodb.BsonIdToSId(m["_id"]),
  2360. Date: time.Now().Unix(),
  2361. Keys: matchkeys,
  2362. FileExists: m["filetext"] != nil,
  2363. }, &m, false, false)
  2364. }
  2365. }
  2366. total = int64(len(resultList))
  2367. if total > pageSize {
  2368. resultList = resultList[:pageSize]
  2369. hasNextPage = true
  2370. }
  2371. }
  2372. }
  2373. return
  2374. }
  2375. // @Author jianghan
  2376. // @Description es获取最新10条数据
  2377. // @Date 2024/3/13
  2378. func (s *subscribePush) GetRecListByEs() (hasNextPage bool, total int64, resultList []*bxsubscribe.SubscribeInfo) {
  2379. resultList = make([]*bxsubscribe.SubscribeInfo, 10)
  2380. if jsonStr := redis.GetStr("pushcache_2_c", "bid_sub_recommend"); jsonStr != "" {
  2381. var data []map[string]interface{}
  2382. _ = json.Unmarshal([]byte(jsonStr), &data)
  2383. for i := 0; i < 10; i++ {
  2384. resultList[i] = s.InfoFormat(&PushCa{
  2385. InfoId: common.ObjToString(data[i]["_id"]),
  2386. Date: time.Now().Unix(),
  2387. Keys: []string{},
  2388. FileExists: data[i]["filetext"] != nil,
  2389. }, &data[i], false, false)
  2390. }
  2391. } else {
  2392. qstr := `{"query": {"bool": {"must": [{"match_all": {}}]}}}`
  2393. list := elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSort, bidField, 0, 10, 10, false)
  2394. redis.Put("pushcache_2_c", "bid_sub_recommend", 1, 86400)
  2395. for i := 0; i < len(*list); i++ {
  2396. resultList[i] = s.InfoFormat(&PushCa{
  2397. InfoId: common.ObjToString((*list)[i]["_id"]),
  2398. Date: time.Now().Unix(),
  2399. Keys: []string{},
  2400. FileExists: (*list)[i]["filetext"] != nil,
  2401. }, &(*list)[i], false, false)
  2402. }
  2403. }
  2404. total = int64(len(resultList))
  2405. if total > pageSize {
  2406. resultList = resultList[:pageSize]
  2407. hasNextPage = true
  2408. }
  2409. return
  2410. }