CoopHistoryService.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "app.yhyue.com/moapp/jybase/common"
  9. "app.yhyue.com/moapp/jybase/encrypt"
  10. elastic "app.yhyue.com/moapp/jybase/es"
  11. "app.yhyue.com/moapp/jybase/redis"
  12. T "bp.jydev.jianyu360.cn/CRM/networkManage/api/common"
  13. "bp.jydev.jianyu360.cn/CRM/networkManage/api/internal/types"
  14. "github.com/ClickHouse/clickhouse-go/v2/lib/driver"
  15. "github.com/zeromicro/go-zero/core/logx"
  16. )
  17. var (
  18. INDEX_1 = "transaction_info_all"
  19. sql_2_0 = `SELECT buyer_id FROM information.transaction_info_all WHERE project_id = ?`
  20. sql_2_2 = `select id as buyer_id from ent_info where company_name=? order by id desc limit 1`
  21. sql_2_1 = `SELECT project_id, project_name, zbtime FROM information.transaction_info_all WHERE buyer_id = ? AND has(winner, ?) ORDER BY zbtime DESC`
  22. sql_2_1_1 = `SELECT project_id, project_name, zbtime FROM information.transaction_info_all WHERE buyer_id = ? AND agency = ? ORDER BY zbtime DESC`
  23. //sql_2_2 = `select DISTINCT b.company_id,b.company_name,a.relate_id,a.relate_name,b.contact_person from connection_introduce a INNER JOIN connection b on a.position_id= ? and a.connection_id=b.id and a.relate_Id = ? and a.itype =1 and b.itype=4 and b.status=1 `
  24. //sql_2_3 = `select a.a_id as a_id, a.b_id as b_id, a.a_name as a_name, a.b_name as b_name, a.code as code, c.legal_person as c_person, d.legal_person d_person from crm.ent_map_code a left join ent_info c on (a.a_id = ? or a.b_id = ? ) and a.code in('0101', '0201') and a.a_id = c.id left join ent_info d on (a.a_id = ? or a.b_id = ? ) and a.code in('0101', '0201') and a.b_id = d.id where (a.a_id = ? or a.b_id = ? ) and a.code in('0101', '0201')`
  25. es_query = `{"query": {"bool": {"must": [{"terms": {"buyer_id": ["%s"]}},{"exists": {"field": "winner_id"}}],"must_not": {"terms": {"topscopeclass": ["%s"]}}}},"aggs": {"winner_count": {"terms": {"field": "winner","size": 1000,"order": {"_count": "desc"}},"aggs": {"amount_all": {"sum": {"field": "project_money"}},"ent_id": {"terms": {"field": "winner_id"}},"buyer_id": {"terms": {"field": "buyer_id"}}}}},"size": 1}`
  26. es_query1 = `{"query": {"bool": {"must": [{"terms": {"buyer_id": ["%s"]}}],"must_not": [{"term": {"agency_id": {"value": ""}}}]}},"aggs": {"agency_count": {"terms": {"field": "agency","size": 1000,"order": {"_count": "desc"}},"aggs": {"amount_all": {"sum": {"field": "project_money"}},"ent_id": {"terms": {"field": "agency_id"}},"buyer_id": {"terms": {"field": "buyer_id"}}}}},"size": 1}`
  27. )
  28. type ResultData struct {
  29. SourceType string `json:"SourceType"`
  30. EntName string `json:"EntName"`
  31. EntId string `json:"EntId"`
  32. EntPerson string `json:"EntPerson"`
  33. Middleman string `json:"Middleman"`
  34. ProjectNum int `json:"ProjectNum"`
  35. TotalAmount float64 `json:"TotalAmount"`
  36. RecentTime int64 `json:"RecentTime"`
  37. NearlyYears bool `json:"NearlyYears"`
  38. SupEnt string `json:"SupEnt"` // 上级
  39. NextEnt string `json:"NextEnt"` // 下级
  40. Relationship string `json:"Relationship"` // 关系
  41. BuyerId string `json:"BuyerId"`
  42. IsIgnore bool `json:"isIgnore"`
  43. }
  44. type ResultDatas []*ResultData
  45. func (n *ResultDatas) Len() int {
  46. return len(*n)
  47. }
  48. func (n *ResultDatas) Less(i, j int) bool {
  49. if (*n)[i].RecentTime == (*n)[j].RecentTime {
  50. return (*n)[i].EntName < (*n)[j].EntName
  51. }
  52. return (*n)[i].RecentTime > (*n)[j].RecentTime
  53. }
  54. func (n *ResultDatas) Swap(i, j int) {
  55. (*n)[i], (*n)[j] = (*n)[j], (*n)[i]
  56. }
  57. type ProjectTmp struct {
  58. BuyerId string `ch:"buyer_id"`
  59. }
  60. type Cooperate struct {
  61. Near bool
  62. ZbTime int64
  63. }
  64. type AggStruct struct {
  65. Buckets []struct {
  66. Key string `json:"key,omitempty"`
  67. Doc_count int64 `json:"doc_count,omitempty"`
  68. Amount_all struct {
  69. Value float64 `json:"value,omitempty"`
  70. } `json:"amount_all"`
  71. EntId struct {
  72. Buckets []struct {
  73. Key string `json:"key,omitempty"`
  74. Doc_count int64 `json:"doc_count,omitempty"`
  75. } `json:"buckets"`
  76. } `json:"ent_id"`
  77. BuyerId struct {
  78. Buckets []struct {
  79. Key string `json:"key,omitempty"`
  80. Doc_count int64 `json:"doc_count,omitempty"`
  81. } `json:"buckets"`
  82. } `json:"buyer_id"`
  83. } `json:"buckets"`
  84. }
  85. func GetPrList(req *types.CoopHistoryReq) (result []*ResultData, size_1, size_2, size_3, size_4 int64) {
  86. pTmp := ProjectTmp{}
  87. var err error
  88. if req.Pid != "" {
  89. err = T.ClickhouseConn.QueryRow(context.TODO(), sql_2_0, req.Pid).ScanStruct(&pTmp)
  90. } else if req.Buyer != "" {
  91. err = T.ClickhouseConn.QueryRow(context.TODO(), sql_2_2, req.Buyer).ScanStruct(&pTmp)
  92. } else {
  93. return
  94. }
  95. if err != nil {
  96. return nil, 0, 0, 0, 0
  97. }
  98. //propertyForm := T.NetworkCom.GetMyProbusfor(req.EntAccountId)
  99. scopeClass := FindBusiness(req.EntId, req.EntUserId)
  100. // firstparty:甲方 supplier:供应商 adiffb:同甲异业 middleman:中间人 agency:招标代理机构 sup_sub: 上下级
  101. // 1、同甲异业数据/ 3、招标代理机构渠道
  102. if pTmp.BuyerId != "" {
  103. // 中间人可介绍业主
  104. var r3 []map[string]interface{}
  105. r3 = FindMiddleman([]string{fmt.Sprintf("'%s'", pTmp.BuyerId)}, req.PositionId, r3)
  106. if r3 != nil && len(r3) > 0 {
  107. size_4 = int64(len(r3))
  108. if req.ChannelType == "0" || req.ChannelType == "4" {
  109. for _, m := range r3 {
  110. tmp := ResultData{
  111. SourceType: "middleman",
  112. EntName: common.ObjToString(m["b_name"]),
  113. EntId: common.ObjToString(m["b_id"]),
  114. EntPerson: common.ObjToString(m["personName"]),
  115. Relationship: "业主的关系人",
  116. BuyerId: pTmp.BuyerId,
  117. }
  118. result = append(result, &tmp)
  119. }
  120. }
  121. }
  122. // 关联单位
  123. var r4 []map[string]interface{}
  124. r4 = Findfirstparty([]string{fmt.Sprintf("'%s'", pTmp.BuyerId)}, r4)
  125. if r4 != nil && len(r4) > 0 {
  126. size_2 = int64(len(r4))
  127. if req.ChannelType == "0" || req.ChannelType == "2" {
  128. for _, m := range r4 {
  129. tmp := ResultData{
  130. SourceType: "sup_sub",
  131. EntName: common.ObjToString(m["b_name"]),
  132. EntId: common.ObjToString(m["b_id"]),
  133. EntPerson: common.ObjToString(m["personName"]),
  134. Relationship: common.ObjToString(m["relationship"]),
  135. BuyerId: pTmp.BuyerId,
  136. }
  137. result = append(result, &tmp)
  138. }
  139. }
  140. }
  141. r1 := GetWinnerData(strings.Split(scopeClass, ","), pTmp.BuyerId)
  142. r2 := GetAgencyData(pTmp.BuyerId)
  143. winners, agency := []string{}, []string{}
  144. for _, m := range r1 {
  145. winners = append(winners, common.ObjToString(m["name"]))
  146. }
  147. for _, m := range r2 {
  148. agency = append(agency, common.ObjToString(m["name"]))
  149. }
  150. logx.Info("CandidateChannel LastTimeCoopBath start ", req.PositionId, " ", pTmp.BuyerId, " ", len(winners), " ", len(agency))
  151. ltcs1, ltcs2 := LastTimeCoopBath(req.PositionId, pTmp.BuyerId, winners, agency)
  152. logx.Info("CandidateChannel LastTimeCoopBath over ", req.PositionId)
  153. if r1 != nil && len(r1) > 0 {
  154. size_1 = int64(len(r1))
  155. if req.ChannelType == "0" || req.ChannelType == "1" {
  156. for _, m := range r1 {
  157. tmp := ResultData{
  158. SourceType: "adiffb",
  159. EntName: common.ObjToString(m["name"]),
  160. ProjectNum: common.IntAll(m["coop_size"]),
  161. TotalAmount: common.Float64All(m["coop_amount"]),
  162. BuyerId: pTmp.BuyerId,
  163. }
  164. if ltc := ltcs1[common.ObjToString(m["name"])]; ltc != nil {
  165. tmp.NearlyYears = ltc.Near
  166. tmp.RecentTime = ltc.ZbTime
  167. }
  168. result = append(result, &tmp)
  169. }
  170. }
  171. }
  172. if r2 != nil && len(r2) > 0 {
  173. size_3 = int64(len(r2))
  174. if req.ChannelType == "0" || req.ChannelType == "3" {
  175. for _, m := range r2 {
  176. tmp := ResultData{
  177. SourceType: "agency",
  178. EntName: common.ObjToString(m["name"]),
  179. ProjectNum: common.IntAll(m["coop_size"]),
  180. TotalAmount: common.Float64All(m["coop_amount"]),
  181. BuyerId: pTmp.BuyerId,
  182. }
  183. if ltc := ltcs2[common.ObjToString(m["name"])]; ltc != nil {
  184. tmp.NearlyYears = ltc.Near
  185. tmp.RecentTime = ltc.ZbTime
  186. }
  187. result = append(result, &tmp)
  188. }
  189. }
  190. }
  191. }
  192. return
  193. }
  194. func GetWinnerData(scopeClass []string, bid string) (result1 []map[string]interface{}) {
  195. result1 = []map[string]interface{}{}
  196. winnerKey := fmt.Sprintf("networkManage_coopHistory_winner_%s", common.GetMd5String(strings.Join(scopeClass, ",")+"_"+bid))
  197. wb, err := redis.GetBytes("newother", winnerKey)
  198. if err == nil {
  199. json.Unmarshal(*wb, &result1)
  200. return
  201. }
  202. m1 := make(map[string]interface{}) //采购单位-中标单位
  203. noIds := []string{}
  204. if len(scopeClass) > 0 {
  205. //同甲异态 中标企业
  206. aggs, _, _ := elastic.GetAggs(INDEX_1, INDEX_1, fmt.Sprintf(es_query, strings.ReplaceAll(bid, ",", `","`), strings.Join(scopeClass, "\",\"")))
  207. logx.Info("es聚合查询结果:", fmt.Sprintf(es_query, strings.ReplaceAll(bid, ",", `","`), strings.Join(scopeClass, "\",\"")))
  208. var m1Buckets = AggStruct{}
  209. if aggs != nil && aggs["winner_count"] != nil {
  210. bs, err := aggs["winner_count"].MarshalJSON()
  211. if err != nil {
  212. logx.Info(err)
  213. } else {
  214. if len(bs) == 0 {
  215. logx.Info(err)
  216. } else {
  217. err := json.Unmarshal(bs, &m1Buckets)
  218. logx.Info(err)
  219. if len(m1Buckets.Buckets) > 0 {
  220. for _, v := range m1Buckets.Buckets {
  221. if v.Key != "" && len(v.EntId.Buckets) > 0 && len(v.BuyerId.Buckets) > 0 {
  222. mv := map[string]interface{}{"name": v.Key, "amount": v.Amount_all.Value, "count": v.Doc_count, "buyerId": v.BuyerId.Buckets[0].Key}
  223. if len(v.EntId.Buckets) == 1 && v.EntId.Buckets[0].Key != "" {
  224. mv["nameId"] = v.EntId.Buckets[0].Key
  225. } else {
  226. noIds = append(noIds, v.Key)
  227. }
  228. m1[v.Key] = mv
  229. }
  230. }
  231. }
  232. }
  233. }
  234. }
  235. }
  236. idName := T.NetworkCom.GetEntIdByName(noIds)
  237. for k, v := range m1 {
  238. v1 := v.(map[string]interface{})
  239. tmp := make(map[string]interface{})
  240. tmp["name"] = k
  241. nameId, _ := v1["nameId"].(string)
  242. if nameId == "" {
  243. nameId = idName[k]
  244. }
  245. tmp["nameId"] = nameId
  246. tmp["coop_size"] = v1["count"]
  247. tmp["coop_amount"] = v1["amount"]
  248. result1 = append(result1, tmp)
  249. }
  250. redis.Put("newother", winnerKey, result1, T.C.CacheTimeOut)
  251. return
  252. }
  253. func GetAgencyData(bid string) (result2 []map[string]interface{}) {
  254. result2 = []map[string]interface{}{}
  255. agencyKey := fmt.Sprintf("networkManage_coopHistory_agency_%s", bid)
  256. wb, err := redis.GetBytes("newother", agencyKey)
  257. if err == nil {
  258. json.Unmarshal(*wb, &result2)
  259. return
  260. }
  261. m2 := make(map[string]interface{}) //采购单位-代理机构
  262. noIds := []string{}
  263. //代理机构
  264. aggs1, _, _ := elastic.GetAggs(INDEX_1, INDEX_1, fmt.Sprintf(es_query1, strings.ReplaceAll(bid, ",", `","`)))
  265. var m2Buckets = AggStruct{}
  266. if aggs1 != nil && aggs1["agency_count"] != nil {
  267. bs, err := aggs1["agency_count"].MarshalJSON()
  268. if err != nil {
  269. logx.Info(err)
  270. } else {
  271. if len(bs) == 0 {
  272. logx.Info(err)
  273. } else {
  274. err = json.Unmarshal(bs, &m2Buckets)
  275. logx.Info(err)
  276. if len(m2Buckets.Buckets) > 0 {
  277. for _, v := range m2Buckets.Buckets {
  278. if v.Key != "" && len(v.EntId.Buckets) > 0 && len(v.BuyerId.Buckets) > 0 {
  279. if v.EntId.Buckets[0].Key == "" {
  280. noIds = append(noIds, v.Key)
  281. }
  282. m2[v.Key] = map[string]interface{}{"name": v.Key, "amount": v.Amount_all.Value, "count": v.Doc_count, "nameId": v.EntId.Buckets[0].Key, "buyerId": v.BuyerId.Buckets[0].Key}
  283. }
  284. }
  285. }
  286. }
  287. }
  288. }
  289. idName := T.NetworkCom.GetEntIdByName(noIds)
  290. for k, v := range m2 {
  291. v1 := v.(map[string]interface{})
  292. tmp := make(map[string]interface{})
  293. tmp["name"] = k
  294. nameId, _ := v1["nameId"].(string)
  295. if nameId == "" {
  296. nameId = idName[k]
  297. }
  298. tmp["nameId"] = nameId
  299. tmp["coop_size"] = v1["count"]
  300. tmp["coop_amount"] = v1["amount"]
  301. result2 = append(result2, tmp)
  302. }
  303. redis.Put("newother", agencyKey, result2, T.C.CacheTimeOut)
  304. return
  305. }
  306. type P_History struct {
  307. ProjectId string `ch:"project_id"`
  308. ProjectName string `ch:"project_name"`
  309. ZbTime int64 `ch:"zbtime"`
  310. Href string `ch:"href"`
  311. }
  312. // @Author jianghan
  313. // @Description 合作历史
  314. // @Date 2024/4/20
  315. func GetData3(source string, buyerId, winnerId string) (result []*P_History) {
  316. var rows driver.Rows
  317. if source == "1" {
  318. rows, _ = T.ClickhouseConn.Query(context.TODO(), sql_2_1_1, buyerId, winnerId)
  319. } else if source == "2" {
  320. rows, _ = T.ClickhouseConn.Query(context.TODO(), sql_2_1, buyerId, winnerId)
  321. }
  322. for rows.Next() {
  323. pHis := P_History{}
  324. _ = rows.ScanStruct(&pHis)
  325. pHis.Href = fmt.Sprintf("/article/content/%s.html", encrypt.CommonEncodeArticle("content", pHis.ProjectId))
  326. result = append(result, &pHis)
  327. }
  328. return
  329. }
  330. // @Author jianghan
  331. // @Description 上次合作时间
  332. // @Date 2024/4/24
  333. func LastTimeCoop(buyerId, ent, stype string) (bool, int64) {
  334. zbtime := int64(0)
  335. near := false
  336. if stype == "adiffb" {
  337. sql := `SELECT zbtime FROM information.transaction_info_all WHERE buyer_id = ? AND has(winner, ?) ORDER BY zbtime DESC LIMIT 1`
  338. _ = T.ClickhouseConn.QueryRow(context.TODO(), sql, buyerId, ent).Scan(&zbtime)
  339. } else if stype == "agency" {
  340. sql := `SELECT zbtime FROM information.transaction_info_all WHERE buyer_id = ? AND agency = ? ORDER BY zbtime DESC LIMIT 1`
  341. _ = T.ClickhouseConn.QueryRow(context.TODO(), sql, buyerId, ent).Scan(&zbtime)
  342. }
  343. timestamp := time.Now().AddDate(-3, 0, 0).Unix()
  344. if timestamp <= zbtime {
  345. near = true
  346. }
  347. return near, zbtime
  348. }
  349. func LastTimeCoopBath(positionId int64, buyerId string, winners, agencys []string) (map[string]*Cooperate, map[string]*Cooperate) {
  350. adiffb, agency := map[string]*Cooperate{}, map[string]*Cooperate{}
  351. if buyerId == "" {
  352. return adiffb, agency
  353. }
  354. var toSearch = func(tp int, query string, ws []string) {
  355. logx.Info("LastTimeCoopBath once start ", positionId)
  356. defer logx.Info("LastTimeCoopBath once over ", positionId)
  357. wh, newArgs := T.NetworkCom.WhArgs(ws)
  358. query = fmt.Sprintf(query, wh)
  359. args := []interface{}{buyerId}
  360. args = append(args, newArgs...)
  361. rows, err := T.ClickhouseConn.Query(context.Background(), query, args...)
  362. if err != nil {
  363. logx.Error(err)
  364. return
  365. }
  366. for rows.Next() {
  367. var (
  368. one string
  369. zbtime int64
  370. )
  371. if err := rows.Scan(&one, &zbtime); err != nil {
  372. logx.Error(err)
  373. continue
  374. }
  375. c := &Cooperate{
  376. ZbTime: zbtime,
  377. }
  378. timestamp := time.Now().AddDate(-3, 0, 0).Unix()
  379. if timestamp <= c.ZbTime {
  380. c.Near = true
  381. }
  382. if tp == 1 {
  383. adiffb[one] = c
  384. } else {
  385. agency[one] = c
  386. }
  387. }
  388. rows.Close()
  389. if err := rows.Err(); err != nil {
  390. logx.Error(err)
  391. }
  392. }
  393. if len(winners) > 0 {
  394. key := fmt.Sprintf("networkManage_lastTimeCoop_winner_%s", common.GetMd5String(buyerId+"_"+strings.Join(winners, ",")))
  395. wb, err := redis.GetBytes("newother", key)
  396. if err == nil {
  397. json.Unmarshal(*wb, &adiffb)
  398. } else {
  399. sql := `SELECT winner_one,max(zbtime) FROM information.transaction_info_all ARRAY JOIN winner AS winner_one WHERE buyer_id=? AND hasAny(winner,[%s])) group by winner_one`
  400. wns := []string{}
  401. for _, v := range winners {
  402. wns = append(wns, v)
  403. if len(wns) == 50 {
  404. toSearch(1, sql, wns)
  405. wns = []string{}
  406. }
  407. }
  408. if len(wns) > 0 {
  409. toSearch(1, sql, wns)
  410. }
  411. redis.Put("newother", key, adiffb, T.C.CacheTimeOut)
  412. }
  413. }
  414. if len(agencys) > 0 {
  415. key := fmt.Sprintf("networkManage_lastTimeCoop_agency_%s", common.GetMd5String(buyerId+"_"+strings.Join(agencys, ",")))
  416. wb, err := redis.GetBytes("newother", key)
  417. if err == nil {
  418. json.Unmarshal(*wb, &agency)
  419. } else {
  420. sql := `SELECT agency,max(zbtime) FROM information.transaction_info_all WHERE buyer_id=? AND agency in (%s) group by agency`
  421. acs := []string{}
  422. for _, v := range agencys {
  423. acs = append(acs, v)
  424. if len(acs) == 50 {
  425. toSearch(2, sql, acs)
  426. acs = []string{}
  427. }
  428. }
  429. if len(acs) > 0 {
  430. toSearch(2, sql, acs)
  431. }
  432. redis.Put("newother", key, agency, T.C.CacheTimeOut)
  433. }
  434. }
  435. return adiffb, agency
  436. }