push.go 76 KB

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