push.go 78 KB

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