push.go 86 KB

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