push.go 88 KB

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