push.go 86 KB

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