push.go 87 KB

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