push.go 88 KB

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