push.go 88 KB

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