CoopHistoryService.go 15 KB

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