push.go 89 KB

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