push.go 87 KB

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