purchase.go 26 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. InterceptKeyWords string `json:"interceptKeyWords"`
  66. }
  67. func NewPurchase(in *bxcore.PurchaseReq) *Purchase {
  68. baseUserId, _ := strconv.ParseInt(in.NewUserId, 10, 64)
  69. accountId, _ := strconv.ParseInt(in.AccountId, 10, 64)
  70. positionId, _ := strconv.ParseInt(in.PositionId, 10, 64)
  71. return &Purchase{
  72. AppId: in.AppId,
  73. UserId: in.UserId,
  74. Phone: in.Phone,
  75. BaseUserId: baseUserId,
  76. EntId: in.EntId,
  77. EntUserId: in.EntUserId,
  78. AccountId: accountId,
  79. EntAccountId: in.EntAccountId,
  80. PositionType: in.PositionType,
  81. PositionId: positionId,
  82. MgoUserId: in.MgoUserId,
  83. PageNum: in.PageNum,
  84. PageSize: in.PageSize,
  85. PublishTime: in.PublishTime,
  86. SelectType: in.SelectType,
  87. DomainFirstType: in.DomainFirstType,
  88. DomainSecondType: in.DomainSecondType,
  89. DomainThirdType: in.DomainThirdType,
  90. DeadlineStatus: in.DeadlineStatus,
  91. DeadlineTime: in.DeadlineTime,
  92. DeliveryArea: in.DeliveryArea,
  93. DeliveryCity: in.DeliveryCity,
  94. DeliveryDistrict: in.DeliveryDistrict,
  95. ProjectArea: in.ProjectArea,
  96. ProjectCity: in.ProjectCity,
  97. ProjectDistrict: in.ProjectDistrict,
  98. Industry: in.Industry,
  99. FileExists: in.FileExists,
  100. Publisher: in.Publisher,
  101. KeyWords: in.KeyWords,
  102. AdditionalWords: in.AdditionalWords,
  103. SearchMode: in.SearchMode,
  104. WordsMode: in.WordsMode,
  105. UserAgent: in.UserAgent,
  106. Platform: in.Platform,
  107. }
  108. }
  109. var (
  110. AreaLabelLink = "/list/%s/%s.html"
  111. noPower = "点击查看"
  112. )
  113. // 缓存
  114. func (p *Purchase) HistoryKeywords() {
  115. var (
  116. cacheKey = fmt.Sprintf("history_purchase_v_%s", p.UserId)
  117. keys []string
  118. code = "other"
  119. isExist = map[string]bool{}
  120. duplicateRemoval = func(values []string) (keys []string) {
  121. for _, kv := range values {
  122. kv = strings.TrimSpace(kv)
  123. if isExist[kv] {
  124. continue
  125. }
  126. isExist[kv] = true
  127. keys = append(keys, kv)
  128. }
  129. return
  130. }
  131. )
  132. values := redis.GetStr(code, cacheKey)
  133. if values != "" {
  134. keys = append(keys, duplicateRemoval(strings.Split(values, ","))...)
  135. }
  136. if p.KeyWords != "" {
  137. keys = append(keys, duplicateRemoval(strings.Split(p.KeyWords, ","))...)
  138. }
  139. if p.AdditionalWords != "" {
  140. keys = append(keys, duplicateRemoval(strings.Split(p.AdditionalWords, ","))...)
  141. }
  142. if len(keys) > 10 {
  143. keys = keys[len(keys)-10:]
  144. }
  145. ok := redis.Put(code, cacheKey, strings.Join(keys, ","), -1)
  146. if !ok {
  147. logx.Info(" history keywords err:", keys)
  148. }
  149. }
  150. // 格式化
  151. func (p *Purchase) PurchaseListFormat(res []map[string]interface{}) (list []*bxcore.PurchaseList) {
  152. for _, rv := range res {
  153. logx.Info("title:", MC.InterfaceToStr(rv["title"]))
  154. id := MC.InterfaceToStr(rv["source_id"]) //拆分后 多条数据会来自一条bidding数据嘛,把bidding的id记一个source_id;mongo 库中bidding的_id
  155. if id == "" {
  156. continue
  157. }
  158. area := MC.InterfaceToStr(rv["area"])
  159. city := MC.InterfaceToStr(rv["city"])
  160. district := MC.InterfaceToStr(rv["district"])
  161. title := MC.InterfaceToStr(rv["title"])
  162. if len([]rune(title)) > 50 {
  163. splitStr := "-"
  164. titles := strings.Split(title, splitStr)
  165. lastPart := ""
  166. if len(titles) > 1 {
  167. lastPart = titles[len(titles)-1]
  168. if lastPart == city || lastPart == area || lastPart == district {
  169. title = strings.Join(titles[:len(titles)-1], splitStr)
  170. } else {
  171. lastPart = ""
  172. }
  173. }
  174. if len([]rune(title)) > 50 {
  175. title = string([]rune(title)[:50])
  176. }
  177. if lastPart != "" {
  178. title = fmt.Sprintf("%s%s%s", title, splitStr, lastPart)
  179. }
  180. }
  181. regionUrl := ""
  182. if district != "" && IC.DistrictMap[district] != "" {
  183. regionUrl = fmt.Sprintf(AreaLabelLink, "city", IC.DistrictMap[district])
  184. } else if city != "" && IC.CityMap[city] != "" {
  185. regionUrl = fmt.Sprintf(AreaLabelLink, "city", IC.CityMap[city])
  186. } else if area != "" && IC.AreaMap[area] != "" {
  187. regionUrl = fmt.Sprintf(AreaLabelLink, "area", IC.AreaMap[area])
  188. }
  189. var price int64
  190. if budget, ok := rv["budget"].(float64); ok && budget > 0 { //预算
  191. price = int64(budget)
  192. }
  193. if bidAmount, ok := rv["bidamount"].(float64); ok && bidAmount > 0 { //中标金额
  194. price = int64(bidAmount)
  195. }
  196. //deliver_area 交付省份//deliver_city 交付城市//deliver_district 交付区县
  197. deliveryLoc := fmt.Sprintf("%s%s%s", MC.InterfaceToStr(rv["deliver_area"]), MC.InterfaceToStr(rv["deliver_city"]), MC.InterfaceToStr(rv["deliver_district"]))
  198. buyer := noPower
  199. buyerTel := noPower
  200. if p.IsPower {
  201. buyer = MC.InterfaceToStr(rv["buyer"])
  202. buyerTel = MC.InterfaceToStr(rv["buyertel"])
  203. }
  204. isValidFile, _ := rv["isValidFile"].(bool)
  205. //buyerPerson := MC.InterfaceToStr(rv["buyerperson"])
  206. //agency := MC.InterfaceToStr(rv["agency"])
  207. //agencyTel := MC.InterfaceToStr(rv["agencytel"])
  208. //agencyPerson := MC.InterfaceToStr(rv["agencyperson"])
  209. //中标信息
  210. var winnerInfo []*bxcore.WinnerInfo
  211. winnerList := MC.ObjToString(rv["s_winner"]) //中标企业名称集合
  212. if winnerList != "" && len(strings.Split(winnerList, ",")) > 0 {
  213. for wk, wv := range strings.Split(winnerList, ",") {
  214. var (
  215. winnerId = ""
  216. )
  217. if rv["entidlist"] != nil {
  218. if entIdList := MC.ObjArrToStringArr(rv["entidlist"].([]interface{})); len(entIdList) > wk { //中标企业id集合
  219. winnerId = entIdList[wk]
  220. }
  221. }
  222. if IC.C.SearchWinner.Switch && winnerId == "" {
  223. continue
  224. }
  225. if entity.RegWinner.MatchString(wv) {
  226. continue
  227. }
  228. winnerInfo = append(winnerInfo, &bxcore.WinnerInfo{
  229. Winner: wv, //中标企业 需要单独处理
  230. WinnerTel: MC.ObjToString(rv["winnertel"]), //中标企业联系电话
  231. WinnerPerson: MC.ObjToString(rv["winnerperson"]), //中标企业联系人
  232. WinnerId: MC.If(winnerId != "" && len([]rune(winnerId)) > 12, encrypt.EncodeArticleId2ByCheck(winnerId), "").(string), //中标企业加密id 存在winnerId 异常的情况
  233. })
  234. }
  235. }
  236. list = append(list, &bxcore.PurchaseList{
  237. Id: encrypt.EncodeArticleId2ByCheck(id),
  238. Area: MC.InterfaceToStr(rv["area"]),
  239. City: MC.InterfaceToStr(rv["city"]),
  240. District: MC.InterfaceToStr(rv["district"]),
  241. RegionUrl: regionUrl,
  242. BuyerClass: MC.InterfaceToStr(rv["buyerclass"]),
  243. PublishTime: MC.Int64All(rv["publishtime"]),
  244. FileExists: isValidFile,
  245. Title: title,
  246. Price: price,
  247. Buyer: buyer,
  248. BuyerTel: buyerTel,
  249. SignEndTime: MC.Int64All(rv["signendtime"]), //报名截止时间
  250. DeliveryLoc: deliveryLoc,
  251. Industry: util.IndustryFormat(p.Industry, strings.Trim(MC.ObjToString(rv["s_subscopeclass"]), ",")),
  252. PublicType: MC.InterfaceToStr(rv["public_type"]),
  253. //BuyerPerson: buyerPerson,
  254. //Agency: agency,
  255. //AgencyTel: agencyTel,
  256. //AgencyPerson: agencyPerson,
  257. //WinnerInfo: winnerInfo,
  258. //BidEndTime: MC.Int64All(rv["bidendtime"]),
  259. //BidOpenTime: MC.Int64All(rv["bidopentime"]), //开标时间,
  260. })
  261. }
  262. return
  263. }
  264. func (p *Purchase) PurchaseQuery() (query string) {
  265. var (
  266. wordsMusts, wordsShould, must, mustNot []string
  267. selectTypeArr = strings.Split(p.SelectType, ",")
  268. selectType = fmt.Sprintf(`"%s"`, strings.Join(selectTypeArr, "\",\""))
  269. )
  270. //发布时间
  271. if len(strings.Split(p.PublishTime, "-")) > 1 {
  272. var (
  273. timeQuery string
  274. startTime, endTime = strings.Split(p.PublishTime, "-")[0], strings.Split(p.PublishTime, "-")[1]
  275. )
  276. if startTime != "" || endTime != "" {
  277. timeQuery += `{"range":{"publishtime":{`
  278. if startTime != "" {
  279. timeQuery += `"gte":` + startTime
  280. }
  281. if startTime != "" && endTime != "" {
  282. timeQuery += `,`
  283. }
  284. if endTime != "" {
  285. timeQuery += `"lt":` + endTime
  286. }
  287. timeQuery += `}}}`
  288. }
  289. if timeQuery != "" {
  290. must = append(must, timeQuery)
  291. }
  292. }
  293. // 关键词
  294. if p.KeyWords != "" {
  295. var (
  296. keyWordsMusts []string
  297. )
  298. for _, v := range strings.Split(p.KeyWords, IC.C.JYKeyMark) {
  299. if elastic.ReplaceYH(v) == "" {
  300. continue
  301. }
  302. keyWordsMusts = append(keyWordsMusts, fmt.Sprintf(fmt.Sprintf(es.MultiMatch, "%s", selectType), elastic.ReplaceYH(v)))
  303. }
  304. //搜索关键词模式;默认0:包含所有,1:包含任意
  305. if p.WordsMode == 1 {
  306. wordsShould = append(wordsShould, fmt.Sprintf(elastic.NgramMust, strings.Join(keyWordsMusts, ",")))
  307. } else {
  308. wordsMusts = append(wordsMusts, keyWordsMusts...)
  309. }
  310. }
  311. //附加词
  312. if p.AdditionalWords != "" {
  313. for _, aws := range strings.Split(p.AdditionalWords, ",") {
  314. //多组附加词,每组间,号隔开。每组内如果关键词中间有空格,自动分词
  315. var (
  316. addWordsMusts []string
  317. )
  318. for _, v := range strings.Split(aws, IC.C.JYKeyMark) {
  319. if elastic.ReplaceYH(v) == "" {
  320. continue
  321. }
  322. addWordsStr := fmt.Sprintf(fmt.Sprintf(es.MultiMatch, "%s", selectType), elastic.ReplaceYH(v))
  323. if p.WordsMode == 0 {
  324. wordsMusts = append(wordsMusts, addWordsStr)
  325. } else {
  326. addWordsMusts = append(addWordsMusts, addWordsStr)
  327. }
  328. }
  329. //搜索关键词模式;默认0:包含所有,1:包含任意
  330. if len(addWordsMusts) > 0 {
  331. wordsShould = append(wordsShould, fmt.Sprintf(elastic.NgramMust, strings.Join(addWordsMusts, ",")))
  332. }
  333. }
  334. }
  335. //搜索关键词模式;默认0:包含所有,1:包含任意
  336. //包含任意一组
  337. if len(wordsShould) > 0 {
  338. must = append(must, fmt.Sprintf(es.QueryBoolShould, strings.Join(wordsShould, ",")))
  339. } else if len(wordsMusts) > 0 {
  340. must = append(must, fmt.Sprintf(elastic.NgramMust, strings.Join(wordsMusts, ",")))
  341. }
  342. //行业
  343. if p.Industry != "" {
  344. must = append(must, fmt.Sprintf(es.QueryBoolMustA, "s_subscopeclass", `"`+strings.ReplaceAll(p.Industry, ",", `","`)+`"`))
  345. }
  346. //附件
  347. if p.FileExists != 0 {
  348. switch p.FileExists {
  349. case 1: //有附件
  350. must = append(must, fmt.Sprintf(es.QueryBoolMustTermBool, "isValidFile", true))
  351. case -1: //无附件
  352. mustNot = append(mustNot, fmt.Sprintf(es.QueryBoolMustTermBool, "isValidFile", true))
  353. }
  354. }
  355. //项目地区
  356. var (
  357. areaQuery []string
  358. areaTerms = `{"terms":{"%s":["%s"]}}`
  359. )
  360. if p.ProjectArea != "" {
  361. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "area", strings.ReplaceAll(p.ProjectArea, ",", "\",\"")))
  362. }
  363. if p.ProjectCity != "" {
  364. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "city", strings.ReplaceAll(p.ProjectCity, ",", "\",\"")))
  365. }
  366. if p.ProjectDistrict != "" {
  367. for _, v := range strings.Split(p.ProjectDistrict, ",") {
  368. if len(strings.Split(v, "_")) > 1 {
  369. cityName := strings.Split(v, "_")[0]
  370. districtName := strings.Split(v, "_")[1]
  371. queryBoolMustAndDistrict := `{"bool":{"must":[{"terms":{"city":["%s"]}},{"terms":{"district":["%s"]}}]}}`
  372. areaQuery = append(areaQuery, fmt.Sprintf(queryBoolMustAndDistrict, cityName, districtName))
  373. }
  374. }
  375. }
  376. if len(areaQuery) > 0 {
  377. must = append(must, fmt.Sprintf(es.QueryBoolShould, strings.Join(areaQuery, ",")))
  378. }
  379. //交付地点
  380. areaQuery = []string{}
  381. if p.DeliveryArea != "" {
  382. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "deliver_area", strings.ReplaceAll(p.DeliveryArea, ",", "\",\"")))
  383. }
  384. if p.DeliveryCity != "" {
  385. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "deliver_city", strings.ReplaceAll(p.DeliveryCity, ",", "\",\"")))
  386. }
  387. if p.DeliveryDistrict != "" {
  388. for _, v := range strings.Split(p.DeliveryDistrict, ",") {
  389. if len(strings.Split(v, "_")) > 1 {
  390. cityName := strings.Split(v, "_")[0]
  391. districtName := strings.Split(v, "_")[1]
  392. queryBoolMustAndDistrict := `{"bool":{"must":[{"terms":{"deliver_city":["%s"]}},{"terms":{"deliver_district":["%s"]}}]}}`
  393. areaQuery = append(areaQuery, fmt.Sprintf(queryBoolMustAndDistrict, cityName, districtName))
  394. }
  395. }
  396. }
  397. if len(areaQuery) > 0 {
  398. must = append(must, fmt.Sprintf(es.QueryBoolShould, strings.Join(areaQuery, ",")))
  399. }
  400. //发布方式
  401. if p.Publisher > 0 {
  402. must = append(must, fmt.Sprintf(es.QueryBoolMustTerm, "public_type", es.PurchasePublicType[p.Publisher-1]))
  403. }
  404. //截止时间
  405. if p.DeadlineStart > 0 || p.DeadlineEnd > 0 {
  406. var timeQuery string
  407. timeQuery += `{"range":{"signendtime":{`
  408. if p.DeadlineStart > 0 {
  409. timeQuery += fmt.Sprintf(`"gte":%d`, p.DeadlineStart)
  410. }
  411. if p.DeadlineStart > 0 && p.DeadlineEnd > 0 {
  412. timeQuery += `,`
  413. }
  414. if p.DeadlineEnd > 0 {
  415. timeQuery += fmt.Sprintf(`"lt":%d`, p.DeadlineEnd)
  416. }
  417. timeQuery += `}}}`
  418. must = append(must, timeQuery)
  419. }
  420. //领域
  421. areaQuery = []string{}
  422. if p.DomainFirstType != "" {
  423. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "domain_firsttype", strings.ReplaceAll(p.DomainFirstType, ",", "\",\"")))
  424. }
  425. if p.DomainSecondType != "" {
  426. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "domain_secondtype", strings.ReplaceAll(p.DomainSecondType, ",", "\",\"")))
  427. }
  428. if p.DomainThirdType != "" {
  429. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "domain_thirdtype", strings.ReplaceAll(p.DomainThirdType, ",", "\",\"")))
  430. }
  431. if len(areaQuery) > 0 {
  432. must = append(must, fmt.Sprintf(es.QueryBoolShould, strings.Join(areaQuery, ",")))
  433. }
  434. //直采 采购信息 搜索
  435. query = fmt.Sprintf(es.Query, strings.Join(must, ","), strings.Join(mustNot, ","))
  436. log.Println("zc-query:", query)
  437. return
  438. }
  439. func (p *Purchase) FindDataFromES() (int64, []map[string]interface{}, error) {
  440. var (
  441. start = int((p.PageNum - 1) * p.PageSize)
  442. total int64
  443. list *[]map[string]interface{}
  444. err error
  445. fields = es.PurchaseBaseFieldForPayer
  446. )
  447. if IC.C.PurchaseDiffSwitch {
  448. if !p.IsPay {
  449. fields = es.PurchaseBaseField
  450. }
  451. }
  452. biddingSearch := es.SearchByES{
  453. Index: es.PurchaseIndex,
  454. IType: es.PurchaseType,
  455. Query: p.PurchaseQuery(),
  456. FindFields: p.SelectType,
  457. Order: es.PurchaseSearchSort,
  458. Fields: fields,
  459. Start: start,
  460. Limit: int(p.PageSize),
  461. Count: 0, //高亮正文数量
  462. HighLight: false, //是否高亮正文
  463. }
  464. total, list = biddingSearch.GetAllByNgramWithCount(es.LoginTypePay)
  465. if total == 0 || list == nil {
  466. log.Println(fmt.Errorf("暂无数据"))
  467. return 0, nil, nil
  468. }
  469. return total, *list, err
  470. }
  471. var (
  472. redisCode = "newother"
  473. purchaseDataCacheKey = "purchase_cache_data"
  474. purchaseCountCacheKey = "purchase_cache_count"
  475. purchaseCacheExpire = 8 * 60 * 60
  476. )
  477. func (p *Purchase) GetPurchaseData() (list []*bxcore.PurchaseList, err error) {
  478. var (
  479. res []map[string]interface{}
  480. total int64
  481. )
  482. if p.IsEmptySearch() {
  483. //查缓存
  484. cacheBytes, err := redis.GetBytes(redisCode, purchaseDataCacheKey)
  485. start := int((p.PageNum - 1) * p.PageSize)
  486. end := int(p.PageNum * p.PageSize)
  487. if err == nil && len(*cacheBytes) > start {
  488. if end > len(*cacheBytes) {
  489. end = len(*cacheBytes)
  490. }
  491. total = int64(redis.GetInt(redisCode, purchaseCountCacheKey))
  492. err = json.Unmarshal(*cacheBytes, &res)
  493. }
  494. if len(res) == 0 {
  495. p.PageNum = 1
  496. pageSize := p.PageSize
  497. start = int((p.PageNum - 1) * p.PageSize)
  498. p.PageSize = int64(util.SearchPageSize * util.SearchMaxPageNum)
  499. total, res, err = p.FindDataFromES()
  500. if total > 0 && len(res) > 0 {
  501. var b []byte
  502. b, err = json.Marshal(res)
  503. if err == nil && len(b) > 0 {
  504. err = redis.PutBytes(redisCode, purchaseDataCacheKey, &b, purchaseCacheExpire)
  505. redis.Put(redisCode, purchaseCountCacheKey, total, purchaseCacheExpire)
  506. }
  507. if end > len(res) {
  508. end = len(res)
  509. }
  510. }
  511. p.PageSize = pageSize
  512. }
  513. res = res[start:end]
  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.InterceptKeyWords, 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. }