push.go 75 KB

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