purchase.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. package service
  2. import (
  3. MC "app.yhyue.com/moapp/jybase/common"
  4. "app.yhyue.com/moapp/jybase/encrypt"
  5. elastic "app.yhyue.com/moapp/jybase/es"
  6. "app.yhyue.com/moapp/jybase/redis"
  7. "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
  8. "bp.jydev.jianyu360.cn/BaseService/jyMicroservices/jyBXCore/entity"
  9. IC "bp.jydev.jianyu360.cn/BaseService/jyMicroservices/jyBXCore/rpc/init"
  10. "bp.jydev.jianyu360.cn/BaseService/jyMicroservices/jyBXCore/rpc/model/es"
  11. "bp.jydev.jianyu360.cn/BaseService/jyMicroservices/jyBXCore/rpc/type/bxcore"
  12. "bp.jydev.jianyu360.cn/BaseService/jyMicroservices/jyBXCore/rpc/util"
  13. "encoding/json"
  14. "fmt"
  15. "github.com/zeromicro/go-zero/core/logx"
  16. "log"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. type Purchase struct {
  22. AppId string ` json:"appId,omitempty"` //剑鱼默认10000
  23. UserId string ` json:"userId,omitempty"` //用户id
  24. Phone string ` json:"phone,omitempty"` //手机号
  25. BaseUserId int64 ` json:"baseUserId,omitempty"` //base_user_id 新用户id
  26. EntId int64 ` json:"entId,omitempty"` //企业id 没有企业 企业id=0
  27. EntUserId int64 ` json:"entUserId,omitempty"` //企业用户id 当前企业下的员工id 没有企业默认0
  28. AccountId int64 ` json:"accountId,omitempty"` //账户id
  29. EntAccountId int64 ` json:"entAccountId,omitempty"` //企业账户id
  30. PositionType int64 ` json:"positionType,omitempty"` //职位类型 0个人 1企业
  31. PositionId int64 ` json:"positionId,omitempty"` //职位id
  32. MgoUserId string ` json:"mgoUserId,omitempty"` //原userId
  33. PageNum int64 ` json:"pageNum,omitempty"` //当前页码
  34. PageSize int64 ` json:"pageSize,omitempty"` //每页数量
  35. PublishTime string ` json:"publishTime,omitempty"` //发布时间
  36. SelectType string ` json:"selectType,omitempty"` //搜索范围:
  37. DomainFirstType string ` json:"domainFirstType,omitempty"` //领域 一级
  38. DomainSecondType string ` json:"domainSecondType,omitempty"` //领域 二级
  39. DomainThirdType string ` json:"domainThirdType,omitempty"` //领域 三级
  40. DeadlineStatus int64 ` json:"deadlineStatus,omitempty"` //报名截止状态
  41. DeadlineTime string ` json:"deadlineTime,omitempty"` //报名截止时间
  42. DeadlineStart int64 ` json:"deadlineStart,omitempty"` //报名截止时间-开始
  43. DeadlineEnd int64 ` json:"deadlineEnd,omitempty"` //报名截止时间-结束
  44. DeliveryArea string ` json:"deliveryArea,omitempty"` //交付地点-省份
  45. DeliveryCity string ` json:"deliveryCity,omitempty"` //交付地点-城市
  46. DeliveryDistrict string ` json:"deliveryDistrict,omitempty"` //交付地点-县区
  47. ProjectArea string ` json:"projectArea,omitempty"` //项目地区-省份
  48. ProjectCity string ` json:"projectCity,omitempty"` //项目地区-城市
  49. ProjectDistrict string ` json:"projectDistrict,omitempty"` //项目地区-县区
  50. Industry string ` json:"industry,omitempty"` //行业
  51. FileExists int64 ` json:"fileExists,omitempty"` //是否有附件
  52. Publisher int64 ` json:"publisher,omitempty"` //发布者:可选:全部、用户发布:1、平台发布:2。
  53. KeyWords string ` json:"keyWords,omitempty"` //关键词:多个空格隔开(主)
  54. AdditionalWords string ` json:"additionalWords,omitempty"` //关键词:附加关键词(副:五组,每组最多15个字符)
  55. SearchMode int64 ` json:"searchMode,omitempty"` //搜索模式:0:精准搜索;1:模糊搜索
  56. WordsMode int64 ` json:"wordsMode,omitempty"` //搜索关键词模式;默认0:包含所有,1:包含任意
  57. UserAgent string ` json:"userAgent,omitempty"` //请求头信息
  58. Platform string ` json:"platform,omitempty"` //请求平台
  59. TipMsg string `json:"tipMsg"` //关键词提示信息
  60. HighlightWords string `json:"highlightWords"` //需要高亮的词,多个,号分割
  61. Total int64 `json:"total"` //数据总量
  62. Count int64 `json:"count"` //结果数据总量
  63. IsPay bool `json:"isPay"` //是否是付费用户
  64. IsPower bool `json:"isPower"` //是否有权限
  65. }
  66. func NewPurchase(in *bxcore.PurchaseReq) *Purchase {
  67. baseUserId, _ := strconv.ParseInt(in.NewUserId, 10, 64)
  68. accountId, _ := strconv.ParseInt(in.AccountId, 10, 64)
  69. positionId, _ := strconv.ParseInt(in.PositionId, 10, 64)
  70. return &Purchase{
  71. AppId: in.AppId,
  72. UserId: in.UserId,
  73. Phone: in.Phone,
  74. BaseUserId: baseUserId,
  75. EntId: in.EntId,
  76. EntUserId: in.EntUserId,
  77. AccountId: accountId,
  78. EntAccountId: in.EntAccountId,
  79. PositionType: in.PositionType,
  80. PositionId: positionId,
  81. MgoUserId: in.MgoUserId,
  82. PageNum: in.PageNum,
  83. PageSize: in.PageSize,
  84. PublishTime: in.PublishTime,
  85. SelectType: in.SelectType,
  86. DomainFirstType: in.DomainFirstType,
  87. DomainSecondType: in.DomainSecondType,
  88. DomainThirdType: in.DomainThirdType,
  89. DeadlineStatus: in.DeadlineStatus,
  90. DeadlineTime: in.DeadlineTime,
  91. DeliveryArea: in.DeliveryArea,
  92. DeliveryCity: in.DeliveryCity,
  93. DeliveryDistrict: in.DeliveryDistrict,
  94. ProjectArea: in.ProjectArea,
  95. ProjectCity: in.ProjectCity,
  96. ProjectDistrict: in.ProjectDistrict,
  97. Industry: in.Industry,
  98. FileExists: in.FileExists,
  99. Publisher: in.Publisher,
  100. KeyWords: in.KeyWords,
  101. AdditionalWords: in.AdditionalWords,
  102. SearchMode: in.SearchMode,
  103. WordsMode: in.WordsMode,
  104. UserAgent: in.UserAgent,
  105. Platform: in.Platform,
  106. }
  107. }
  108. var (
  109. AreaLabelLink = "/list/%s/%s.html"
  110. noPower = "点击查看"
  111. )
  112. // 缓存
  113. func (p *Purchase) HistoryKeywords() {
  114. var (
  115. cacheKey = fmt.Sprintf("history_purchase_v_%s", p.UserId)
  116. keys []string
  117. code = "other"
  118. isExist = map[string]bool{}
  119. duplicateRemoval = func(values []string) (keys []string) {
  120. for _, kv := range values {
  121. kv = strings.TrimSpace(kv)
  122. if isExist[kv] {
  123. continue
  124. }
  125. isExist[kv] = true
  126. keys = append(keys, kv)
  127. }
  128. return
  129. }
  130. )
  131. values := redis.GetStr(code, cacheKey)
  132. if values != "" {
  133. keys = append(keys, duplicateRemoval(strings.Split(values, ","))...)
  134. }
  135. if p.KeyWords != "" {
  136. keys = append(keys, duplicateRemoval(strings.Split(p.KeyWords, ","))...)
  137. }
  138. if p.AdditionalWords != "" {
  139. keys = append(keys, duplicateRemoval(strings.Split(p.AdditionalWords, ","))...)
  140. }
  141. if len(keys) > 10 {
  142. keys = keys[len(keys)-10:]
  143. }
  144. ok := redis.Put(code, cacheKey, strings.Join(keys, ","), -1)
  145. if !ok {
  146. logx.Info(" history keywords err:", keys)
  147. }
  148. }
  149. // 格式化
  150. func (p *Purchase) PurchaseListFormat(res []map[string]interface{}) (list []*bxcore.PurchaseList) {
  151. for _, rv := range res {
  152. logx.Info("title:", MC.InterfaceToStr(rv["title"]))
  153. id := MC.InterfaceToStr(rv["source_id"]) //拆分后 多条数据会来自一条bidding数据嘛,把bidding的id记一个source_id;mongo 库中bidding的_id
  154. if id == "" {
  155. continue
  156. }
  157. area := MC.InterfaceToStr(rv["area"])
  158. city := MC.InterfaceToStr(rv["city"])
  159. district := MC.InterfaceToStr(rv["district"])
  160. title := MC.InterfaceToStr(rv["title"])
  161. if len([]rune(title)) > 50 {
  162. splitStr := "-"
  163. titles := strings.Split(title, splitStr)
  164. lastPart := ""
  165. if len(titles) > 1 {
  166. lastPart = titles[len(titles)-1]
  167. if lastPart == city || lastPart == area || lastPart == district {
  168. title = strings.Join(titles[:len(titles)-1], splitStr)
  169. } else {
  170. lastPart = ""
  171. }
  172. }
  173. if len([]rune(title)) > 50 {
  174. title = string([]rune(title)[:50])
  175. }
  176. if lastPart != "" {
  177. title = fmt.Sprintf("%s%s%s", title, splitStr, lastPart)
  178. }
  179. }
  180. regionUrl := ""
  181. if district != "" && IC.DistrictMap[district] != "" {
  182. regionUrl = fmt.Sprintf(AreaLabelLink, "city", IC.DistrictMap[district])
  183. } else if city != "" && IC.CityMap[city] != "" {
  184. regionUrl = fmt.Sprintf(AreaLabelLink, "city", IC.CityMap[city])
  185. } else if area != "" && IC.AreaMap[area] != "" {
  186. regionUrl = fmt.Sprintf(AreaLabelLink, "area", IC.AreaMap[area])
  187. }
  188. var price int64
  189. if budget, ok := rv["budget"].(float64); ok && budget > 0 { //预算
  190. price = int64(budget)
  191. }
  192. if bidAmount, ok := rv["bidamount"].(float64); ok && bidAmount > 0 { //中标金额
  193. price = int64(bidAmount)
  194. }
  195. //deliver_area 交付省份//deliver_city 交付城市//deliver_district 交付区县
  196. deliveryLoc := fmt.Sprintf("%s%s%s", MC.InterfaceToStr(rv["deliver_area"]), MC.InterfaceToStr(rv["deliver_city"]), MC.InterfaceToStr(rv["deliver_district"]))
  197. buyer := noPower
  198. buyerTel := noPower
  199. if p.IsPower {
  200. buyer = MC.InterfaceToStr(rv["buyer"])
  201. buyerTel = MC.InterfaceToStr(rv["buyertel"])
  202. }
  203. isValidFile, _ := rv["isValidFile"].(bool)
  204. //buyerPerson := MC.InterfaceToStr(rv["buyerperson"])
  205. //agency := MC.InterfaceToStr(rv["agency"])
  206. //agencyTel := MC.InterfaceToStr(rv["agencytel"])
  207. //agencyPerson := MC.InterfaceToStr(rv["agencyperson"])
  208. //中标信息
  209. var winnerInfo []*bxcore.WinnerInfo
  210. winnerList := MC.ObjToString(rv["s_winner"]) //中标企业名称集合
  211. if winnerList != "" && len(strings.Split(winnerList, ",")) > 0 {
  212. for wk, wv := range strings.Split(winnerList, ",") {
  213. var (
  214. winnerId = ""
  215. )
  216. if rv["entidlist"] != nil {
  217. if entIdList := MC.ObjArrToStringArr(rv["entidlist"].([]interface{})); len(entIdList) > wk { //中标企业id集合
  218. winnerId = entIdList[wk]
  219. }
  220. }
  221. if IC.C.SearchWinner.Switch && winnerId == "" {
  222. continue
  223. }
  224. if entity.RegWinner.MatchString(wv) {
  225. continue
  226. }
  227. winnerInfo = append(winnerInfo, &bxcore.WinnerInfo{
  228. Winner: wv, //中标企业 需要单独处理
  229. WinnerTel: MC.ObjToString(rv["winnertel"]), //中标企业联系电话
  230. WinnerPerson: MC.ObjToString(rv["winnerperson"]), //中标企业联系人
  231. WinnerId: MC.If(winnerId != "" && len([]rune(winnerId)) > 12, encrypt.EncodeArticleId2ByCheck(winnerId), "").(string), //中标企业加密id 存在winnerId 异常的情况
  232. })
  233. }
  234. }
  235. list = append(list, &bxcore.PurchaseList{
  236. Id: encrypt.EncodeArticleId2ByCheck(id),
  237. Area: MC.InterfaceToStr(rv["area"]),
  238. City: MC.InterfaceToStr(rv["city"]),
  239. District: MC.InterfaceToStr(rv["district"]),
  240. RegionUrl: regionUrl,
  241. BuyerClass: MC.InterfaceToStr(rv["buyerclass"]),
  242. PublishTime: MC.Int64All(rv["publishtime"]),
  243. FileExists: isValidFile,
  244. Title: title,
  245. Price: price,
  246. Buyer: buyer,
  247. BuyerTel: buyerTel,
  248. SignEndTime: MC.Int64All(rv["signendtime"]), //报名截止时间
  249. DeliveryLoc: deliveryLoc,
  250. Industry: util.IndustryFormat(p.Industry, strings.Trim(MC.ObjToString(rv["s_subscopeclass"]), ",")),
  251. PublicType: MC.InterfaceToStr(rv["public_type"]),
  252. //BuyerPerson: buyerPerson,
  253. //Agency: agency,
  254. //AgencyTel: agencyTel,
  255. //AgencyPerson: agencyPerson,
  256. //WinnerInfo: winnerInfo,
  257. //BidEndTime: MC.Int64All(rv["bidendtime"]),
  258. //BidOpenTime: MC.Int64All(rv["bidopentime"]), //开标时间,
  259. })
  260. }
  261. return
  262. }
  263. func (p *Purchase) PurchaseQuery() (query string) {
  264. var (
  265. wordsMusts, wordsShould, must, mustNot []string
  266. selectTypeArr = strings.Split(p.SelectType, ",")
  267. selectType = fmt.Sprintf(`"%s"`, strings.Join(selectTypeArr, "\",\""))
  268. )
  269. //发布时间
  270. if len(strings.Split(p.PublishTime, "-")) > 1 {
  271. var (
  272. timeQuery string
  273. startTime, endTime = strings.Split(p.PublishTime, "-")[0], strings.Split(p.PublishTime, "-")[1]
  274. )
  275. if startTime != "" || endTime != "" {
  276. timeQuery += `{"range":{"publishtime":{`
  277. if startTime != "" {
  278. timeQuery += `"gte":` + startTime
  279. }
  280. if startTime != "" && endTime != "" {
  281. timeQuery += `,`
  282. }
  283. if endTime != "" {
  284. timeQuery += `"lt":` + endTime
  285. }
  286. timeQuery += `}}}`
  287. }
  288. if timeQuery != "" {
  289. must = append(must, timeQuery)
  290. }
  291. }
  292. // 关键词
  293. if p.KeyWords != "" {
  294. var (
  295. keyWordsMusts []string
  296. )
  297. for _, v := range strings.Split(p.KeyWords, IC.C.JYKeyMark) {
  298. if elastic.ReplaceYH(v) == "" {
  299. continue
  300. }
  301. keyWordsMusts = append(keyWordsMusts, fmt.Sprintf(fmt.Sprintf(es.MultiMatch, "%s", selectType), elastic.ReplaceYH(v)))
  302. }
  303. //搜索关键词模式;默认0:包含所有,1:包含任意
  304. if p.WordsMode == 1 {
  305. wordsShould = append(wordsShould, fmt.Sprintf(elastic.NgramMust, strings.Join(keyWordsMusts, ",")))
  306. } else {
  307. wordsMusts = append(wordsMusts, keyWordsMusts...)
  308. }
  309. }
  310. //附加词
  311. if p.AdditionalWords != "" {
  312. for _, aws := range strings.Split(p.AdditionalWords, ",") {
  313. //多组附加词,每组间,号隔开。每组内如果关键词中间有空格,自动分词
  314. var (
  315. addWordsMusts []string
  316. )
  317. for _, v := range strings.Split(aws, IC.C.JYKeyMark) {
  318. if elastic.ReplaceYH(v) == "" {
  319. continue
  320. }
  321. addWordsStr := fmt.Sprintf(fmt.Sprintf(es.MultiMatch, "%s", selectType), elastic.ReplaceYH(v))
  322. if p.WordsMode == 0 {
  323. wordsMusts = append(wordsMusts, addWordsStr)
  324. } else {
  325. addWordsMusts = append(addWordsMusts, addWordsStr)
  326. }
  327. }
  328. //搜索关键词模式;默认0:包含所有,1:包含任意
  329. if len(addWordsMusts) > 0 {
  330. wordsShould = append(wordsShould, fmt.Sprintf(elastic.NgramMust, strings.Join(addWordsMusts, ",")))
  331. }
  332. }
  333. }
  334. //搜索关键词模式;默认0:包含所有,1:包含任意
  335. //包含任意一组
  336. if len(wordsShould) > 0 {
  337. must = append(must, fmt.Sprintf(es.QueryBoolShould, strings.Join(wordsShould, ",")))
  338. } else if len(wordsMusts) > 0 {
  339. must = append(must, fmt.Sprintf(elastic.NgramMust, strings.Join(wordsMusts, ",")))
  340. }
  341. //行业
  342. if p.Industry != "" {
  343. must = append(must, fmt.Sprintf(es.QueryBoolMustA, "s_subscopeclass", `"`+strings.ReplaceAll(p.Industry, ",", `","`)+`"`))
  344. }
  345. //附件
  346. if p.FileExists != 0 {
  347. switch p.FileExists {
  348. case 1: //有附件
  349. must = append(must, fmt.Sprintf(es.QueryBoolMustTermBool, "isValidFile", true))
  350. case -1: //无附件
  351. mustNot = append(mustNot, fmt.Sprintf(es.QueryBoolMustTermBool, "isValidFile", true))
  352. }
  353. }
  354. //项目地区
  355. var (
  356. areaQuery []string
  357. areaTerms = `{"terms":{"%s":["%s"]}}`
  358. )
  359. if p.ProjectArea != "" {
  360. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "area", strings.ReplaceAll(p.ProjectArea, ",", "\",\"")))
  361. }
  362. if p.ProjectCity != "" {
  363. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "city", strings.ReplaceAll(p.ProjectCity, ",", "\",\"")))
  364. }
  365. if p.ProjectDistrict != "" {
  366. for _, v := range strings.Split(p.ProjectDistrict, ",") {
  367. if len(strings.Split(v, "_")) > 1 {
  368. cityName := strings.Split(v, "_")[0]
  369. districtName := strings.Split(v, "_")[1]
  370. queryBoolMustAndDistrict := `{"bool":{"must":[{"terms":{"city":["%s"]}},{"terms":{"district":["%s"]}}]}}`
  371. areaQuery = append(areaQuery, fmt.Sprintf(queryBoolMustAndDistrict, cityName, districtName))
  372. }
  373. }
  374. }
  375. if len(areaQuery) > 0 {
  376. must = append(must, fmt.Sprintf(es.QueryBoolShould, strings.Join(areaQuery, ",")))
  377. }
  378. //交付地点
  379. areaQuery = []string{}
  380. if p.DeliveryArea != "" {
  381. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "deliver_area", strings.ReplaceAll(p.DeliveryArea, ",", "\",\"")))
  382. }
  383. if p.DeliveryCity != "" {
  384. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "deliver_city", strings.ReplaceAll(p.DeliveryCity, ",", "\",\"")))
  385. }
  386. if p.DeliveryDistrict != "" {
  387. for _, v := range strings.Split(p.DeliveryDistrict, ",") {
  388. if len(strings.Split(v, "_")) > 1 {
  389. cityName := strings.Split(v, "_")[0]
  390. districtName := strings.Split(v, "_")[1]
  391. queryBoolMustAndDistrict := `{"bool":{"must":[{"terms":{"deliver_city":["%s"]}},{"terms":{"deliver_district":["%s"]}}]}}`
  392. areaQuery = append(areaQuery, fmt.Sprintf(queryBoolMustAndDistrict, cityName, districtName))
  393. }
  394. }
  395. }
  396. if len(areaQuery) > 0 {
  397. must = append(must, fmt.Sprintf(es.QueryBoolShould, strings.Join(areaQuery, ",")))
  398. }
  399. //发布方式
  400. if p.Publisher > 0 {
  401. must = append(must, fmt.Sprintf(es.QueryBoolMustTerm, "public_type", es.PurchasePublicType[p.Publisher-1]))
  402. }
  403. //截止时间
  404. if p.DeadlineStart > 0 || p.DeadlineEnd > 0 {
  405. var timeQuery string
  406. timeQuery += `{"range":{"signendtime":{`
  407. if p.DeadlineStart > 0 {
  408. timeQuery += fmt.Sprintf(`"gte":%d`, p.DeadlineStart)
  409. }
  410. if p.DeadlineStart > 0 && p.DeadlineEnd > 0 {
  411. timeQuery += `,`
  412. }
  413. if p.DeadlineEnd > 0 {
  414. timeQuery += fmt.Sprintf(`"lt":%d`, p.DeadlineEnd)
  415. }
  416. timeQuery += `}}}`
  417. must = append(must, timeQuery)
  418. }
  419. //领域
  420. areaQuery = []string{}
  421. if p.DomainFirstType != "" {
  422. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "domain_firsttype", strings.ReplaceAll(p.DomainFirstType, ",", "\",\"")))
  423. }
  424. if p.DomainSecondType != "" {
  425. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "domain_secondtype", strings.ReplaceAll(p.DomainSecondType, ",", "\",\"")))
  426. }
  427. if p.DomainThirdType != "" {
  428. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "domain_thirdtype", strings.ReplaceAll(p.DomainThirdType, ",", "\",\"")))
  429. }
  430. if len(areaQuery) > 0 {
  431. must = append(must, fmt.Sprintf(es.QueryBoolShould, strings.Join(areaQuery, ",")))
  432. }
  433. //直采 采购信息 搜索
  434. query = fmt.Sprintf(es.Query, strings.Join(must, ","), strings.Join(mustNot, ","))
  435. log.Println("zc-query:", query)
  436. return
  437. }
  438. func (p *Purchase) FindDataFromES() (int64, []map[string]interface{}, error) {
  439. var (
  440. start = int((p.PageNum - 1) * p.PageSize)
  441. total int64
  442. list *[]map[string]interface{}
  443. err error
  444. fields = es.PurchaseBaseFieldForPayer
  445. )
  446. if IC.C.PurchaseDiffSwitch {
  447. if !p.IsPay {
  448. fields = es.PurchaseBaseField
  449. }
  450. }
  451. biddingSearch := es.SearchByES{
  452. Index: es.PurchaseIndex,
  453. IType: es.PurchaseType,
  454. Query: p.PurchaseQuery(),
  455. FindFields: p.SelectType,
  456. Order: es.PurchaseSearchSort,
  457. Fields: fields,
  458. Start: start,
  459. Limit: int(p.PageSize),
  460. Count: 0, //高亮正文数量
  461. HighLight: false, //是否高亮正文
  462. }
  463. total, list = biddingSearch.GetAllByNgramWithCount(es.LoginTypePay)
  464. if total == 0 || list == nil {
  465. log.Println(fmt.Errorf("暂无数据"))
  466. return 0, nil, nil
  467. }
  468. return total, *list, err
  469. }
  470. var (
  471. redisCode = "newother"
  472. purchaseCacheKey = "purchase_cache_data"
  473. purchaseCacheExpire = 4 * 60 * 60
  474. )
  475. func (p *Purchase) GetPurchaseData() (list []*bxcore.PurchaseList, err error) {
  476. var (
  477. res []map[string]interface{}
  478. total int64
  479. )
  480. if p.IsEmptySearch() {
  481. //查缓存
  482. cacheBytes, err := redis.GetBytes(redisCode, purchaseCacheKey)
  483. start := int((p.PageNum - 1) * p.PageSize)
  484. if err == nil && len(*cacheBytes) > start {
  485. end := int(p.PageNum * p.PageSize)
  486. if end > len(*cacheBytes) {
  487. end = len(*cacheBytes)
  488. }
  489. total = int64(len(*cacheBytes))
  490. err = json.Unmarshal((*cacheBytes)[start:end], &res)
  491. }
  492. if len(res) == 0 {
  493. p.PageNum = 1
  494. pageSize := p.PageSize
  495. start = int((p.PageNum - 1) * p.PageSize)
  496. end := int(p.PageNum * p.PageSize)
  497. p.PageSize = int64(util.SearchPageSize * util.SearchMaxPageNum)
  498. total, res, err = p.FindDataFromES()
  499. log.Println(total, "----------缓存数据:", len(res))
  500. if total > 0 && len(res) > 0 {
  501. var b []byte
  502. b, err = json.Marshal(res)
  503. log.Println(b, "----------------002---------------------", err)
  504. if err == nil && len(b) > 0 {
  505. err = redis.PutBytes(redisCode, purchaseCacheKey, &b, purchaseCacheExpire)
  506. }
  507. if end > len(res) {
  508. end = len(res)
  509. }
  510. res = res[start:end]
  511. }
  512. p.PageSize = pageSize
  513. }
  514. } else {
  515. //实时查询
  516. total, res, err = p.FindDataFromES()
  517. }
  518. if len(res) > 0 {
  519. p.Total = total
  520. p.Count = int64(util.SearchPageSize * util.SearchMaxPageNum)
  521. if p.Count > total {
  522. p.Count = total
  523. }
  524. list = p.PurchaseListFormat(res)
  525. }
  526. return
  527. }
  528. // 关键词 附加词 行业
  529. func (p *Purchase) IsEmptySearch() bool {
  530. if p.KeyWords != "" || p.AdditionalWords != "" || p.Industry != "" {
  531. return false
  532. }
  533. return true
  534. }
  535. var (
  536. purchaseSelectTypeMap = map[string]bool{
  537. "title": true,
  538. "purchasing": true,
  539. }
  540. tipMsg = "“%s“及其后面的字词均被忽略,因为剑鱼标讯的查询限制在%d个汉字以内。"
  541. )
  542. // 筛选条件格式化
  543. func (p *Purchase) FilterCriteriaFormat() {
  544. if p.UserId != "" {
  545. //判断用户身份
  546. userInfo := IC.Middleground.PowerCheckCenter.Check(p.AppId, p.MgoUserId, p.BaseUserId, p.AccountId, p.EntId, p.PositionType, p.PositionId)
  547. if userInfo != nil {
  548. p.IsPay = !userInfo.Free.IsFree
  549. }
  550. res := IC.Middleground.ResourceCenter.Haspowers(p.AccountId, p.EntAccountId, p.EntId, p.EntUserId)
  551. if res != nil {
  552. p.IsPower = strings.Contains(strings.Join(res.Powers, ","), IC.C.PurchaseCode)
  553. }
  554. }
  555. //搜索范围
  556. if p.SelectType != "" {
  557. var selectTypes []string
  558. for _, sv := range strings.Split(p.SelectType, ",") {
  559. if purchaseSelectTypeMap[sv] {
  560. selectTypes = append(selectTypes, sv)
  561. }
  562. }
  563. if len(selectTypes) > 0 {
  564. p.SelectType = strings.Join(selectTypes, ",")
  565. }
  566. }
  567. if p.SelectType == "" {
  568. p.SelectType = "title"
  569. }
  570. // p.SearchMode 搜索模式:0:精准搜索;1:模糊搜索
  571. // 精准搜索:不分词,完全匹配;(中间带空格的关键词组自动分词)
  572. // 模糊搜索:对用户输入的单个关键词进行分词处理,但必须都存在;
  573. if p.SearchMode < 0 || p.SearchMode > 1 {
  574. p.SearchMode = 0
  575. }
  576. // p.WordsMode 搜索关键词模式;默认0:包含所有,1:包含任意
  577. if p.WordsMode < 0 || p.WordsMode > 1 {
  578. p.WordsMode = 0
  579. }
  580. //发布时间--默认最近一年
  581. if p.PublishTime == "" {
  582. p.PublishTime = fmt.Sprintf("%d-%d", time.Now().AddDate(-1, 0, 0).Unix(), time.Now().Unix())
  583. }
  584. //默认每页数据量
  585. if p.PageSize <= 0 || p.PageSize > 100 {
  586. p.PageSize = 50
  587. }
  588. //第一页
  589. if p.PageNum <= 0 || p.PageNum > int64(IC.C.DefaultBidInfo.Count)/p.PageSize {
  590. p.PageNum = 1
  591. }
  592. //行业
  593. if p.Industry != "" {
  594. p.Industry = strings.TrimSpace(p.Industry)
  595. //P510 行业:其它
  596. if qt := jy.IndustryHandle(p.Industry); len(qt) > 0 {
  597. p.Industry = fmt.Sprintf("%s,%s", p.Industry, strings.Join(qt, ","))
  598. }
  599. }
  600. var (
  601. searchWords []string
  602. )
  603. //关键词
  604. if p.KeyWords != "" {
  605. p.KeyWords = strings.TrimSpace(p.KeyWords)
  606. _, p.TipMsg, p.KeyWords = util.InterceptSearchKW(p.KeyWords, MC.IntAllDef(IC.C.KeywordsLimit, 35), true)
  607. if p.TipMsg != "" {
  608. p.TipMsg = fmt.Sprintf(tipMsg, p.TipMsg, MC.IntAllDef(IC.C.KeywordsLimit, 35))
  609. }
  610. // in.SearchMode 搜索模式:0:精准搜索;1:模糊搜索
  611. // 精准搜索:不分词,完全匹配;(中间带空格的关键词组自动分词)
  612. // 模糊搜索:对用户输入的单个关键词进行分词处理,但必须都存在;
  613. //主关键词词组
  614. if p.SearchMode == 1 {
  615. if ikWords := util.HttpEs(p.KeyWords, "ik_smart", IC.DB.Es.Addr); ikWords != "" {
  616. p.KeyWords = jy.KeywordsProcessing(ikWords, IC.C.JYKeyMark)
  617. }
  618. }
  619. searchWords = append(searchWords, p.KeyWords)
  620. }
  621. //附加词 每组附加词不能超过15个字符
  622. if p.AdditionalWords != "" {
  623. var additionalWords []string
  624. for _, ak := range strings.Split(p.AdditionalWords, ",") {
  625. if len([]rune(ak)) > 15 {
  626. additionalWords = append(additionalWords, string([]rune(ak)[:15]))
  627. } else {
  628. additionalWords = append(additionalWords, ak)
  629. }
  630. }
  631. p.AdditionalWords = strings.Join(additionalWords, ",") //分组不变
  632. //多组附加词,每组间,号隔开。每组内如果关键词中间有空格,自动分词
  633. if p.SearchMode == 1 {
  634. var (
  635. addWords []string
  636. )
  637. for _, awv := range strings.Split(p.AdditionalWords, ",") {
  638. if strings.TrimSpace(awv) != "" {
  639. if ikWords := util.HttpEs(awv, "ik_smart", IC.DB.Es.Addr); ikWords != "" {
  640. addWords = append(addWords, jy.KeywordsProcessing(ikWords, IC.C.JYKeyMark))
  641. }
  642. }
  643. }
  644. if len(addWords) > 0 {
  645. p.AdditionalWords = strings.Join(addWords, ",")
  646. }
  647. }
  648. searchWords = append(searchWords, strings.Split(p.AdditionalWords, ",")...)
  649. }
  650. p.HighlightWords = strings.Join(searchWords, ",")
  651. //报名截止
  652. if p.DeadlineStatus < 0 || p.DeadlineStatus > 2 {
  653. p.DeadlineStatus = 0
  654. }
  655. if len(strings.Split(p.DeadlineTime, "-")) > 1 {
  656. p.DeadlineStart, _ = strconv.ParseInt(strings.Split(p.DeadlineTime, "-")[0], 10, 64)
  657. p.DeadlineEnd, _ = strconv.ParseInt(strings.Split(p.DeadlineTime, "-")[1], 10, 64)
  658. if p.DeadlineEnd < p.DeadlineStart {
  659. var deadline = p.DeadlineStart
  660. p.DeadlineStart = p.DeadlineEnd
  661. p.DeadlineEnd = deadline
  662. }
  663. }
  664. switch p.DeadlineStatus {
  665. case 1: //未截止
  666. if p.DeadlineEnd < time.Now().Unix() {
  667. p.DeadlineStart = time.Now().Unix()
  668. p.DeadlineEnd = 0
  669. }
  670. case 2: //已截止
  671. if p.DeadlineEnd == 0 || p.DeadlineEnd > time.Now().Unix() {
  672. p.DeadlineStart = 0
  673. p.DeadlineEnd = time.Now().Unix()
  674. }
  675. }
  676. //发布平台
  677. if p.Publisher < 0 || p.Publisher > int64(len(es.PurchasePublicType)) {
  678. p.Publisher = 0
  679. }
  680. //空搜索 其它筛选条件 无效
  681. if p.IsEmptySearch() {
  682. //
  683. p.DomainFirstType = ""
  684. p.DomainSecondType = ""
  685. p.DomainThirdType = ""
  686. p.DeadlineStatus = 0
  687. p.DeadlineStart = 0
  688. p.DeadlineEnd = 0
  689. p.DeliveryArea = ""
  690. p.DeliveryCity = ""
  691. p.DeliveryDistrict = ""
  692. p.ProjectArea = ""
  693. p.ProjectCity = ""
  694. p.ProjectDistrict = ""
  695. p.FileExists = 0
  696. p.Publisher = 0
  697. }
  698. }