push.go 88 KB

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