push.go 75 KB

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