CoopHistoryService.go 16 KB

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