push.go 87 KB

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