purchase.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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. var (
  151. titleSuffix = "%s等"
  152. )
  153. // 格式化
  154. func (p *Purchase) PurchaseListFormat(res []map[string]interface{}) (list []*bxcore.PurchaseList) {
  155. for _, rv := range res {
  156. logx.Info("title:", MC.InterfaceToStr(rv["title"]))
  157. id := MC.InterfaceToStr(rv["source_id"]) //拆分后 多条数据会来自一条bidding数据嘛,把bidding的id记一个source_id;mongo 库中bidding的_id
  158. if id == "" {
  159. continue
  160. }
  161. area := MC.InterfaceToStr(rv["area"])
  162. city := MC.InterfaceToStr(rv["city"])
  163. district := MC.InterfaceToStr(rv["district"])
  164. title := MC.InterfaceToStr(rv["title"])
  165. originalTitle := title
  166. if len([]rune(title)) > 50 {
  167. splitStr := "-"
  168. titles := strings.Split(title, splitStr)
  169. lastPart := ""
  170. if len(titles) > 1 {
  171. lastPart = titles[len(titles)-1]
  172. if lastPart == city || lastPart == area || lastPart == district {
  173. title = strings.Join(titles[:len(titles)-1], splitStr)
  174. } else {
  175. lastPart = ""
  176. }
  177. }
  178. if len([]rune(title)) > 50 {
  179. title = fmt.Sprintf(titleSuffix, string([]rune(title)[:50]))
  180. }
  181. if lastPart != "" {
  182. title = fmt.Sprintf("%s%s%s", title, splitStr, lastPart)
  183. }
  184. }
  185. publicType := MC.InterfaceToStr(rv["public_type"])
  186. if publicType == "平台发布" && rv["purchasinglist"] != nil {
  187. purchasingList := MC.ObjArrToMapArr(rv["purchasinglist"].([]interface{}))
  188. if len(purchasingList) > 1 {
  189. originalTitle = fmt.Sprintf(titleSuffix, originalTitle)
  190. }
  191. }
  192. regionUrl := ""
  193. if district != "" && IC.DistrictMap[district] != "" {
  194. regionUrl = fmt.Sprintf(AreaLabelLink, "city", IC.DistrictMap[district])
  195. } else if city != "" && IC.CityMap[city] != "" {
  196. regionUrl = fmt.Sprintf(AreaLabelLink, "city", IC.CityMap[city])
  197. } else if area != "" && IC.AreaMap[area] != "" {
  198. regionUrl = fmt.Sprintf(AreaLabelLink, "area", IC.AreaMap[area])
  199. }
  200. var price int64
  201. if budget, ok := rv["budget"].(float64); ok && budget > 0 { //预算
  202. price = int64(budget)
  203. }
  204. if bidAmount, ok := rv["bidamount"].(float64); ok && bidAmount > 0 { //中标金额
  205. price = int64(bidAmount)
  206. }
  207. //deliver_area 交付省份//deliver_city 交付城市//deliver_district 交付区县
  208. deliveryLoc := fmt.Sprintf("%s%s%s", MC.InterfaceToStr(rv["deliver_area"]), MC.InterfaceToStr(rv["deliver_city"]), MC.InterfaceToStr(rv["deliver_district"]))
  209. buyer := noPower
  210. buyerTel := noPower
  211. if p.IsPower {
  212. buyer = MC.InterfaceToStr(rv["buyer"])
  213. buyerTel = MC.InterfaceToStr(rv["buyertel"])
  214. }
  215. isValidFile, _ := rv["isValidFile"].(bool)
  216. //buyerPerson := MC.InterfaceToStr(rv["buyerperson"])
  217. //agency := MC.InterfaceToStr(rv["agency"])
  218. //agencyTel := MC.InterfaceToStr(rv["agencytel"])
  219. //agencyPerson := MC.InterfaceToStr(rv["agencyperson"])
  220. //中标信息
  221. var winnerInfo []*bxcore.WinnerInfo
  222. winnerList := MC.ObjToString(rv["s_winner"]) //中标企业名称集合
  223. if winnerList != "" && len(strings.Split(winnerList, ",")) > 0 {
  224. for wk, wv := range strings.Split(winnerList, ",") {
  225. var (
  226. winnerId = ""
  227. )
  228. if rv["entidlist"] != nil {
  229. if entIdList := MC.ObjArrToStringArr(rv["entidlist"].([]interface{})); len(entIdList) > wk { //中标企业id集合
  230. winnerId = entIdList[wk]
  231. }
  232. }
  233. if IC.C.SearchWinner.Switch && winnerId == "" {
  234. continue
  235. }
  236. if entity.RegWinner.MatchString(wv) {
  237. continue
  238. }
  239. winnerInfo = append(winnerInfo, &bxcore.WinnerInfo{
  240. Winner: wv, //中标企业 需要单独处理
  241. WinnerTel: MC.ObjToString(rv["winnertel"]), //中标企业联系电话
  242. WinnerPerson: MC.ObjToString(rv["winnerperson"]), //中标企业联系人
  243. WinnerId: MC.If(winnerId != "" && len([]rune(winnerId)) > 12, encrypt.EncodeArticleId2ByCheck(winnerId), "").(string), //中标企业加密id 存在winnerId 异常的情况
  244. })
  245. }
  246. }
  247. list = append(list, &bxcore.PurchaseList{
  248. Id: encrypt.EncodeArticleId2ByCheck(id),
  249. Area: MC.InterfaceToStr(rv["area"]),
  250. City: MC.InterfaceToStr(rv["city"]),
  251. District: MC.InterfaceToStr(rv["district"]),
  252. RegionUrl: regionUrl,
  253. BuyerClass: MC.InterfaceToStr(rv["buyerclass"]),
  254. PublishTime: MC.Int64All(rv["publishtime"]),
  255. FileExists: isValidFile,
  256. Title: title,
  257. Price: price,
  258. Buyer: buyer,
  259. BuyerTel: buyerTel,
  260. SignEndTime: MC.Int64All(rv["signendtime"]), //报名截止时间
  261. DeliveryLoc: deliveryLoc,
  262. Industry: util.IndustryFormat(p.Industry, strings.Trim(MC.ObjToString(rv["s_subscopeclass"]), ",")),
  263. PublicType: MC.InterfaceToStr(rv["public_type"]),
  264. IsNew: MC.Int64All(rv["is_yg_new"]), //is_yg_new==1 新的网站来源
  265. OriginalTitle: originalTitle,
  266. //BuyerPerson: buyerPerson,
  267. //Agency: agency,
  268. //AgencyTel: agencyTel,
  269. //AgencyPerson: agencyPerson,
  270. //WinnerInfo: winnerInfo,
  271. //BidEndTime: MC.Int64All(rv["bidendtime"]),
  272. //BidOpenTime: MC.Int64All(rv["bidopentime"]), //开标时间,
  273. })
  274. }
  275. return
  276. }
  277. func (p *Purchase) PurchaseQuery() (query string) {
  278. var (
  279. wordsMusts, wordsShould, must, mustNot []string
  280. selectTypeArr = strings.Split(p.SelectType, ",")
  281. selectType = fmt.Sprintf(`"%s"`, strings.Join(selectTypeArr, "\",\""))
  282. )
  283. //发布时间
  284. if len(strings.Split(p.PublishTime, "-")) > 1 {
  285. var (
  286. timeQuery string
  287. startTime, endTime = strings.Split(p.PublishTime, "-")[0], strings.Split(p.PublishTime, "-")[1]
  288. )
  289. if startTime != "" || endTime != "" {
  290. timeQuery += `{"range":{"publishtime":{`
  291. if startTime != "" {
  292. timeQuery += `"gte":` + startTime
  293. }
  294. if startTime != "" && endTime != "" {
  295. timeQuery += `,`
  296. }
  297. if endTime != "" {
  298. timeQuery += `"lt":` + endTime
  299. }
  300. timeQuery += `}}}`
  301. }
  302. if timeQuery != "" {
  303. must = append(must, timeQuery)
  304. }
  305. }
  306. // 关键词
  307. if p.KeyWords != "" {
  308. var (
  309. keyWordsMusts []string
  310. )
  311. for _, v := range strings.Split(p.KeyWords, IC.C.JYKeyMark) {
  312. if elastic.ReplaceYH(v) == "" {
  313. continue
  314. }
  315. keyWordsMusts = append(keyWordsMusts, fmt.Sprintf(fmt.Sprintf(es.MultiMatch, "%s", selectType), elastic.ReplaceYH(v)))
  316. }
  317. //搜索关键词模式;默认0:包含所有,1:包含任意
  318. if p.WordsMode == 1 {
  319. wordsShould = append(wordsShould, fmt.Sprintf(elastic.NgramMust, strings.Join(keyWordsMusts, ",")))
  320. } else {
  321. wordsMusts = append(wordsMusts, keyWordsMusts...)
  322. }
  323. }
  324. //附加词
  325. if p.AdditionalWords != "" {
  326. for _, aws := range strings.Split(p.AdditionalWords, ",") {
  327. //多组附加词,每组间,号隔开。每组内如果关键词中间有空格,自动分词
  328. var (
  329. addWordsMusts []string
  330. )
  331. for _, v := range strings.Split(aws, IC.C.JYKeyMark) {
  332. if elastic.ReplaceYH(v) == "" {
  333. continue
  334. }
  335. addWordsStr := fmt.Sprintf(fmt.Sprintf(es.MultiMatch, "%s", selectType), elastic.ReplaceYH(v))
  336. if p.WordsMode == 0 {
  337. wordsMusts = append(wordsMusts, addWordsStr)
  338. } else {
  339. addWordsMusts = append(addWordsMusts, addWordsStr)
  340. }
  341. }
  342. //搜索关键词模式;默认0:包含所有,1:包含任意
  343. if len(addWordsMusts) > 0 {
  344. wordsShould = append(wordsShould, fmt.Sprintf(elastic.NgramMust, strings.Join(addWordsMusts, ",")))
  345. }
  346. }
  347. }
  348. //搜索关键词模式;默认0:包含所有,1:包含任意
  349. //包含任意一组
  350. if len(wordsShould) > 0 {
  351. must = append(must, fmt.Sprintf(es.QueryBoolShould, strings.Join(wordsShould, ",")))
  352. } else if len(wordsMusts) > 0 {
  353. must = append(must, fmt.Sprintf(elastic.NgramMust, strings.Join(wordsMusts, ",")))
  354. }
  355. //行业
  356. if p.Industry != "" {
  357. must = append(must, fmt.Sprintf(es.QueryBoolMustA, "s_subscopeclass", `"`+strings.ReplaceAll(p.Industry, ",", `","`)+`"`))
  358. }
  359. //附件
  360. if p.FileExists != 0 {
  361. switch p.FileExists {
  362. case 1: //有附件
  363. must = append(must, fmt.Sprintf(es.QueryBoolMustTermBool, "isValidFile", true))
  364. case -1: //无附件
  365. mustNot = append(mustNot, fmt.Sprintf(es.QueryBoolMustTermBool, "isValidFile", true))
  366. }
  367. }
  368. //项目地区
  369. var (
  370. areaQuery []string
  371. areaTerms = `{"terms":{"%s":["%s"]}}`
  372. )
  373. if p.ProjectArea != "" {
  374. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "area", strings.ReplaceAll(p.ProjectArea, ",", "\",\"")))
  375. }
  376. if p.ProjectCity != "" {
  377. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "city", strings.ReplaceAll(p.ProjectCity, ",", "\",\"")))
  378. }
  379. if p.ProjectDistrict != "" {
  380. for _, v := range strings.Split(p.ProjectDistrict, ",") {
  381. if len(strings.Split(v, "_")) > 1 {
  382. cityName := strings.Split(v, "_")[0]
  383. districtName := strings.Split(v, "_")[1]
  384. queryBoolMustAndDistrict := `{"bool":{"must":[{"terms":{"city":["%s"]}},{"terms":{"district":["%s"]}}]}}`
  385. areaQuery = append(areaQuery, fmt.Sprintf(queryBoolMustAndDistrict, cityName, districtName))
  386. }
  387. }
  388. }
  389. if len(areaQuery) > 0 {
  390. must = append(must, fmt.Sprintf(es.QueryBoolShould, strings.Join(areaQuery, ",")))
  391. }
  392. //交付地点
  393. areaQuery = []string{}
  394. if p.DeliveryArea != "" {
  395. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "deliver_area", strings.ReplaceAll(p.DeliveryArea, ",", "\",\"")))
  396. }
  397. if p.DeliveryCity != "" {
  398. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "deliver_city", strings.ReplaceAll(p.DeliveryCity, ",", "\",\"")))
  399. }
  400. if p.DeliveryDistrict != "" {
  401. for _, v := range strings.Split(p.DeliveryDistrict, ",") {
  402. if len(strings.Split(v, "_")) > 1 {
  403. cityName := strings.Split(v, "_")[0]
  404. districtName := strings.Split(v, "_")[1]
  405. queryBoolMustAndDistrict := `{"bool":{"must":[{"terms":{"deliver_city":["%s"]}},{"terms":{"deliver_district":["%s"]}}]}}`
  406. areaQuery = append(areaQuery, fmt.Sprintf(queryBoolMustAndDistrict, cityName, districtName))
  407. }
  408. }
  409. }
  410. if len(areaQuery) > 0 {
  411. must = append(must, fmt.Sprintf(es.QueryBoolShould, strings.Join(areaQuery, ",")))
  412. }
  413. //发布方式
  414. if p.Publisher > 0 {
  415. must = append(must, fmt.Sprintf(es.QueryBoolMustTerm, "public_type", es.PurchasePublicType[p.Publisher-1]))
  416. }
  417. //截止时间
  418. if p.DeadlineStart > 0 || p.DeadlineEnd > 0 {
  419. var timeQuery string
  420. timeQuery += `{"range":{"signendtime":{`
  421. if p.DeadlineStart > 0 {
  422. timeQuery += fmt.Sprintf(`"gte":%d`, p.DeadlineStart)
  423. }
  424. if p.DeadlineStart > 0 && p.DeadlineEnd > 0 {
  425. timeQuery += `,`
  426. }
  427. if p.DeadlineEnd > 0 {
  428. timeQuery += fmt.Sprintf(`"lt":%d`, p.DeadlineEnd)
  429. }
  430. timeQuery += `}}}`
  431. must = append(must, timeQuery)
  432. }
  433. //领域
  434. areaQuery = []string{}
  435. if p.DomainFirstType != "" {
  436. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "domain_firsttype", strings.ReplaceAll(p.DomainFirstType, ",", "\",\"")))
  437. }
  438. if p.DomainSecondType != "" {
  439. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "domain_secondtype", strings.ReplaceAll(p.DomainSecondType, ",", "\",\"")))
  440. }
  441. if p.DomainThirdType != "" {
  442. areaQuery = append(areaQuery, fmt.Sprintf(areaTerms, "domain_thirdtype", strings.ReplaceAll(p.DomainThirdType, ",", "\",\"")))
  443. }
  444. if len(areaQuery) > 0 {
  445. must = append(must, fmt.Sprintf(es.QueryBoolShould, strings.Join(areaQuery, ",")))
  446. }
  447. //直采 采购信息 搜索
  448. query = fmt.Sprintf(es.Query, strings.Join(must, ","), strings.Join(mustNot, ","))
  449. log.Println("zc-query:", query)
  450. return
  451. }
  452. func (p *Purchase) FindDataFromES() (int64, []map[string]interface{}, error) {
  453. var (
  454. start = int((p.PageNum - 1) * p.PageSize)
  455. total int64
  456. list *[]map[string]interface{}
  457. err error
  458. fields = es.PurchaseBaseFieldForPayer
  459. )
  460. if IC.C.PurchaseDiffSwitch {
  461. if !p.IsPay {
  462. fields = es.PurchaseBaseField
  463. }
  464. }
  465. biddingSearch := es.SearchByES{
  466. Index: es.PurchaseIndex,
  467. IType: es.PurchaseType,
  468. Query: p.PurchaseQuery(),
  469. FindFields: p.SelectType,
  470. Order: es.PurchaseSearchSort,
  471. Fields: fields,
  472. Start: start,
  473. Limit: int(p.PageSize),
  474. Count: 0, //高亮正文数量
  475. HighLight: false, //是否高亮正文
  476. }
  477. total, list = biddingSearch.GetAllByNgramWithCount(es.LoginTypePay)
  478. if total == 0 || list == nil {
  479. log.Println(fmt.Errorf("暂无数据"))
  480. return 0, nil, nil
  481. }
  482. return total, *list, err
  483. }
  484. var (
  485. redisCode = "newother"
  486. purchaseDataCacheKey = "purchase_cache_data"
  487. purchaseCountCacheKey = "purchase_cache_count"
  488. purchaseCacheExpire = 8 * 60 * 60
  489. )
  490. func (p *Purchase) GetPurchaseCount() (count int64) {
  491. count, _, _ = p.FindDataFromES()
  492. return
  493. }
  494. // 数据
  495. func (p *Purchase) GetPurchaseData() (list []*bxcore.PurchaseList, err error) {
  496. var (
  497. res []map[string]interface{}
  498. total int64
  499. )
  500. if p.IsEmptySearch() {
  501. //查缓存
  502. cacheBytes, err := redis.GetBytes(redisCode, purchaseDataCacheKey)
  503. start := int((p.PageNum - 1) * p.PageSize)
  504. end := int(p.PageNum * p.PageSize)
  505. if err == nil && len(*cacheBytes) > start {
  506. if end > len(*cacheBytes) {
  507. end = len(*cacheBytes)
  508. }
  509. total = int64(redis.GetInt(redisCode, purchaseCountCacheKey))
  510. err = json.Unmarshal(*cacheBytes, &res)
  511. }
  512. if len(res) == 0 {
  513. p.PageNum = 1
  514. pageSize := p.PageSize
  515. start = int((p.PageNum - 1) * p.PageSize)
  516. p.PageSize = int64(util.SearchPageSize * util.SearchMaxPageNum)
  517. total, res, err = p.FindDataFromES()
  518. if total > 0 && len(res) > 0 {
  519. var b []byte
  520. b, err = json.Marshal(res)
  521. if err == nil && len(b) > 0 {
  522. err = redis.PutBytes(redisCode, purchaseDataCacheKey, &b, purchaseCacheExpire)
  523. redis.Put(redisCode, purchaseCountCacheKey, total, purchaseCacheExpire)
  524. }
  525. if end > len(res) {
  526. end = len(res)
  527. }
  528. }
  529. p.PageSize = pageSize
  530. }
  531. res = res[start:end]
  532. } else {
  533. //实时查询
  534. total, res, err = p.FindDataFromES()
  535. }
  536. if len(res) > 0 {
  537. p.Total = total
  538. p.Count = int64(util.SearchPageSize * util.SearchMaxPageNum)
  539. if p.Count > total {
  540. p.Count = total
  541. }
  542. list = p.PurchaseListFormat(res)
  543. }
  544. return
  545. }
  546. // 关键词 附加词 行业
  547. func (p *Purchase) IsEmptySearch() bool {
  548. if p.KeyWords != "" || p.AdditionalWords != "" || p.Industry != "" {
  549. return false
  550. }
  551. return true
  552. }
  553. var (
  554. purchaseSelectTypeMap = map[string]bool{
  555. "title": true,
  556. "purchasing": true,
  557. }
  558. tipMsg = "“%s“及其后面的字词均被忽略,因为剑鱼标讯的查询限制在%d个汉字以内。"
  559. )
  560. // 筛选条件格式化
  561. func (p *Purchase) FilterCriteriaFormat() {
  562. if p.UserId != "" {
  563. //判断用户身份
  564. userInfo := IC.Middleground.PowerCheckCenter.Check(p.AppId, p.MgoUserId, p.BaseUserId, p.AccountId, p.EntId, p.PositionType, p.PositionId)
  565. if userInfo != nil {
  566. p.IsPay = !userInfo.Free.IsFree
  567. }
  568. res := IC.Middleground.ResourceCenter.Haspowers(p.AccountId, p.EntAccountId, p.EntId, p.EntUserId)
  569. if res != nil {
  570. p.IsPower = strings.Contains(strings.Join(res.Powers, ","), IC.C.PurchaseCode)
  571. }
  572. }
  573. //搜索范围
  574. if p.SelectType != "" {
  575. var selectTypes []string
  576. for _, sv := range strings.Split(p.SelectType, ",") {
  577. if purchaseSelectTypeMap[sv] {
  578. selectTypes = append(selectTypes, sv)
  579. }
  580. }
  581. if len(selectTypes) > 0 {
  582. p.SelectType = strings.Join(selectTypes, ",")
  583. }
  584. }
  585. if p.SelectType == "" {
  586. p.SelectType = "title"
  587. }
  588. // p.SearchMode 搜索模式:0:精准搜索;1:模糊搜索
  589. // 精准搜索:不分词,完全匹配;(中间带空格的关键词组自动分词)
  590. // 模糊搜索:对用户输入的单个关键词进行分词处理,但必须都存在;
  591. if p.SearchMode < 0 || p.SearchMode > 1 {
  592. p.SearchMode = 0
  593. }
  594. // p.WordsMode 搜索关键词模式;默认0:包含所有,1:包含任意
  595. if p.WordsMode < 0 || p.WordsMode > 1 {
  596. p.WordsMode = 0
  597. }
  598. //发布时间--默认最近一年
  599. if p.PublishTime == "" {
  600. p.PublishTime = fmt.Sprintf("%d-%d", time.Now().AddDate(-1, 0, 0).Unix(), time.Now().Unix())
  601. }
  602. //默认每页数据量
  603. if p.PageSize <= 0 || p.PageSize > 100 {
  604. p.PageSize = 50
  605. }
  606. //第一页
  607. if p.PageNum <= 0 || p.PageNum > int64(IC.C.DefaultBidInfo.Count)/p.PageSize {
  608. p.PageNum = 1
  609. }
  610. //行业
  611. if p.Industry != "" {
  612. p.Industry = strings.TrimSpace(p.Industry)
  613. //P510 行业:其它
  614. if qt := jy.IndustryHandle(p.Industry); len(qt) > 0 {
  615. p.Industry = fmt.Sprintf("%s,%s", p.Industry, strings.Join(qt, ","))
  616. }
  617. }
  618. var (
  619. searchWords []string
  620. )
  621. //关键词
  622. if p.KeyWords != "" {
  623. p.KeyWords = strings.TrimSpace(p.KeyWords)
  624. p.InterceptKeyWords, p.TipMsg, p.KeyWords = util.InterceptSearchKW(p.KeyWords, MC.IntAllDef(IC.C.KeywordsLimit, 35), true)
  625. //if p.TipMsg != "" {
  626. // p.TipMsg = fmt.Sprintf(tipMsg, p.TipMsg, MC.IntAllDef(IC.C.KeywordsLimit, 35))
  627. //}
  628. // in.SearchMode 搜索模式:0:精准搜索;1:模糊搜索
  629. // 精准搜索:不分词,完全匹配;(中间带空格的关键词组自动分词)
  630. // 模糊搜索:对用户输入的单个关键词进行分词处理,但必须都存在;
  631. //主关键词词组
  632. if p.SearchMode == 1 {
  633. if ikWords := util.HttpEs(p.KeyWords, "ik_smart", IC.DB.Es.Addr); ikWords != "" {
  634. p.KeyWords = jy.KeywordsProcessing(ikWords, IC.C.JYKeyMark)
  635. }
  636. }
  637. searchWords = append(searchWords, p.KeyWords)
  638. }
  639. //附加词 每组附加词不能超过15个字符
  640. if p.AdditionalWords != "" {
  641. var additionalWords []string
  642. for _, ak := range strings.Split(p.AdditionalWords, ",") {
  643. if len([]rune(ak)) > 15 {
  644. additionalWords = append(additionalWords, string([]rune(ak)[:15]))
  645. } else {
  646. additionalWords = append(additionalWords, ak)
  647. }
  648. }
  649. p.AdditionalWords = strings.Join(additionalWords, ",") //分组不变
  650. //多组附加词,每组间,号隔开。每组内如果关键词中间有空格,自动分词
  651. if p.SearchMode == 1 {
  652. var (
  653. addWords []string
  654. )
  655. for _, awv := range strings.Split(p.AdditionalWords, ",") {
  656. if strings.TrimSpace(awv) != "" {
  657. if ikWords := util.HttpEs(awv, "ik_smart", IC.DB.Es.Addr); ikWords != "" {
  658. addWords = append(addWords, jy.KeywordsProcessing(ikWords, IC.C.JYKeyMark))
  659. }
  660. }
  661. }
  662. if len(addWords) > 0 {
  663. p.AdditionalWords = strings.Join(addWords, ",")
  664. }
  665. }
  666. searchWords = append(searchWords, strings.Split(p.AdditionalWords, ",")...)
  667. }
  668. p.HighlightWords = strings.Join(searchWords, " ")
  669. //报名截止
  670. if p.DeadlineStatus < 0 || p.DeadlineStatus > 2 {
  671. p.DeadlineStatus = 0
  672. }
  673. if len(strings.Split(p.DeadlineTime, "-")) > 1 {
  674. p.DeadlineStart, _ = strconv.ParseInt(strings.Split(p.DeadlineTime, "-")[0], 10, 64)
  675. p.DeadlineEnd, _ = strconv.ParseInt(strings.Split(p.DeadlineTime, "-")[1], 10, 64)
  676. if p.DeadlineEnd < p.DeadlineStart {
  677. var deadline = p.DeadlineStart
  678. p.DeadlineStart = p.DeadlineEnd
  679. p.DeadlineEnd = deadline
  680. }
  681. }
  682. switch p.DeadlineStatus {
  683. case 1: //未截止
  684. if p.DeadlineEnd < time.Now().Unix() {
  685. p.DeadlineStart = time.Now().Unix()
  686. p.DeadlineEnd = 0
  687. }
  688. case 2: //已截止
  689. if p.DeadlineEnd == 0 || p.DeadlineEnd > time.Now().Unix() {
  690. p.DeadlineStart = 0
  691. p.DeadlineEnd = time.Now().Unix()
  692. }
  693. }
  694. //发布平台
  695. if p.Publisher < 0 || p.Publisher > int64(len(es.PurchasePublicType)) {
  696. p.Publisher = 0
  697. }
  698. //空搜索 其它筛选条件 无效
  699. if p.IsEmptySearch() {
  700. //
  701. p.DomainFirstType = ""
  702. p.DomainSecondType = ""
  703. p.DomainThirdType = ""
  704. p.DeadlineStatus = 0
  705. p.DeadlineStart = 0
  706. p.DeadlineEnd = 0
  707. p.DeliveryArea = ""
  708. p.DeliveryCity = ""
  709. p.DeliveryDistrict = ""
  710. p.ProjectArea = ""
  711. p.ProjectCity = ""
  712. p.ProjectDistrict = ""
  713. p.FileExists = 0
  714. p.Publisher = 0
  715. }
  716. }