push.go 65 KB

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