CoopHistoryService.go 15 KB

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