push.go 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790
  1. package model
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. IC "jyBXSubscribe/rpc/init"
  7. ms "jyBXSubscribe/rpc/model/service"
  8. "jyBXSubscribe/rpc/type/bxsubscribe"
  9. "log"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "app.yhyue.com/moapp/jybase/common"
  15. "app.yhyue.com/moapp/jybase/date"
  16. "app.yhyue.com/moapp/jybase/encrypt"
  17. "app.yhyue.com/moapp/jybase/esv1"
  18. "app.yhyue.com/moapp/jybase/mongodb"
  19. "app.yhyue.com/moapp/jybase/mysql"
  20. "app.yhyue.com/moapp/jybase/redis"
  21. "bp.jydev.jianyu360.cn/BaseService/jyCodeService/rpc/codeservice/codeservice"
  22. "github.com/zeromicro/go-zero/core/logx"
  23. "go.mongodb.org/mongo-driver/bson/primitive"
  24. )
  25. const (
  26. pageSize = 100
  27. AllSubPushCacheSize = 200
  28. query = `{"query":{"terms":{"_id":["%s"]}},"_source":["_id","area", "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"],"from":0,"size":%d}`
  29. mongodb_fields = `{"_id":1,"area":1,"publishtime":1,"s_subscopeclass":1,"subtype":1,"title":1,"toptype":1,"type":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}`
  30. SubFreeFlag = "fType"
  31. SubVipFlag = "vType"
  32. MemberFlag = "mType"
  33. EntnicheFlag = "eType"
  34. oneDay = 24 * 60 * 60
  35. Baseinfo = "global_common_data.dws_f_bid_baseinfo"
  36. BidTags = "global_common_data.dws_f_bid_tags"
  37. )
  38. var (
  39. ennicheInsertCollKey = []string{"entid", "deptid", "userid", "infoid", "matchkeys", "date", "source", "product"}
  40. subscribeInsertCollKey = []string{"userid", "infoid", "matchkeys", "date", "isvip"}
  41. memberInsertCollKey = []string{"userid", "infoid", "matchkeys", "date"}
  42. )
  43. var aboutDbMsg map[string]*AboutDbMsg = map[string]*AboutDbMsg{
  44. SubFreeFlag: &AboutDbMsg{"pushsubscribe", "subpush"},
  45. SubVipFlag: &AboutDbMsg{"pushsubscribe", "subpush"},
  46. MemberFlag: &AboutDbMsg{"pushmember", "memberpush"},
  47. EntnicheFlag: &AboutDbMsg{"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. }
  70. // 查询参数
  71. type SubPushQueryParam struct {
  72. Mgo_bidding mongodb.MongodbSim //
  73. Bidding string //
  74. Bidding_back string //
  75. UserId string //用户id
  76. PageNum int //页面
  77. PageSize int //每页数量
  78. SelectTime string //时间
  79. Area string //区域
  80. City string //城市
  81. Buyerclass string //采购单位行业
  82. Subtype string //信息类型 二级分类
  83. Subscopeclass string //信息行业
  84. Key string //订阅词
  85. Export bool //导出
  86. EntId string //企业id
  87. Price string //价格
  88. FileExists string //是否有附件;默认全部;1:有附件;-1:无附件
  89. EntUserId string //商机管理用户id
  90. DeptId string //商机管理用户部门id
  91. IsRead string //是否已读
  92. Source string //信息来源
  93. Staffs []string //分发人员
  94. BaseServiceMysql *mysql.Mysql
  95. NewUserId int64
  96. IsEnt bool
  97. SelectInfoIds []string
  98. BuySubject int64
  99. UserType string
  100. PositionType int64
  101. IsPayUser bool // 是否是付费用户
  102. }
  103. // 关键词参数
  104. type KeyParam struct {
  105. UserId string //用户id
  106. EntUserId string //商机管理用户id
  107. DeptId string //商机管理用户部门id
  108. NewUserId int64
  109. IsEnt bool
  110. VipPower int64
  111. EntId string //企业id
  112. MemberPower int64
  113. PowerSource int64
  114. UserPower int64
  115. PositionType int64
  116. }
  117. func (spqp *SubPushQueryParam) IsEmpty() bool {
  118. return (spqp.SelectTime == "" || spqp.SelectTime == "all") && spqp.Area == "" && spqp.City == "" && spqp.Buyerclass == "" && spqp.Subscopeclass == "" && spqp.Subtype == "" && spqp.Key == "" && spqp.Price == "" && spqp.FileExists == "" && len(spqp.Staffs) == 0 && spqp.Source == "" && spqp.IsRead == ""
  119. }
  120. type subscribePush struct {
  121. ModuleFlag string
  122. }
  123. func NewSubscribePush(module ...string) *subscribePush {
  124. m := ""
  125. if len(module) > 0 {
  126. m = module[0]
  127. }
  128. return &subscribePush{m}
  129. }
  130. // 从pushcache_2_a中取
  131. func (s *subscribePush) GetTodayCache(userId, userType string) (*SubPush, error) {
  132. pc_a, err := redis.GetNewBytes("pushcache_2_b", s.todayKey(userId, userType))
  133. if err != nil {
  134. return nil, err
  135. }
  136. if pc_a == nil {
  137. return nil, nil
  138. }
  139. var p *SubPush
  140. if err := json.Unmarshal(*pc_a, &p); err != nil {
  141. return nil, err
  142. }
  143. return p, nil
  144. }
  145. // 往pushcache_2_a中放
  146. func (s *subscribePush) PutTodayCache(userId, userType string, pc_a *SubPush) {
  147. redis.Put("pushcache_2_b", s.todayKey(userId, userType), pc_a, oneDay)
  148. }
  149. // 获取redis key
  150. func (s *subscribePush) todayKey(userId, userType string) string {
  151. if userType == EntnicheFlag {
  152. return fmt.Sprintf("%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, userId)
  153. } else {
  154. return fmt.Sprintf("%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, userId)
  155. }
  156. }
  157. func (s *subscribePush) allKey(userId, userType string) string {
  158. if s.ModuleFlag == EntnicheFlag {
  159. switch userType {
  160. case SubVipFlag:
  161. return fmt.Sprintf("all_%s_%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, "vip", userId)
  162. case MemberFlag:
  163. return fmt.Sprintf("all_%s_%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, "member", userId)
  164. case SubFreeFlag:
  165. return fmt.Sprintf("all_%s_%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, "free", userId)
  166. }
  167. }
  168. return fmt.Sprintf("all_%s_%s", aboutDbMsg[s.ModuleFlag].RedisKeyFlag, userId)
  169. }
  170. // 历史推送记录中单条信息格式化
  171. func (s *subscribePush) InfoFormat(p *PushCa, info *map[string]interface{}, isPay bool) *bxsubscribe.SubscribeInfo {
  172. area := common.ObjToString((*info)["area"])
  173. if area == "A" {
  174. area = "全国"
  175. }
  176. industry := common.ObjToString((*info)["s_subscopeclass"])
  177. scs := strings.Split(industry, ",")
  178. if len(scs) > 0 {
  179. industry = scs[0]
  180. if industry != "" {
  181. iss := strings.Split(industry, "_")
  182. if len(iss) > 0 {
  183. industry = iss[0]
  184. }
  185. }
  186. }
  187. infotype := common.ObjToString((*info)["subtype"])
  188. if infotype == "" {
  189. infotype = common.ObjToString((*info)["toptype"])
  190. }
  191. _id := p.InfoId
  192. if _id == "" {
  193. _id = common.ObjToString((*info)["_id"])
  194. }
  195. formatInfo := &bxsubscribe.SubscribeInfo{
  196. XId: encrypt.EncodeArticleId2ByCheck(_id),
  197. Title: common.InterfaceToStr((*info)["title"]),
  198. Area: area,
  199. BuyerClass: common.InterfaceToStr((*info)["buyerclass"]),
  200. Subtype: infotype,
  201. Industry: industry,
  202. PublishTime: common.Int64All((*info)["publishtime"]),
  203. CaIndex: p.Index,
  204. CaDate: p.Date,
  205. CaIsvisit: int64(p.Visit),
  206. CaIsvip: int64(p.Isvip),
  207. CaType: int64(p.Type),
  208. MatchKeys: p.Keys,
  209. Budget: common.Float64All((*info)["budget"]),
  210. BidAmount: common.Float64All((*info)["bidamount"]),
  211. Buyer: common.InterfaceToStr((*info)["buyer"]),
  212. ProjectName: common.InterfaceToStr((*info)["projectname"]),
  213. Winner: common.InterfaceToStr((*info)["s_winner"]),
  214. BidOpenTime: common.Int64All((*info)["bidopentime"]),
  215. CaFileExists: p.FileExists,
  216. Source: p.Source,
  217. Site: common.InterfaceToStr((*info)["site"]),
  218. SpiderCode: common.InterfaceToStr((*info)["spidercode"]),
  219. }
  220. // 免费用户返回精简列表字段
  221. if !isPay {
  222. return formatInfo
  223. }
  224. winnerList := common.InterfaceToStr((*info)["s_winner"]) //中标企业名称集合
  225. if winnerList != "" && len(strings.Split(winnerList, ",")) > 0 {
  226. for wk, wv := range strings.Split(winnerList, ",") {
  227. var (
  228. winnerId = ""
  229. )
  230. if (*info)["entidlist"] != nil {
  231. if entIdList := common.ObjArrToStringArr((*info)["entidlist"].([]interface{})); len(entIdList) > wk { //中标企业id集合
  232. winnerId = entIdList[wk]
  233. }
  234. }
  235. formatInfo.WinnerInfo = append(formatInfo.WinnerInfo, &bxsubscribe.WinnerInfo{
  236. Winner: wv, //中标企业 需要单独处理
  237. WinnerTel: common.ObjToString((*info)["winnertel"]), //中标企业联系电话
  238. WinnerPerson: common.ObjToString((*info)["winnerperson"]), //中标企业联系人
  239. WinnerId: common.If(winnerId != "" && len([]rune(winnerId)) > 12, encrypt.EncodeArticleId2ByCheck(winnerId), "").(string), //中标企业加密id 存在winnerId 异常的情况
  240. })
  241. }
  242. }
  243. // 付费用户返回详细列表字段
  244. formatInfo.BuyerTel = common.ObjToString((*info)["buyertel"])
  245. formatInfo.BuyerPerson = common.ObjToString((*info)["buyerperson"])
  246. formatInfo.Agency = common.ObjToString((*info)["agency"])
  247. formatInfo.AgencyPerson = common.ObjToString((*info)["agencyperson"])
  248. formatInfo.AgencyTel = common.ObjToString((*info)["agencytel"])
  249. formatInfo.SignendTime = common.Int64All((*info)["signendtime"])
  250. formatInfo.BidendTime = common.Int64All((*info)["bidendtime"])
  251. return formatInfo
  252. }
  253. func (s *subscribePush) Datas(spqp *SubPushQueryParam) (hasNextPage bool, total int64, result []*bxsubscribe.SubscribeInfo) {
  254. logx.Info(spqp.UserId, spqp.NewUserId, s.ModuleFlag, "subscribePush query param:", "SelectTime:", spqp.SelectTime, "Area:", spqp.Area, "City:", spqp.City, "Subtype:", spqp.Subtype, "Subscopeclass:", spqp.Subscopeclass, "Buyerclass:", spqp.Buyerclass, "Key:", spqp.Key, "PageNum:", spqp.PageNum, "Price:", spqp.Price, "FileExists:", spqp.FileExists)
  255. if spqp.UserId == "" {
  256. return
  257. }
  258. if spqp.PageNum < 1 {
  259. spqp.PageNum = 1
  260. }
  261. if spqp.PageSize < 1 || spqp.PageSize > pageSize {
  262. if !spqp.Export {
  263. spqp.PageSize = pageSize
  264. } else { //数据导出查询20000条限制
  265. if spqp.PageSize < 1 || spqp.PageSize > 20000 {
  266. spqp.PageSize = 20000
  267. }
  268. }
  269. }
  270. starttime, endtime := int64(0), int64(0)
  271. if len(strings.Split(spqp.SelectTime, "_")) == 2 {
  272. st := strings.Split(spqp.SelectTime, "_")[0]
  273. et := strings.Split(spqp.SelectTime, "_")[1]
  274. if st != "" && et != "" {
  275. starttime, _ = strconv.ParseInt(st, 0, 64)
  276. endtime, _ = strconv.ParseInt(et, 0, 64)
  277. if endtime > 0 {
  278. etTime := time.Unix(endtime, 0)
  279. endtime = time.Date(etTime.Year(), etTime.Month(), etTime.Day(), 23, 59, 59, 0, time.Local).Unix()
  280. }
  281. }
  282. }
  283. nowFormat := date.NowFormat(date.Date_Short_Layout)
  284. start := (spqp.PageNum - 1) * spqp.PageSize
  285. end := start + spqp.PageSize
  286. //时间是今天,没有别的过滤条件--首先读取当前推送缓存数据 其次查询数据库
  287. if nowFormat == date.FormatDateByInt64(&starttime, date.Date_Short_Layout) && spqp.Area == "" && spqp.City == "" && spqp.Buyerclass == "" && spqp.Subscopeclass == "" && spqp.Subtype == "" && spqp.Key == "" && spqp.Price == "" && spqp.FileExists == "" && len(spqp.Staffs) == 0 && spqp.Source == "" && spqp.IsRead == "" && len(spqp.SelectInfoIds) == 0 {
  288. subPush := &SubPush{}
  289. var err error
  290. if spqp.IsEnt == false {
  291. subPush, err = s.GetTodayCache(spqp.UserId, spqp.UserType)
  292. }
  293. if err != nil {
  294. logx.Info(spqp.UserId, "GetTodayCache Error", err)
  295. }
  296. if err != nil || subPush == nil || subPush.Date != nowFormat || len(subPush.Datas) == 0 {
  297. list, countSearch := s.getDatasFromMysql(spqp, starttime, endtime, spqp.PageSize, false)
  298. subPush = &SubPush{
  299. Date: nowFormat,
  300. Datas: list,
  301. Count: countSearch,
  302. }
  303. if spqp.IsEnt == false {
  304. s.PutTodayCache(spqp.UserId, spqp.UserType, subPush)
  305. }
  306. }
  307. length := len(subPush.Datas)
  308. if end > length {
  309. end = length
  310. }
  311. if start < length {
  312. result = subPush.Datas[start:end]
  313. } else {
  314. result = subPush.Datas
  315. }
  316. total = int64(length)
  317. //全部,没有过滤条件 之前缓存500
  318. } else if spqp.IsEmpty() && (spqp.PageNum-1)*spqp.PageSize < 200 && len(spqp.SelectInfoIds) == 0 && !spqp.Export { //全部,没有过滤条件 之前缓存5页*50条=250 非数据导出
  319. allCache := &SubPush{}
  320. var err error
  321. if !spqp.IsEnt {
  322. allCache, err = s.GetAllCache(spqp.UserId, spqp.UserType)
  323. }
  324. if err != nil {
  325. logx.Info(spqp.UserId, "GetAllCache Error", err)
  326. }
  327. if err != nil || allCache == nil || allCache.Date != nowFormat || len(allCache.Datas) == 0 {
  328. list, countSearch := []*bxsubscribe.SubscribeInfo{}, int64(0)
  329. if spqp.IsEnt {
  330. list, countSearch = s.getDatasFromMysql(spqp, starttime, endtime, spqp.PageSize, true)
  331. } else {
  332. spqp.PageNum = 1
  333. list, countSearch = s.getDatasFromMysql(spqp, starttime, endtime, AllSubPushCacheSize, true)
  334. }
  335. allCache = &SubPush{
  336. Date: nowFormat,
  337. Datas: list,
  338. Count: countSearch,
  339. }
  340. if spqp.IsEnt == false {
  341. s.PutAllCache(spqp.UserId, spqp.UserType, allCache)
  342. }
  343. }
  344. length := len(allCache.Datas)
  345. if end > length {
  346. end = length
  347. }
  348. if start < length {
  349. result = allCache.Datas[start:end]
  350. } else {
  351. result = allCache.Datas
  352. }
  353. total = allCache.Count
  354. } else {
  355. result, total = s.getDatasFromMysql(spqp, starttime, endtime, spqp.PageSize, true)
  356. }
  357. if result == nil {
  358. result = []*bxsubscribe.SubscribeInfo{}
  359. }
  360. hasNextPage = len(result) >= spqp.PageSize
  361. return
  362. }
  363. func (s *subscribePush) getDatasFromMysql(spqp *SubPushQueryParam, starttime, endtime int64, size int, isLimit bool) (result []*bxsubscribe.SubscribeInfo, count int64) {
  364. querys := []string{}
  365. userStr := " "
  366. leftJoinStr := " "
  367. var (
  368. countSql, findSql string
  369. )
  370. codeMap, err := IC.CodeLib.CodeTransformation(context.Background(), &codeservice.Request{})
  371. if codeMap.Data == nil || err != nil {
  372. logx.Error("代码表获取失败")
  373. return result, count
  374. }
  375. querys = append(querys, " 1=1 ")
  376. if spqp.SelectInfoIds != nil && len(spqp.SelectInfoIds) > 0 {
  377. countSql = fmt.Sprintf("select count(1) as count from %s a LEFT JOIN %s b ON a.infoid = b.infoid where %s", aboutDbMsg[s.ModuleFlag].MysqlTable, Baseinfo, fmt.Sprintf("a.id in ('%s')", strings.Join(spqp.SelectInfoIds, "','")))
  378. logx.Info("countSql", countSql)
  379. findSql = fmt.Sprintf("select a.id,a.date,a.infoid,a.isvisit,a.matchkeys,a.type,b.isvalidfile as attachment_count from %s a LEFT JOIN %s b ON a.infoid = b.infoid where %s order by a.date desc,a.id desc", aboutDbMsg[s.ModuleFlag].MysqlTable, Baseinfo, fmt.Sprintf("a.id in ('%s')", strings.Join(spqp.SelectInfoIds, "','")))
  380. //查询总数
  381. count = spqp.BaseServiceMysql.CountBySql(countSql)
  382. } else {
  383. //公共查询条件
  384. //时间
  385. if starttime > 0 && endtime > 0 {
  386. userStr += fmt.Sprintf(" and a.date>=%d and a.date<=%d", starttime, endtime)
  387. } else if starttime > 0 && endtime == 0 {
  388. userStr += fmt.Sprintf(" and a.date>=%d", starttime)
  389. } else if starttime == 0 && endtime > 0 {
  390. userStr += fmt.Sprintf(" and a.date<=%d", endtime)
  391. }
  392. if spqp.Area != "" || spqp.City != "" {
  393. var sqlAreaCity = ""
  394. //城市
  395. city := []string{}
  396. for _, v := range strings.Split(spqp.City, ",") {
  397. if codeMap.Data.City[v] != "" {
  398. city = append(city, fmt.Sprint(codeMap.Data.City[v]))
  399. } else {
  400. city = append(city, "-1")
  401. }
  402. }
  403. if len(city) == 1 {
  404. city = append(city, "9999")
  405. }
  406. if len(city) > 0 {
  407. sqlAreaCity = fmt.Sprintf("b.city_code in (%s)", strings.Join(city, ","))
  408. }
  409. //区域
  410. var sqlArea = ""
  411. area := []string{}
  412. for _, v := range strings.Split(spqp.Area, ",") {
  413. if codeMap.Data.Area[v] != "" {
  414. area = append(area, fmt.Sprint(codeMap.Data.Area[v]))
  415. } else {
  416. area = append(area, "-1")
  417. }
  418. }
  419. if len(area) == 1 {
  420. area = append(area, "9999")
  421. }
  422. if len(area) > 0 {
  423. sqlArea = fmt.Sprintf("b.area_code in (%s)", strings.Join(area, ","))
  424. }
  425. if sqlAreaCity != "" && sqlArea != "" {
  426. sqlAreaCity = "( " + sqlAreaCity + " or " + sqlArea + " )"
  427. } else if sqlAreaCity == "" && sqlArea != "" {
  428. sqlAreaCity = sqlArea
  429. }
  430. if sqlAreaCity != "" {
  431. querys = append(querys, sqlAreaCity)
  432. }
  433. }
  434. //采购单位行业
  435. if spqp.Buyerclass != "" {
  436. buyerclass := []string{}
  437. for _, v := range strings.Split(spqp.Buyerclass, ",") {
  438. if codeMap.Data.Buyerclass[v] != "" {
  439. buyerclass = append(buyerclass, fmt.Sprint(codeMap.Data.Buyerclass[v]))
  440. }
  441. }
  442. if len(buyerclass) == 1 {
  443. buyerclass = append(buyerclass, "9999")
  444. }
  445. if len(buyerclass) > 0 {
  446. querys = append(querys, fmt.Sprintf("b.buyerclass_code in (%s)", strings.Join(buyerclass, ",")))
  447. }
  448. }
  449. //信息类型
  450. if spqp.Subtype != "" {
  451. subtype := []string{}
  452. for _, v := range strings.Split(spqp.Subtype, ",") {
  453. if codeMap.Data.Subtype[v] != "" {
  454. subtype = append(subtype, fmt.Sprint(codeMap.Data.Subtype[v]))
  455. }
  456. }
  457. if len(subtype) == 1 {
  458. subtype = append(subtype, "9999")
  459. }
  460. if len(subtype) > 0 {
  461. querys = append(querys, fmt.Sprintf("b.subtype_code in (%s)", strings.Join(subtype, ",")))
  462. }
  463. }
  464. //信息行业
  465. if spqp.Subscopeclass != "" {
  466. find_in_set := []string{}
  467. for _, v := range strings.Split(spqp.Subscopeclass, ",") {
  468. if codeMap.Data.Subscopeclass[v] != "" {
  469. find_in_set = append(find_in_set, codeMap.Data.Subscopeclass[v])
  470. }
  471. }
  472. if len(find_in_set) > 0 {
  473. leftJoinStr = fmt.Sprintf(" STRAIGHT_JOIN %s t on t.infoid = b.infoid and t.labelcode=2 ", BidTags)
  474. querys = append(querys, fmt.Sprintf(" t.labelvalues in (%s)", strings.Join(find_in_set, ",")))
  475. }
  476. }
  477. //关键词
  478. if spqp.Key != "" {
  479. find_in_set := []string{}
  480. for _, v := range strings.Split(spqp.Key, ",") {
  481. find_in_set = append(find_in_set, fmt.Sprintf("find_in_set('%s',replace(replace(a.matchkeys,'+',','),' ',','))", v))
  482. }
  483. if len(find_in_set) == 1 {
  484. querys = append(querys, find_in_set[0])
  485. } else if len(find_in_set) > 1 {
  486. querys = append(querys, fmt.Sprintf("(%s)", strings.Join(find_in_set, " or ")))
  487. }
  488. }
  489. //价格- 预算和中标金额
  490. if spqp.Price != "" && strings.Contains(spqp.Price, "-") {
  491. minPriceStr, maxPriceStr := strings.Split(spqp.Price, "-")[0], strings.Split(spqp.Price, "-")[1]
  492. minPrice := common.Int64All(common.Float64All(minPriceStr) * 10000) //换成元
  493. maxPrice := common.Int64All(common.Float64All(maxPriceStr) * 10000) //换成元
  494. if minPriceStr != "" && maxPriceStr != "" {
  495. querys = append(querys, fmt.Sprintf("((b.bidamount>=%d and b.bidamount<=%d) or (b.budget>=%d and b.budget<=%d and b.bidamount is null))", minPrice, maxPrice, minPrice, maxPrice))
  496. } else if minPriceStr != "" {
  497. querys = append(querys, fmt.Sprintf("(b.bidamount>=%d or (b.budget>=%d and b.bidamount is null))", minPrice, minPrice))
  498. } else if maxPriceStr != "" {
  499. querys = append(querys, fmt.Sprintf("(b.bidamount<=%d or (b.budget<=%d and b.bidamount is null))", maxPrice, maxPrice))
  500. }
  501. }
  502. //附件
  503. if spqp.FileExists != "" {
  504. if spqp.FileExists == "1" {
  505. querys = append(querys, fmt.Sprintf("b.isvalidfile =1 "))
  506. } else if spqp.FileExists == "-1" {
  507. querys = append(querys, fmt.Sprintf("b.isvalidfile =0 "))
  508. }
  509. }
  510. if spqp.IsEnt {
  511. var staffs []string
  512. userStr += fmt.Sprintf(" and a.entid='%s' ", spqp.EntId)
  513. //判断是企业管理员还是部门管理员 部门管理员获取所有子部门
  514. userEnt := EntInfo(common.IntAll(spqp.EntId), common.IntAll(spqp.EntUserId))
  515. if !(userEnt.Role_admin_system || userEnt.Role_admin_department) {
  516. result = []*bxsubscribe.SubscribeInfo{}
  517. return
  518. }
  519. if userEnt.Role_admin_department { //部门管理员 获取所有部门和子部门员工
  520. users := GetDisUsers(common.IntAll(spqp.EntId), userEnt.Dept.Id)
  521. if users != nil && len(*users) > 0 {
  522. for _, v := range *users {
  523. if len(spqp.Staffs) > 0 {
  524. for _, vv := range spqp.Staffs {
  525. if fmt.Sprintf("%d", v.Id) == vv {
  526. staffs = append(staffs, common.InterfaceToStr(v.Id))
  527. }
  528. }
  529. } else {
  530. staffs = append(staffs, common.InterfaceToStr(v.Id))
  531. }
  532. }
  533. } else {
  534. log.Printf("部门管理员为获取到部门员工:%s", spqp.EntUserId)
  535. result = []*bxsubscribe.SubscribeInfo{}
  536. return
  537. }
  538. } else if len(spqp.Staffs) > 0 {
  539. staffs = spqp.Staffs
  540. }
  541. //老板商机管理需要查询全部来源
  542. isNew := true
  543. //商机管理判断
  544. newCount := IC.MainMysql.CountBySql("select count(id) from entniche_info where id =? and isNew != 1 and status=1", spqp.EntId)
  545. if newCount > 0 {
  546. isNew = false
  547. }
  548. // 无查询分配人员、是否已读
  549. if spqp.IsRead == "" && len(staffs) == 0 {
  550. //查询数量(需要去重)
  551. countSql = fmt.Sprintf("select count(1) from %s a STRAIGHT_JOIN %s b ON a.infoid = b.infoid %s where %s %s %s", aboutDbMsg[s.ModuleFlag].MysqlTable, Baseinfo, leftJoinStr, strings.Join(querys, " and "), userStr, common.If(isNew, " and a.source = 2 ", ""))
  552. //列表查询
  553. findSql = fmt.Sprintf("select a.id,a.infoid,a.matchkeys,b.isvalidfile as attachment_count from %s a STRAIGHT_JOIN %s b ON a.infoid = b.infoid %s where %s %s %s order by a.date desc,a.id desc",
  554. aboutDbMsg[s.ModuleFlag].MysqlTable, Baseinfo, leftJoinStr, strings.Join(querys, " and "), userStr, common.If(isNew, " and a.source = 2 ", ""))
  555. } else {
  556. //查询分配人员或是否已读
  557. staffQuery := " 1=1 "
  558. if len(staffs) > 0 {
  559. staffQuery += fmt.Sprintf(" and a.userid in ('%s') ", strings.Join(staffs, "','"))
  560. }
  561. if spqp.IsRead != "" {
  562. if spqp.IsRead == "0" {
  563. staffQuery += " and a.isvisit IS NULL"
  564. } else if spqp.IsRead == "1" {
  565. staffQuery += " and a.isvisit=1"
  566. }
  567. }
  568. countSql = fmt.Sprintf("select count(1) from %s a STRAIGHT_JOIN %s b ON a.infoid = b.infoid %s where %s %s %s and ((%s) or EXISTS (SELECT 1 from %s c STRAIGHT_JOIN %s b ON c.infoid = b.infoid %s WHERE c.source=3 %s and %s and a.id=c.pid and (%s))) ", aboutDbMsg[s.ModuleFlag].MysqlTable, Baseinfo, leftJoinStr, strings.Join(querys, " and "), userStr, common.If(isNew, " and a.source = 2 ", ""), staffQuery, aboutDbMsg[s.ModuleFlag].MysqlTable, Baseinfo, leftJoinStr, strings.ReplaceAll(userStr, "a.", "c."), strings.Join(querys, " and "), strings.ReplaceAll(staffQuery, "a.", "c."))
  569. //列表查询
  570. findSql = fmt.Sprintf("select a.id,a.infoid,a.matchkeys,b.isvalidfile as attachment_count from %s a STRAIGHT_JOIN %s b ON a.infoid = b.infoid %s where %s %s %s and ((%s) or EXISTS (SELECT 1 from %s c STRAIGHT_JOIN %s b ON c.infoid = b.infoid %s WHERE c.source=3 %s and %s and a.id=c.pid and (%s))) order by a.date desc,a.id desc ", aboutDbMsg[s.ModuleFlag].MysqlTable, Baseinfo, leftJoinStr, strings.Join(querys, " and "), userStr, common.If(isNew, " and a.source = 2 ", ""), staffQuery, aboutDbMsg[s.ModuleFlag].MysqlTable, Baseinfo, leftJoinStr, strings.ReplaceAll(userStr, "a.", "c."), strings.Join(querys, " and "), strings.ReplaceAll(staffQuery, "a.", "c."))
  571. }
  572. } else {
  573. // 是否已读
  574. if spqp.IsRead != "" {
  575. if spqp.IsRead == "0" {
  576. userStr += " and a.isvisit IS NULL"
  577. } else if spqp.IsRead == "1" {
  578. userStr += " and a.isvisit=1"
  579. }
  580. }
  581. // 信息来源
  582. if spqp.Source == "1" || spqp.Source == "2" || spqp.Source == "3" {
  583. userStr += " and a.source=" + spqp.Source
  584. }
  585. if spqp.PositionType == 1 {
  586. //企业主体是企业的个人查询
  587. if spqp.UserType == SubVipFlag {
  588. 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)))
  589. } else if spqp.UserType == MemberFlag {
  590. 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)))
  591. } else if spqp.UserType == EntnicheFlag {
  592. 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)))
  593. } else {
  594. userStr += fmt.Sprintf(" and a.userid='%s' ", common.If(s.ModuleFlag == EntnicheFlag, spqp.EntUserId, common.InterfaceToStr(spqp.NewUserId)))
  595. }
  596. } else {
  597. if s.ModuleFlag == EntnicheFlag {
  598. //老商机管理个人订阅查询
  599. userStr += fmt.Sprintf(" and a.userid='%s' and a.product is null", common.If(s.ModuleFlag == EntnicheFlag, spqp.EntUserId, common.InterfaceToStr(spqp.NewUserId)))
  600. } else {
  601. //个人订阅查询
  602. userStr += fmt.Sprintf(" and a.userid='%s'", common.If(s.ModuleFlag == EntnicheFlag, spqp.EntUserId, common.InterfaceToStr(spqp.NewUserId)))
  603. }
  604. }
  605. //查询数量
  606. countSql = fmt.Sprintf("select count(1) as count from %s a STRAIGHT_JOIN %s b ON a.infoid = b.infoid %s where 1=1 %s and %s", aboutDbMsg[s.ModuleFlag].MysqlTable, Baseinfo, leftJoinStr, userStr, strings.Join(querys, " and "))
  607. //列表查询语句
  608. findSql = "select a.id,a.date,a.infoid,a.isvisit,a.matchkeys,a.type,b.isvalidfile as attachment_count"
  609. if s.ModuleFlag == EntnicheFlag {
  610. findSql += ", IF(a.source is NULL,1,a.source) as source "
  611. }
  612. if s.ModuleFlag != MemberFlag && s.ModuleFlag != EntnicheFlag {
  613. findSql += ",a.isvip"
  614. }
  615. findSql = fmt.Sprintf("%s from %s a STRAIGHT_JOIN %s b ON 1=1 %s and a.infoid = b.infoid %s where %s"+
  616. " order by a.date desc,a.id desc", findSql, aboutDbMsg[s.ModuleFlag].MysqlTable, Baseinfo, userStr, leftJoinStr, strings.Join(querys, " and "))
  617. }
  618. //查询总数
  619. logx.Info("countSql", countSql)
  620. count = spqp.BaseServiceMysql.CountBySql(countSql)
  621. }
  622. if isLimit {
  623. findSql += fmt.Sprintf(" limit %d,%d", (spqp.PageNum-1)*size, size)
  624. }
  625. logx.Info(spqp.NewUserId, "subscribePush query sql:", findSql)
  626. list := spqp.BaseServiceMysql.SelectBySql(findSql)
  627. if list != nil && len(*list) > 0 {
  628. pushCas := s.GetJyPushs(*list)
  629. if !spqp.Export {
  630. result = s.GetInfoByIds(spqp.Mgo_bidding, spqp.Bidding, spqp.Bidding_back, pushCas, spqp.IsPayUser)
  631. } else {
  632. result = s.GetOnlyExportInfo(pushCas)
  633. }
  634. } else {
  635. result = []*bxsubscribe.SubscribeInfo{}
  636. }
  637. return
  638. }
  639. // GetOnlyInfoId 获取信息id
  640. func (s *subscribePush) GetOnlyExportInfo(pushCas []*PushCa) []*bxsubscribe.SubscribeInfo {
  641. array := make([]*bxsubscribe.SubscribeInfo, len(pushCas))
  642. for k, v := range pushCas {
  643. array[k] = &bxsubscribe.SubscribeInfo{XId: encrypt.EncodeArticleId2ByCheck(v.InfoId), MatchKeys: v.Keys}
  644. }
  645. return array
  646. }
  647. // 根据id取内容
  648. func (s *subscribePush) GetInfoByIds(Mgo_bidding mongodb.MongodbSim, bidding, bidding_back string, pushCas []*PushCa, isPay bool) []*bxsubscribe.SubscribeInfo {
  649. array := make([]*bxsubscribe.SubscribeInfo, len(pushCas))
  650. if len(pushCas) == 0 {
  651. return array
  652. }
  653. m := map[string]bool{}
  654. ids := []string{}
  655. for _, v := range pushCas {
  656. if m[v.InfoId] {
  657. continue
  658. }
  659. m[v.InfoId] = true
  660. ids = append(ids, v.InfoId)
  661. }
  662. infos := map[string]map[string]interface{}{}
  663. //redis
  664. pool := make(chan bool, 3)
  665. wait := &sync.WaitGroup{}
  666. lock := &sync.Mutex{}
  667. es_ids := []string{}
  668. for _, vv := range ids {
  669. pool <- true
  670. wait.Add(1)
  671. go func(v string) {
  672. defer func() {
  673. <-pool
  674. wait.Done()
  675. }()
  676. //剑鱼程序未找到赋值 位置;猜测在推送程序中
  677. info_i := redis.Get("pushcache_1", fmt.Sprintf("info_%s", v))
  678. lock.Lock()
  679. defer lock.Unlock()
  680. if info_i != nil {
  681. info_m, _ := info_i.(map[string]interface{})
  682. info_m["_id"] = v
  683. infos[v] = info_m
  684. } else {
  685. es_ids = append(es_ids, v)
  686. }
  687. }(vv)
  688. }
  689. wait.Wait()
  690. //elasticsearch
  691. if len(es_ids) > 0 {
  692. list := elastic.Get("bidding", "bidding", fmt.Sprintf(query, strings.Join(es_ids, `","`), len(es_ids)))
  693. if list != nil {
  694. for _, v := range *list {
  695. _id := common.ObjToString(v["_id"])
  696. infos[_id] = v
  697. }
  698. }
  699. }
  700. //mongodb bidding
  701. mgo_ids := []primitive.ObjectID{}
  702. for _, v := range es_ids {
  703. if infos[v] == nil {
  704. _id, _ := primitive.ObjectIDFromHex(v)
  705. mgo_ids = append(mgo_ids, _id)
  706. }
  707. }
  708. if len(mgo_ids) > 0 {
  709. list, ok := Mgo_bidding.Find(bidding, map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_ids}}, nil, mongodb_fields, false, -1, -1)
  710. if ok && *list != nil {
  711. for _, v := range *list {
  712. _id := mongodb.BsonIdToSId(v["_id"])
  713. v["_id"] = _id
  714. infos[_id] = v
  715. }
  716. }
  717. }
  718. //mongodb bidding_back
  719. mgo_back_ids := []primitive.ObjectID{}
  720. for _, v := range mgo_ids {
  721. if infos[mongodb.BsonIdToSId(v)] == nil {
  722. mgo_back_ids = append(mgo_back_ids, v)
  723. }
  724. }
  725. if len(mgo_back_ids) > 0 {
  726. list, ok := Mgo_bidding.Find(bidding_back, map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_back_ids}}, nil, mongodb_fields, false, -1, -1)
  727. if ok && *list != nil {
  728. for _, v := range *list {
  729. _id := mongodb.BsonIdToSId(v["_id"])
  730. v["_id"] = _id
  731. infos[_id] = v
  732. }
  733. }
  734. }
  735. for k, v := range pushCas {
  736. info := infos[v.InfoId]
  737. if info == nil {
  738. info = map[string]interface{}{}
  739. }
  740. array[k] = s.InfoFormat(v, &info, isPay)
  741. }
  742. return array
  743. }
  744. // 获取历史推送
  745. func (s *subscribePush) GetJyPushs(datas []map[string]interface{}) (pushCas []*PushCa) {
  746. pushCas = []*PushCa{}
  747. for _, v := range datas {
  748. keys := []string{}
  749. if matchkeys := common.ObjToString(v["matchkeys"]); matchkeys != "" {
  750. keys = strings.Split(matchkeys, " ")
  751. }
  752. pushCas = append(pushCas, &PushCa{
  753. Date: common.Int64All(v["date"]),
  754. InfoId: common.ObjToString(v["infoid"]),
  755. Visit: common.IntAll(v["isvisit"]),
  756. Index: common.Int64All(v["id"]),
  757. Keys: keys,
  758. Type: common.IntAll(v["type"]),
  759. Isvip: common.IntAll(v["isvip"]),
  760. FileExists: common.IntAll(v["attachment_count"]) > 0,
  761. Source: common.Int64All(v["source"]),
  762. })
  763. }
  764. return
  765. }
  766. // 查看全部列表缓存
  767. func (s *subscribePush) PutAllCache(userId, userType string, datas *SubPush) {
  768. redis.Put("pushcache_2_a", s.allKey(userId, userType), datas, oneDay)
  769. }
  770. func (s *subscribePush) GetAllCache(userId, userType string) (*SubPush, error) {
  771. return s.GetCache("pushcache_2_a", s.allKey(userId, userType))
  772. }
  773. func (s *subscribePush) GetCache(code, key string) (*SubPush, error) {
  774. pc_a, err := redis.GetNewBytes(code, key)
  775. if err != nil {
  776. return nil, err
  777. }
  778. if pc_a == nil {
  779. return nil, nil
  780. }
  781. var p *SubPush
  782. if err := json.Unmarshal(*pc_a, &p); err != nil {
  783. return nil, err
  784. }
  785. return p, nil
  786. }
  787. // 是否收藏
  788. func (s *subscribePush) MakeCollection(userId string, list []*bxsubscribe.SubscribeInfo) {
  789. if list == nil || len(list) == 0 {
  790. return
  791. }
  792. param := []interface{}{userId}
  793. wh := []string{}
  794. for _, v := range list {
  795. array := encrypt.DecodeArticleId2ByCheck(v.XId)
  796. if len(array) == 1 && array[0] != "" {
  797. param = append(param, array[0])
  798. wh = append(wh, "?")
  799. }
  800. }
  801. if len(wh) > 0 {
  802. result := IC.MainMysql.SelectBySql(`select bid from bdcollection where userid=? and bid in (`+strings.Join(wh, ",")+`)`, param...)
  803. bid_map := map[string]bool{}
  804. if result != nil {
  805. for _, v := range *result {
  806. bid_map[encrypt.EncodeArticleId2ByCheck(common.ObjToString(v["bid"]))] = true
  807. }
  808. }
  809. for _, v := range list {
  810. if bid_map[v.XId] {
  811. v.Collection = 1
  812. }
  813. }
  814. }
  815. }
  816. // 仅移动端首页使用,历史推送7天信息
  817. func (s *subscribePush) sevenDayKey(userId string) string {
  818. return fmt.Sprintf("7day_subpush_%s", userId)
  819. }
  820. func (s *subscribePush) PutSevenDayCache(userId string, datas []*bxsubscribe.SubscribeInfo) {
  821. redis.Put("pushcache_2_a", s.sevenDayKey(userId), SubPush{Datas: datas}, 7*24*60*60)
  822. }
  823. // 从pushcache_2_a中取
  824. func (s *subscribePush) GetSevenDayCache(userId string) ([]*bxsubscribe.SubscribeInfo, error) {
  825. allPush, _ := s.GetCache("pushcache_2_a", s.sevenDayKey(userId))
  826. if allPush != nil && allPush.Datas != nil && len(allPush.Datas) > 0 {
  827. return allPush.Datas, nil
  828. }
  829. return nil, nil
  830. }
  831. // 历史推送记录中单条信息格式化
  832. func InfoFormats(info map[string]interface{}, tmp map[string]interface{}) map[string]interface{} {
  833. area := common.ObjToString(info["area"])
  834. if area == "A" {
  835. area = "全国"
  836. }
  837. industry := common.ObjToString(info["s_subscopeclass"])
  838. scs := strings.Split(industry, ",")
  839. if len(scs) > 0 {
  840. industry = scs[0]
  841. if industry != "" {
  842. iss := strings.Split(industry, "_")
  843. if len(iss) > 0 {
  844. industry = iss[0]
  845. }
  846. }
  847. }
  848. infotype := common.ObjToString(info["subtype"])
  849. if infotype == "" {
  850. infotype = common.ObjToString(info["toptype"])
  851. }
  852. if infotype == "" {
  853. infotype = common.ObjToString(info["type"])
  854. if infotype == "tender" {
  855. infotype = "招标"
  856. } else if infotype == "bid" {
  857. infotype = "中标"
  858. }
  859. }
  860. info["type"] = infotype
  861. return info
  862. }
  863. // UpdateUserPushUnread 更新app未读标识为已读
  864. func UpdateUserPushUnread(userid string, vt string) {
  865. if vt == MemberFlag {
  866. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_member_apppushunread": 0}})
  867. } else if vt == EntnicheFlag {
  868. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_entniche_apppushunread": 0}})
  869. } else {
  870. IC.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_apppushunread": 0}})
  871. }
  872. }
  873. func (s *subscribePush) SetRead(newUserId, id int64, userId, entUserId, entId string, isEnt bool, userType string) error {
  874. if id <= 0 && newUserId == 0 {
  875. return nil
  876. }
  877. if newUserId == 0 {
  878. return nil
  879. }
  880. if isEnt {
  881. if s.ModuleFlag == EntnicheFlag {
  882. IC.BaseServiceMysql.UpdateOrDeleteBySql(fmt.Sprintf("update %s set isvisit=1 ,visittime=now() where entid=? and id=?", aboutDbMsg[s.ModuleFlag].MysqlTable), entId, id)
  883. } else {
  884. IC.BaseServiceMysql.UpdateOrDeleteBySql(fmt.Sprintf("update %s set isvisit=1 where entid=? and id=?", aboutDbMsg[s.ModuleFlag].MysqlTable), entId, id)
  885. }
  886. } else {
  887. if s.ModuleFlag == EntnicheFlag {
  888. //商机管理
  889. IC.BaseServiceMysql.UpdateOrDeleteBySql(fmt.Sprintf("update %s set isvisit=1,visittime=now() where userid=? and id=?", aboutDbMsg[s.ModuleFlag].MysqlTable), entUserId, id)
  890. } else {
  891. //其他
  892. IC.BaseServiceMysql.UpdateOrDeleteBySql(fmt.Sprintf("update %s set isvisit=1 where userid=? and id=?", aboutDbMsg[s.ModuleFlag].MysqlTable), newUserId, id)
  893. }
  894. }
  895. if !isEnt {
  896. if s.ModuleFlag == EntnicheFlag {
  897. userId = entUserId
  898. }
  899. todaySubPush, err := s.GetTodayCache(userId, userType)
  900. //当天数据处理
  901. if err == nil && todaySubPush != nil {
  902. for _, v := range todaySubPush.Datas {
  903. if v.CaIndex == id {
  904. v.CaIsvisit = 1
  905. break
  906. }
  907. }
  908. s.PutTodayCache(userId, userType, todaySubPush)
  909. }
  910. //全部数据处理
  911. allSubPush, err := s.GetAllCache(userId, userType)
  912. if err == nil && allSubPush != nil {
  913. for _, v := range allSubPush.Datas {
  914. if v.CaIndex == id {
  915. v.CaIsvisit = 1
  916. break
  917. }
  918. }
  919. s.PutAllCache(userId, userType, allSubPush)
  920. }
  921. }
  922. return nil
  923. }
  924. // UserInfo 获取用户信息
  925. func (s *subscribePush) UserInfo(baseUserId int64) (*map[string]interface{}, int64) {
  926. 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}`)
  927. if !ok || user == nil {
  928. return nil, 0
  929. }
  930. return user, common.Int64All((*user)["l_firstpushtime"])
  931. }
  932. // GetKeySet 是否有订阅词
  933. func GetKeySet(t string, u *map[string]interface{}, data []string) (bool, []string) {
  934. var industry_ = []string{}
  935. if u != nil {
  936. if t == SubFreeFlag {
  937. o_jy, _ := (*u)["o_jy"].(map[string]interface{})
  938. a_key, _ := o_jy["a_key"].([]interface{})
  939. return len(a_key) > 0, industry_
  940. } else {
  941. var obj map[string]interface{}
  942. if t == SubVipFlag {
  943. obj, _ = (*u)["o_vipjy"].(map[string]interface{})
  944. } else if t == MemberFlag {
  945. obj, _ = (*u)["o_member_jy"].(map[string]interface{})
  946. } else if t == EntnicheFlag {
  947. if len(data) > 0 {
  948. return true, data
  949. } else {
  950. return false, data
  951. }
  952. }
  953. if obj != nil {
  954. if buyerclassObj, ok := obj["a_buyerclass"].([]interface{}); ok {
  955. industry_ = common.ObjArrToStringArr(buyerclassObj)
  956. }
  957. itmes, _ := obj["a_items"].([]interface{})
  958. for _, v := range itmes {
  959. item, _ := v.(map[string]interface{})
  960. keys, _ := item["a_key"].([]interface{})
  961. if len(keys) > 0 {
  962. return true, industry_
  963. }
  964. }
  965. }
  966. }
  967. }
  968. return false, industry_
  969. }
  970. const (
  971. INDEX = "bidding"
  972. TYPE = "bidding"
  973. 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"`
  974. bidTime = `{"range":{"publishtime":{"gt":%d}}}`
  975. bidSort = `{"publishtime":"desc"}`
  976. findfields = `"title"`
  977. )
  978. // 首次访问推送页面 默认生成推送数据
  979. // 默认匹配es 7天内数据
  980. func (s *subscribePush) DefaultDatas(spqp *SubPushQueryParam) (hasNextPage bool, total int64, result []*bxsubscribe.SubscribeInfo) {
  981. if spqp.UserId == "" {
  982. return false, 0, nil
  983. }
  984. t1 := time.Now()
  985. logx.Info("userId:", spqp.UserId, "newUserId:", spqp.NewUserId)
  986. //用户信息
  987. bsp := s.getUserInfo(spqp)
  988. logx.Info("获取用户信息耗时:", time.Since(t1))
  989. t2 := time.Now()
  990. if len(bsp.Keyword) > 0 {
  991. logx.Info(time.Since(t1), "--bsp:", bsp)
  992. //获取查询语句
  993. qstr := s.getDefaultDatasSQL(bsp)
  994. list := elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSort, bidField, 0, bsp.Size, 0, false)
  995. //logx.Info(time.Since(t1), "count:", len(*list))
  996. if list != nil && len(*list) > 0 {
  997. total = int64(len(*list))
  998. result = s.listManager(spqp, *list, bsp.Keyword)
  999. if len(result) > pageSize {
  1000. result = result[:pageSize]
  1001. hasNextPage = true
  1002. }
  1003. }
  1004. }
  1005. logx.Info("请求耗时:", time.Since(t2))
  1006. return
  1007. }
  1008. // 保存推送表
  1009. func (s *subscribePush) listManager(spqp *SubPushQueryParam, list []map[string]interface{}, keyword []ViewKeyWord) (resultList []*bxsubscribe.SubscribeInfo) {
  1010. t2 := time.Now()
  1011. now := time.Now().Unix()
  1012. length := len(list)
  1013. resultList = make([]*bxsubscribe.SubscribeInfo, length)
  1014. pushInsert := []interface{}{}
  1015. product := ""
  1016. if spqp.UserType == SubVipFlag {
  1017. product = "1"
  1018. } else if spqp.UserType == MemberFlag {
  1019. product = "2"
  1020. }
  1021. for i := length - 1; i >= 0; i-- {
  1022. v := list[i]
  1023. title := strings.Replace(common.ObjToString(v["title"]), " ", "", -1)
  1024. infoid := common.InterfaceToStr(v["_id"])
  1025. matchkeys := getKeys(title, keyword)
  1026. matchkey := strings.Join(matchkeys, " ")
  1027. redisKey := fmt.Sprintf("pushinfo_%s_%s", spqp.UserId, common.ObjToString(v["_id"]))
  1028. entid := spqp.EntId
  1029. entUserId := spqp.EntUserId
  1030. deptid := spqp.DeptId
  1031. switch s.ModuleFlag {
  1032. case EntnicheFlag:
  1033. pushInsert = append(pushInsert, entid, deptid, entUserId, common.InterfaceToStr(infoid), matchkey, now, 1, product)
  1034. case MemberFlag:
  1035. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId), common.InterfaceToStr(infoid), matchkey, now)
  1036. case SubVipFlag:
  1037. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId), common.InterfaceToStr(infoid), matchkey, now, 1)
  1038. case SubFreeFlag:
  1039. pushInsert = append(pushInsert, common.InterfaceToStr(spqp.NewUserId), common.InterfaceToStr(infoid), matchkey, now, 0)
  1040. }
  1041. redis.Put("pushcache_2_a", redisKey, 1, 86400)
  1042. resultList[i] = s.InfoFormat(&PushCa{
  1043. InfoId: infoid,
  1044. Date: time.Now().Unix(),
  1045. Keys: matchkeys,
  1046. FileExists: v["filetext"] != nil,
  1047. }, &v, spqp.IsPayUser)
  1048. }
  1049. id := int64(0)
  1050. switch s.ModuleFlag {
  1051. case EntnicheFlag:
  1052. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, ennicheInsertCollKey, pushInsert)
  1053. case MemberFlag:
  1054. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, memberInsertCollKey, pushInsert)
  1055. default:
  1056. _, id = spqp.BaseServiceMysql.InsertIgnoreBatch(aboutDbMsg[s.ModuleFlag].MysqlTable, subscribeInsertCollKey, pushInsert)
  1057. }
  1058. for i := length - 1; i >= 0; i-- {
  1059. resultList[i].CaIndex = id
  1060. id++
  1061. }
  1062. logx.Info("数据处理耗时:", time.Since(t2))
  1063. return
  1064. }
  1065. // 获取匹配得关键词
  1066. func getKeys(title string, keywords []ViewKeyWord) (str []string) {
  1067. if len(keywords) > 0 {
  1068. L:
  1069. for _, v := range keywords {
  1070. for _, vk := range v.Keyword {
  1071. if strings.Contains(title, vk) {
  1072. str = append(str, v.Keyword...)
  1073. break L
  1074. }
  1075. }
  1076. for _, va := range v.Appended {
  1077. if strings.Contains(title, va) {
  1078. str = append(str, v.Appended...)
  1079. break L
  1080. }
  1081. }
  1082. }
  1083. }
  1084. return
  1085. }
  1086. // 获取查询语句
  1087. func (s *subscribePush) getDefaultDatasSQL(bsp *ViewCondition) (str string) {
  1088. query := `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match": %d}}}`
  1089. query_bool_should := `{"bool":{"should":[%s],"minimum_should_match": 1}}`
  1090. multi_match := `{"multi_match": {"query": %s,"type": "phrase", "fields": [%s]}}`
  1091. query_bool_must_and := `{"bool":{"must":[%s]%s}}`
  1092. bools := []string{}
  1093. musts := []string{}
  1094. //发布时间最新7天(正式环境需要修改)
  1095. musts = append(musts, fmt.Sprintf(bidTime, time.Now().AddDate(0, 0, -7).Unix()))
  1096. //省份
  1097. areaCity := []string{}
  1098. if len(bsp.Area) > 0 {
  1099. areaquery := `{"terms":{"area":[`
  1100. for k, v := range bsp.Area {
  1101. if k > 0 {
  1102. areaquery += `,`
  1103. }
  1104. areaquery += `"` + v + `"`
  1105. }
  1106. areaquery += `]}}`
  1107. areaCity = append(areaCity, areaquery)
  1108. }
  1109. //城市
  1110. if len(bsp.City) > 0 {
  1111. areaquery := `{"terms":{"city":[`
  1112. for k, v := range bsp.City {
  1113. if k > 0 {
  1114. areaquery += `,`
  1115. }
  1116. areaquery += `"` + v + `"`
  1117. }
  1118. areaquery += `]}}`
  1119. areaCity = append(areaCity, areaquery)
  1120. }
  1121. if len(areaCity) > 0 {
  1122. musts = append(musts, fmt.Sprintf(query_bool_should, strings.Join(areaCity, ",")))
  1123. }
  1124. if len(bsp.Subtype) > 0 {
  1125. subquery := `{"terms":{"subtype":[`
  1126. for k, v := range bsp.Subtype {
  1127. if k > 0 {
  1128. subquery += `,`
  1129. }
  1130. subquery += `"` + v + `"`
  1131. }
  1132. subquery += `]}}`
  1133. musts = append(musts, subquery)
  1134. }
  1135. if len(bsp.Buyerclass) > 0 {
  1136. Buyerclass := `{"terms":{"buyerclass":[`
  1137. for k, v := range bsp.Buyerclass {
  1138. if k > 0 {
  1139. Buyerclass += `,`
  1140. }
  1141. Buyerclass += `"` + v + `"`
  1142. }
  1143. Buyerclass += `]}}`
  1144. musts = append(musts, Buyerclass)
  1145. }
  1146. boolsNum := 0 //should
  1147. if len(bsp.Keyword) > 0 {
  1148. boolsNum = 1
  1149. if bsp.SelectType == "" || bsp.SelectType == "2" {
  1150. bsp.SelectType = "detail\", \"title"
  1151. } else {
  1152. bsp.SelectType = "title"
  1153. }
  1154. multi_match = fmt.Sprintf(multi_match, "%s", "\""+bsp.SelectType+"\"")
  1155. for _, v := range bsp.Keyword {
  1156. shoulds := []string{}
  1157. must_not := []string{}
  1158. //附加词
  1159. for _, vv := range v.Keyword {
  1160. vv = strings.TrimSpace(vv)
  1161. if vv == "" {
  1162. continue
  1163. }
  1164. shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
  1165. }
  1166. for _, vv := range v.Appended {
  1167. vv = strings.TrimSpace(vv)
  1168. if vv == "" {
  1169. continue
  1170. }
  1171. shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
  1172. }
  1173. //排除词
  1174. for _, vv := range v.Exclude {
  1175. vv = strings.TrimSpace(vv)
  1176. if vv == "" {
  1177. continue
  1178. }
  1179. must_not = append(must_not, fmt.Sprintf(multi_match, "\""+vv+"\""))
  1180. }
  1181. //添加
  1182. if len(shoulds) > 0 {
  1183. notStr := ""
  1184. if len(must_not) > 0 {
  1185. notStr = fmt.Sprintf(`,"must_not":[%s]`, strings.Join(must_not, ","))
  1186. }
  1187. bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(shoulds, ","), notStr))
  1188. }
  1189. }
  1190. }
  1191. qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum)
  1192. logx.Info("----", qstr)
  1193. return qstr
  1194. }
  1195. /*已选条件--关键词*/
  1196. type ViewKeyWord struct {
  1197. Keyword []string `json:"key"` //关键词
  1198. Appended []string `json:"appendkey"` //附加词
  1199. Exclude []string `json:"notkey"` //排除词
  1200. MatchWay int `json:"matchway"` //匹配模式
  1201. }
  1202. /*已选条件*/
  1203. type ViewCondition struct {
  1204. Area []string //地区-省份
  1205. City []string //地区-城市
  1206. Buyerclass []string //采购行业
  1207. Keyword []ViewKeyWord //关键词
  1208. SelectType string //筛选(正文 or 标题)
  1209. Subtype []string //信息类型
  1210. Size int //数量
  1211. }
  1212. // 获取用户信息
  1213. func (s *subscribePush) getUserInfo(spqp *SubPushQueryParam) (vc *ViewCondition) {
  1214. var isPayBool = false
  1215. var tmpInfo = struct {
  1216. Items []interface{}
  1217. BuyerClass []interface{}
  1218. SubType []interface{}
  1219. Area map[string]interface{}
  1220. SelectType string
  1221. }{}
  1222. switch s.ModuleFlag {
  1223. case MemberFlag:
  1224. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_member_jy":1,"i_member_status":1}`)
  1225. if !ok || userMap == nil || len(*userMap) == 0 {
  1226. return &ViewCondition{}
  1227. }
  1228. //大会员
  1229. if common.IntAll((*userMap)["i_member_status"]) > 0 {
  1230. isPayBool = true
  1231. o_member_jy, _ := (*userMap)["o_member_jy"].(map[string]interface{})
  1232. tmpInfo.Items, _ = o_member_jy["a_items"].([]interface{})
  1233. tmpInfo.BuyerClass, _ = o_member_jy["a_buyerclass"].([]interface{})
  1234. tmpInfo.SubType, _ = o_member_jy["a_infotype"].([]interface{})
  1235. tmpInfo.Area, _ = o_member_jy["o_area"].(map[string]interface{})
  1236. }
  1237. case SubVipFlag:
  1238. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_vipjy":1,"i_vip_status":1}`)
  1239. if !ok || userMap == nil || len(*userMap) == 0 {
  1240. return &ViewCondition{}
  1241. }
  1242. if common.IntAll((*userMap)["i_vip_status"]) > 0 {
  1243. isPayBool = true
  1244. o_vipjy, _ := (*userMap)["o_vipjy"].(map[string]interface{})
  1245. tmpInfo.Items, _ = o_vipjy["a_items"].([]interface{})
  1246. tmpInfo.BuyerClass, _ = o_vipjy["a_buyerclass"].([]interface{})
  1247. tmpInfo.SubType, _ = o_vipjy["a_infotype"].([]interface{})
  1248. tmpInfo.Area, _ = o_vipjy["o_area"].(map[string]interface{})
  1249. }
  1250. case EntnicheFlag:
  1251. //商机管理
  1252. entUserId, _ := strconv.Atoi(spqp.EntUserId)
  1253. entId, _ := strconv.Atoi(spqp.EntId)
  1254. entInfo, deptId := (&ms.MatchJob{}).Start(entId, entUserId)
  1255. if entInfo != nil && len(entInfo) > 0 {
  1256. spqp.DeptId = strconv.Itoa(deptId)
  1257. isPayBool = true
  1258. tmpInfo.Items, _ = entInfo["a_items"].([]interface{})
  1259. tmpInfo.BuyerClass, _ = entInfo["a_buyerclass"].([]interface{})
  1260. tmpInfo.SubType, _ = entInfo["a_infotype"].([]interface{})
  1261. tmpInfo.Area, _ = entInfo["o_area"].(map[string]interface{})
  1262. }
  1263. default:
  1264. userMap, ok := IC.Mgo.FindById("user", spqp.UserId, `{"o_jy":1}`)
  1265. if !ok || userMap == nil || len(*userMap) == 0 {
  1266. return &ViewCondition{}
  1267. }
  1268. o_jy, _ := (*userMap)["o_jy"].(map[string]interface{})
  1269. if o_jy["a_key"] != nil {
  1270. tmpInfo.Items, _ = o_jy["a_key"].([]interface{})
  1271. //信息类型
  1272. tmpInfo.SubType, _ = o_jy["a_infotype"].([]interface{})
  1273. //省份
  1274. tmpInfo.Area, _ = o_jy["o_area"].(map[string]interface{})
  1275. if common.IntAllDef(o_jy["i_ppstatus"], 0) == 1 && o_jy["o_area_p"] != nil {
  1276. tmpInfo.Area, _ = o_jy["o_area_p"].(map[string]interface{})
  1277. }
  1278. }
  1279. }
  1280. vc = &ViewCondition{
  1281. Buyerclass: common.ObjArrToStringArr(tmpInfo.BuyerClass),
  1282. Subtype: common.ObjArrToStringArr(tmpInfo.SubType),
  1283. Area: getStringArrFromDbResult(tmpInfo.Area, 1),
  1284. City: getStringArrFromDbResult(tmpInfo.Area, 2),
  1285. SelectType: "1",
  1286. }
  1287. //付费用户
  1288. if isPayBool {
  1289. vc.Size = IC.C.DefaulCount.Pay
  1290. vc.Keyword = getKeyWordArrFromDbResult(tmpInfo.Items, "", -1)
  1291. } else {
  1292. vc.Size = IC.C.DefaulCount.Free
  1293. vc.Keyword = getKeyWordArrFromDbResultByFree(tmpInfo.Items, "", -1)
  1294. //vc.Keyword = getKeyWordArrFromDbResult(tmpInfo.Items, "", -1)
  1295. }
  1296. return
  1297. }
  1298. // 关键词 附加词 排除词
  1299. func getKeyWordArrFromDbResult(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
  1300. if a_items == nil {
  1301. return
  1302. }
  1303. for _, v := range a_items {
  1304. vm, _ := v.(map[string]interface{})
  1305. if item != "" && index >= 0 && item != common.ObjToString(vm["s_item"]) {
  1306. continue
  1307. }
  1308. kwsArr := vm["a_key"]
  1309. for i, k := range kwsArr.([]interface{}) {
  1310. if item != "" && index >= 0 && i != index {
  1311. continue
  1312. }
  1313. kw := ViewKeyWord{}
  1314. b, e := json.Marshal(k)
  1315. if e != nil {
  1316. log.Println(e.Error())
  1317. }
  1318. json.Unmarshal(b, &kw)
  1319. if kw.MatchWay == 1 {
  1320. for _, kk := range kw.Keyword {
  1321. arr = append(arr, ViewKeyWord{
  1322. Keyword: []string{kk},
  1323. Exclude: kw.Exclude,
  1324. })
  1325. }
  1326. for _, kk := range kw.Appended {
  1327. arr = append(arr, ViewKeyWord{
  1328. Keyword: []string{kk},
  1329. Exclude: kw.Exclude,
  1330. })
  1331. }
  1332. } else {
  1333. arr = append(arr, kw)
  1334. }
  1335. }
  1336. }
  1337. return
  1338. }
  1339. // //关键词 附加词 排除词 省份订阅包 - 普通用户
  1340. func getKeyWordArrFromDbResultByFree(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
  1341. if a_items == nil {
  1342. return
  1343. }
  1344. for _, v := range a_items {
  1345. kw := ViewKeyWord{}
  1346. b, e := json.Marshal(v)
  1347. if e != nil {
  1348. log.Println(e.Error())
  1349. }
  1350. json.Unmarshal(b, &kw)
  1351. if kw.MatchWay == 1 {
  1352. for _, kk := range kw.Keyword {
  1353. arr = append(arr, ViewKeyWord{
  1354. Keyword: []string{kk},
  1355. Exclude: kw.Exclude,
  1356. })
  1357. }
  1358. for _, kk := range kw.Appended {
  1359. arr = append(arr, ViewKeyWord{
  1360. Keyword: []string{kk},
  1361. Exclude: kw.Exclude,
  1362. })
  1363. }
  1364. } else {
  1365. arr = append(arr, kw)
  1366. }
  1367. }
  1368. return
  1369. }
  1370. // 地区格式化
  1371. func getStringArrFromDbResult(area map[string]interface{}, i int) (arr []string) {
  1372. if area == nil {
  1373. return
  1374. }
  1375. var eareArr []string
  1376. var cityArr []string
  1377. for k, v := range area {
  1378. if len(v.([]interface{})) > 0 {
  1379. cityArr = append(cityArr, common.ObjArrToStringArr(v.([]interface{}))...)
  1380. } else {
  1381. eareArr = append(eareArr, k)
  1382. }
  1383. }
  1384. if i == 1 {
  1385. arr = eareArr
  1386. } else {
  1387. arr = cityArr
  1388. }
  1389. return
  1390. }
  1391. // IsInTsGuide 是否进入向导
  1392. func (s *subscribePush) IsInTsGuide(userid string) bool {
  1393. if userid == "" {
  1394. return false
  1395. }
  1396. data, ok := IC.Mgo.FindById("user", userid, `{"o_jy":1,"i_ts_guide":1,"":1,"i_member_status":1,"i_vip_status":1}`)
  1397. if ok {
  1398. //付费用户无免费订阅,不进入订阅向导页面
  1399. if common.IntAll((*data)["i_member_status"]) > 0 || common.IntAll((*data)["i_vip_status"]) > 0 {
  1400. return false
  1401. }
  1402. o_jy, _ := (*data)["o_jy"].(map[string]interface{})
  1403. i_ts_guide := common.IntAll((*data)["i_ts_guide"])
  1404. if i_ts_guide == 2 || (i_ts_guide == 0 && len(o_jy) == 0) {
  1405. return true
  1406. }
  1407. }
  1408. return false
  1409. }
  1410. func (s *subscribePush) Keys(spqp *KeyParam) (result []*bxsubscribe.KeyItems) {
  1411. keyData := map[string][]interface{}{}
  1412. if spqp.IsEnt {
  1413. //企业关键词查找
  1414. res_, _ := IC.Mgo.Find("entniche_rule", map[string]interface{}{
  1415. "i_userid": map[string]interface{}{
  1416. "$exists": false,
  1417. },
  1418. "i_entid": common.Int64All(spqp.EntId),
  1419. }, "", `{"o_entniche":1}`, false, -1, -1)
  1420. o_entniche := map[string]interface{}{}
  1421. if res_ == nil || len(*res_) == 0 {
  1422. return MapToarr(keyData)
  1423. }
  1424. for _, ruleV := range *res_ {
  1425. o_entniche = common.StructToMapMore(ruleV["o_entniche"])
  1426. if o_entniche["a_items"] != nil {
  1427. a_item := common.ObjArrToMapArr(o_entniche["a_items"].([]interface{}))
  1428. for _, v := range a_item {
  1429. if v["a_key"] != nil {
  1430. a_key_arr := v["a_key"].([]interface{})
  1431. s_item := common.InterfaceToStr(v["s_item"])
  1432. if keyData[s_item] != nil {
  1433. //第一次搜索存在
  1434. //去重
  1435. keyData[s_item] = MergeArray(a_key_arr, keyData[s_item])
  1436. } else {
  1437. //第一次搜索不存在
  1438. keyData[s_item] = a_key_arr
  1439. }
  1440. }
  1441. }
  1442. }
  1443. }
  1444. } else {
  1445. //个人关键词查找
  1446. //fType:普通用户;vType:超级订阅用户;mType:大会员用户;eType:商机管理用户
  1447. types := 2
  1448. typeKey := ""
  1449. switch s.ModuleFlag {
  1450. case SubVipFlag:
  1451. types = 1
  1452. typeKey = "o_vipjy"
  1453. case MemberFlag:
  1454. types = 1
  1455. typeKey = "o_member_jy"
  1456. case EntnicheFlag:
  1457. types = 0
  1458. typeKey = "o_entniche"
  1459. }
  1460. if spqp.PositionType == 1 {
  1461. typeKey = "o_entniche"
  1462. }
  1463. o_entniche := &map[string]interface{}{}
  1464. if spqp.PositionType == 0 {
  1465. 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}`)
  1466. if mData == nil || len(*mData) == 0 || !ok {
  1467. return nil
  1468. }
  1469. if s.ModuleFlag == MemberFlag {
  1470. sub_status := common.Int64All((*mData)["i_member_sub_status"])
  1471. if sub_status == 1 {
  1472. //大会员子账号处理
  1473. 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}`)
  1474. if mData == nil || len(*mData) == 0 || !ok {
  1475. return nil
  1476. }
  1477. }
  1478. }
  1479. o_entniche = common.ObjToMap((*mData)[typeKey])
  1480. } else {
  1481. res_, _ := IC.Mgo.FindOneByField("entniche_rule", map[string]interface{}{
  1482. "i_userid": common.Int64All(spqp.EntUserId),
  1483. "i_entid": common.Int64All(spqp.EntId),
  1484. "i_type": types,
  1485. }, `{"o_entniche":1}`)
  1486. if res_ != nil {
  1487. o_entniche = common.ObjToMap((*res_)["o_entniche"])
  1488. }
  1489. }
  1490. if s.ModuleFlag == SubVipFlag {
  1491. //从user表中取 o_vipjy.a_items
  1492. if (*o_entniche)["a_items"] != nil {
  1493. a_items := common.ObjArrToMapArr((*o_entniche)["a_items"].([]interface{}))
  1494. for _, v := range a_items {
  1495. if v["a_key"] != nil {
  1496. a_key_arr := v["a_key"].([]interface{})
  1497. keyData[common.InterfaceToStr(v["s_item"])] = a_key_arr
  1498. }
  1499. }
  1500. }
  1501. } else if s.ModuleFlag == MemberFlag {
  1502. //从user表中取 o_member_jy.a_items
  1503. //o_memeberjy := common.ObjToMap((*mData)["o_member_jy"])
  1504. if (*o_entniche)["a_items"] != nil {
  1505. a_items := common.ObjArrToMapArr((*o_entniche)["a_items"].([]interface{}))
  1506. for _, v := range a_items {
  1507. if v["a_key"] != nil {
  1508. a_key_arr := v["a_key"].([]interface{})
  1509. keyData[common.InterfaceToStr(v["s_item"])] = a_key_arr
  1510. }
  1511. }
  1512. }
  1513. } else if s.ModuleFlag == EntnicheFlag {
  1514. res_, _ := IC.Mgo.FindOneByField("entniche_rule", map[string]interface{}{
  1515. "i_userid": common.Int64All(spqp.EntUserId),
  1516. "i_entid": common.Int64All(spqp.EntId),
  1517. "i_type": types,
  1518. }, `{"o_entniche":1}`)
  1519. o_entniche := &map[string]interface{}{}
  1520. if res_ != nil {
  1521. o_entniche = common.ObjToMap((*res_)["o_entniche"])
  1522. }
  1523. if (*o_entniche)["a_items"] != nil {
  1524. a_item := common.ObjArrToMapArr((*o_entniche)["a_items"].([]interface{}))
  1525. for _, v := range a_item {
  1526. if v["a_key"] != nil {
  1527. a_key_arr := v["a_key"].([]interface{})
  1528. keyData[common.InterfaceToStr(v["s_item"])] = a_key_arr
  1529. }
  1530. }
  1531. }
  1532. } else {
  1533. //免费用户
  1534. a_key, _ := (*o_entniche)["a_key"].([]interface{})
  1535. if len(a_key) > 0 {
  1536. for _, v := range a_key {
  1537. if keyData["未分类"] != nil {
  1538. keyData["未分类"] = append(keyData["未分类"], v)
  1539. } else {
  1540. keyData["未分类"] = []interface{}{v}
  1541. }
  1542. }
  1543. }
  1544. }
  1545. if spqp.PositionType == 1 && s.ModuleFlag != SubFreeFlag {
  1546. //1、mysql entniche_user_rule表中获取自己的分发规则id
  1547. data := IC.MainMysql.SelectBySql(`SELECT rule_id FROM entniche_user_rule a
  1548. INNER JOIN entniche_department b ON a.dept_id = b.id AND a.user_id =?
  1549. ORDER BY b.pid
  1550. LIMIT 1 `, spqp.EntUserId)
  1551. if data == nil || len(*data) == 0 {
  1552. return MapToarr(keyData)
  1553. }
  1554. ruleId := common.ObjToString((*data)[0]["rule_id"])
  1555. //3、entniche_distribute表,查询条件:{_id:ObjectId(1结果中的分发规则id),i_status:0},取 o_entniche.a_items,这个查到的是分类名称,然后到上面1的结果中获取这个分类下的词
  1556. res, _ := IC.Mgo.FindById("entniche_distribute", ruleId, nil)
  1557. if res == nil || len(*res) == 0 {
  1558. return MapToarr(keyData)
  1559. }
  1560. entItem := (*res)["a_items"].([]interface{})
  1561. if (*res)["a_items"] == nil {
  1562. return MapToarr(keyData)
  1563. }
  1564. //2、entniche_rule表, 企业订阅关键词查询条件: {i_entid:123,i_deptid:0},取 o_entniche.a_items
  1565. deptid := common.Int64All((*res)["i_deptid"])
  1566. ruleMap := map[string]interface{}{
  1567. "i_entid": common.Int64All(spqp.EntId),
  1568. }
  1569. if deptid == 0 {
  1570. ruleMap["i_deptid"] = map[string]interface{}{"$exists": false}
  1571. ruleMap["i_userid"] = map[string]interface{}{"$exists": false}
  1572. } else {
  1573. ruleMap["i_deptid"] = deptid
  1574. }
  1575. res_, _ := IC.Mgo.FindOneByField("entniche_rule", ruleMap, `{"o_entniche":1}`)
  1576. o_entniche := &map[string]interface{}{}
  1577. if res_ != nil {
  1578. o_entniche = common.ObjToMap((*res_)["o_entniche"])
  1579. }
  1580. entnicheRule := map[string][]interface{}{}
  1581. if (*o_entniche)["a_items"] != nil {
  1582. a_item := common.ObjArrToMapArr((*o_entniche)["a_items"].([]interface{}))
  1583. for _, v := range a_item {
  1584. if v["a_key"] != nil {
  1585. a_key_arr := v["a_key"].([]interface{})
  1586. entnicheRule[common.InterfaceToStr(v["s_item"])] = a_key_arr
  1587. }
  1588. }
  1589. }
  1590. for _, value := range entItem {
  1591. v := common.InterfaceToStr(value)
  1592. if entnicheRule[v] != nil {
  1593. if keyData[v] != nil {
  1594. //第一次搜索存在
  1595. //去重
  1596. keyData[v] = MergeArray(keyData[v], entnicheRule[v])
  1597. } else {
  1598. //第一次搜索不存在
  1599. keyData[v] = entnicheRule[v]
  1600. }
  1601. }
  1602. }
  1603. }
  1604. }
  1605. return MapToarr(keyData)
  1606. }
  1607. // 关键词处理
  1608. func KeyHandle(a_items map[string]interface{}) []interface{} {
  1609. keyArr := []interface{}{}
  1610. if a_items["a_key"] != nil {
  1611. a_key_arr := common.ObjArrToMapArr(a_items["a_key"].([]interface{}))
  1612. for _, vv := range a_key_arr {
  1613. for _, v := range vv["key"].([]interface{}) {
  1614. keyArr = append(keyArr, v)
  1615. }
  1616. }
  1617. }
  1618. return keyArr
  1619. }
  1620. func MapToarr(data map[string][]interface{}) []*bxsubscribe.KeyItems {
  1621. result := []*bxsubscribe.KeyItems{}
  1622. for k, v := range data {
  1623. keyArr := []*bxsubscribe.Key{}
  1624. for _, m := range common.ObjArrToMapArr(v) {
  1625. keys := &bxsubscribe.Key{}
  1626. if m["notkey"] != nil {
  1627. keys.Notkey = common.ObjArrToStringArr(m["notkey"].([]interface{}))
  1628. }
  1629. if m["key"] != nil {
  1630. keys.Key = common.ObjArrToStringArr(m["key"].([]interface{}))
  1631. }
  1632. if m["matchway"] != nil {
  1633. keys.Matchway = common.Int64All(m["matchway"])
  1634. }
  1635. if m["appendkey"] != nil {
  1636. keys.Appendkey = common.ObjArrToStringArr(m["appendkey"].([]interface{}))
  1637. }
  1638. keyArr = append(keyArr, keys)
  1639. }
  1640. result = append(result, &bxsubscribe.KeyItems{
  1641. AKey: keyArr,
  1642. SItem: k,
  1643. })
  1644. }
  1645. return result
  1646. }
  1647. func MergeArray(dest []interface{}, src []interface{}) (result []interface{}) {
  1648. data := map[string]interface{}{}
  1649. for _, v := range common.ObjArrToMapArr(dest) {
  1650. notkey := ""
  1651. key := ""
  1652. matchway := ""
  1653. appendkey := ""
  1654. if v["notkey"] != nil {
  1655. otkeyArr := common.ObjArrToStringArr(v["notkey"].([]interface{}))
  1656. for _, keyV := range otkeyArr {
  1657. if common.InterfaceToStr(keyV) != "" {
  1658. notkey += fmt.Sprintf(",%s", common.InterfaceToStr(keyV))
  1659. }
  1660. }
  1661. }
  1662. if v["key"] != nil {
  1663. keyArr := common.ObjArrToStringArr(v["key"].([]interface{}))
  1664. for _, keyV := range keyArr {
  1665. if common.InterfaceToStr(keyV) != "" {
  1666. key += fmt.Sprintf(",%s", common.InterfaceToStr(keyV))
  1667. }
  1668. }
  1669. }
  1670. if v["matchway"] != nil {
  1671. matchway = common.InterfaceToStr(v["matchway"])
  1672. }
  1673. if v["appendkey"] != nil {
  1674. appendkeyArr := common.ObjArrToStringArr(v["appendkey"].([]interface{}))
  1675. for _, keyV := range appendkeyArr {
  1676. if common.InterfaceToStr(keyV) != "" {
  1677. appendkey += fmt.Sprintf(",%s", common.InterfaceToStr(keyV))
  1678. }
  1679. }
  1680. }
  1681. k := fmt.Sprintf("%s_____%s_____%s_____%s", notkey, key, matchway, appendkey)
  1682. data[k] = v
  1683. }
  1684. for _, v := range common.ObjArrToMapArr(src) {
  1685. notkey := ""
  1686. key := ""
  1687. matchway := ""
  1688. appendkey := ""
  1689. if v["notkey"] != nil {
  1690. otkeyArr := common.ObjArrToStringArr(v["notkey"].([]interface{}))
  1691. for _, keyV := range otkeyArr {
  1692. if common.InterfaceToStr(keyV) != "" {
  1693. notkey += fmt.Sprintf(",%s", common.InterfaceToStr(keyV))
  1694. }
  1695. }
  1696. }
  1697. if v["key"] != nil {
  1698. keyArr := common.ObjArrToStringArr(v["key"].([]interface{}))
  1699. for _, keyV := range keyArr {
  1700. if common.InterfaceToStr(keyV) != "" {
  1701. key += fmt.Sprintf(",%s", common.InterfaceToStr(keyV))
  1702. }
  1703. }
  1704. }
  1705. if v["matchway"] != nil {
  1706. matchway = common.InterfaceToStr(v["matchway"])
  1707. }
  1708. if v["appendkey"] != nil {
  1709. appendkeyArr := common.ObjArrToStringArr(v["appendkey"].([]interface{}))
  1710. for _, keyV := range appendkeyArr {
  1711. if common.InterfaceToStr(keyV) != "" {
  1712. appendkey += fmt.Sprintf(",%s", common.InterfaceToStr(keyV))
  1713. }
  1714. }
  1715. }
  1716. k := fmt.Sprintf("%s_____%s_____%s_____%s", notkey, key, matchway, appendkey)
  1717. data[k] = v
  1718. }
  1719. for _, v := range data {
  1720. result = append(result, v)
  1721. }
  1722. return
  1723. }