CoopHistoryService.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. func GetPrList(req *types.CoopHistoryReq) (result []*ResultData, size_1, size_2, size_3, size_4 int64) {
  65. pTmp := ProjectTmp{}
  66. err := T.ClickhouseConn.QueryRow(context.TODO(), sql_2_0, req.Pid).ScanStruct(&pTmp)
  67. if err != nil {
  68. return nil, 0, 0, 0, 0
  69. }
  70. propertyForm := T.NetworkCom.GetMyProbusfor(req.EntAccountId)
  71. // firstparty:甲方 supplier:供应商 adiffb:同甲异业 middleman:中间人 agency:招标代理机构 sup_sub: 上下级
  72. // 1、同甲异业数据/ 3、招标代理机构渠道
  73. if pTmp.BuyerId != "" {
  74. // 中间人可介绍业主
  75. var r3 []map[string]interface{}
  76. r3 = FindMiddleman([]string{fmt.Sprintf("'%s'", pTmp.BuyerId)}, req.PositionId, r3)
  77. if r3 != nil && len(r3) > 0 {
  78. size_4 = int64(len(r3))
  79. if req.ChannelType == "0" || req.ChannelType == "4" {
  80. for _, m := range r3 {
  81. tmp := ResultData{
  82. SourceType: "middleman",
  83. EntName: common.ObjToString(m["b_name"]),
  84. EntId: common.ObjToString(m["b_id"]),
  85. EntPerson: common.ObjToString(m["personName"]),
  86. Relationship: "业主的关系人",
  87. BuyerId: pTmp.BuyerId,
  88. }
  89. result = append(result, &tmp)
  90. }
  91. }
  92. }
  93. // 关联单位
  94. var r4 []map[string]interface{}
  95. r4 = Findfirstparty([]string{fmt.Sprintf("'%s'", pTmp.BuyerId)}, r4)
  96. if r4 != nil && len(r4) > 0 {
  97. size_2 = int64(len(r4))
  98. if req.ChannelType == "0" || req.ChannelType == "2" {
  99. for _, m := range r4 {
  100. tmp := ResultData{
  101. SourceType: "sup_sub",
  102. EntName: common.ObjToString(m["b_name"]),
  103. EntId: common.ObjToString(m["b_id"]),
  104. EntPerson: common.ObjToString(m["personName"]),
  105. Relationship: common.ObjToString(m["relationship"]),
  106. BuyerId: pTmp.BuyerId,
  107. }
  108. result = append(result, &tmp)
  109. }
  110. }
  111. }
  112. rs1, rs2 := GetData(propertyForm, pTmp.BuyerId)
  113. r1 := rs1[pTmp.BuyerId]
  114. r2 := rs2[pTmp.BuyerId]
  115. if r1 != nil && len(r1) > 0 {
  116. size_1 = int64(len(r1))
  117. if req.ChannelType == "0" || req.ChannelType == "1" {
  118. for _, m := range r1 {
  119. near, zbtime := LastTimeCoop(pTmp.BuyerId, common.ObjToString(m["name"]), "adiffb")
  120. tmp := ResultData{
  121. SourceType: "adiffb",
  122. EntName: common.ObjToString(m["name"]),
  123. ProjectNum: common.IntAll(m["coop_size"]),
  124. TotalAmount: common.Float64All(m["coop_amount"]),
  125. RecentTime: zbtime,
  126. NearlyYears: near,
  127. BuyerId: pTmp.BuyerId,
  128. }
  129. result = append(result, &tmp)
  130. }
  131. }
  132. }
  133. if r2 != nil && len(r2) > 0 {
  134. size_3 = int64(len(r2))
  135. if req.ChannelType == "0" || req.ChannelType == "3" {
  136. for _, m := range r2 {
  137. near, zbtime := LastTimeCoop(pTmp.BuyerId, common.ObjToString(m["name"]), "agency")
  138. tmp := ResultData{
  139. SourceType: "agency",
  140. EntName: common.ObjToString(m["name"]),
  141. ProjectNum: common.IntAll(m["coop_size"]),
  142. TotalAmount: common.Float64All(m["coop_amount"]),
  143. RecentTime: zbtime,
  144. NearlyYears: near,
  145. BuyerId: pTmp.BuyerId,
  146. }
  147. result = append(result, &tmp)
  148. }
  149. }
  150. }
  151. }
  152. return
  153. }
  154. func GetData(propertyForm []string, bid string) (result1, result2 map[string][]map[string]interface{}) {
  155. result1, result2 = map[string][]map[string]interface{}{}, map[string][]map[string]interface{}{}
  156. type AggStruct struct {
  157. Buckets []struct {
  158. Key string `json:"key,omitempty"`
  159. Doc_count int64 `json:"doc_count,omitempty"`
  160. Amount_all struct {
  161. Value float64 `json:"value,omitempty"`
  162. } `json:"amount_all"`
  163. EntId struct {
  164. Buckets []struct {
  165. Key string `json:"key,omitempty"`
  166. Doc_count int64 `json:"doc_count,omitempty"`
  167. } `json:"buckets"`
  168. } `json:"ent_id"`
  169. BuyerId struct {
  170. Buckets []struct {
  171. Key string `json:"key,omitempty"`
  172. Doc_count int64 `json:"doc_count,omitempty"`
  173. } `json:"buckets"`
  174. } `json:"buyer_id"`
  175. } `json:"buckets"`
  176. }
  177. m1 := make(map[string]interface{}) //采购单位-中标单位
  178. m2 := make(map[string]interface{}) //采购单位-代理机构
  179. noIds := []string{}
  180. if len(propertyForm) > 0 {
  181. //同甲异态 中标企业
  182. aggs, _, _ := elastic.GetAggs(INDEX_1, INDEX_1, fmt.Sprintf(es_query, strings.ReplaceAll(bid, ",", `","`), strings.Join(propertyForm, "\",\"")))
  183. logx.Info("es聚合查询结果:", fmt.Sprintf(es_query, strings.ReplaceAll(bid, ",", `","`), strings.Join(propertyForm, "\",\"")))
  184. var m1Buckets = AggStruct{}
  185. if aggs != nil && aggs["winner_count"] != nil {
  186. bs, err := aggs["winner_count"].MarshalJSON()
  187. if err != nil {
  188. logx.Info(err)
  189. } else {
  190. if len(bs) == 0 {
  191. logx.Info(err)
  192. } else {
  193. err := json.Unmarshal(bs, &m1Buckets)
  194. logx.Info(err)
  195. if len(m1Buckets.Buckets) > 0 {
  196. for _, v := range m1Buckets.Buckets {
  197. if v.Key != "" && len(v.EntId.Buckets) > 0 && len(v.BuyerId.Buckets) > 0 {
  198. mv := map[string]interface{}{"name": v.Key, "amount": v.Amount_all.Value, "count": v.Doc_count, "buyerId": v.BuyerId.Buckets[0].Key}
  199. if len(v.EntId.Buckets) == 1 && v.EntId.Buckets[0].Key != "" {
  200. mv["nameId"] = v.EntId.Buckets[0].Key
  201. } else {
  202. noIds = append(noIds, v.Key)
  203. }
  204. m1[v.Key] = mv
  205. }
  206. }
  207. }
  208. }
  209. }
  210. }
  211. }
  212. //代理机构
  213. aggs1, _, _ := elastic.GetAggs(INDEX_1, INDEX_1, fmt.Sprintf(es_query1, strings.ReplaceAll(bid, ",", `","`)))
  214. var m2Buckets = AggStruct{}
  215. if aggs1 != nil && aggs1["agency_count"] != nil {
  216. bs, err := aggs1["agency_count"].MarshalJSON()
  217. if err != nil {
  218. logx.Info(err)
  219. } else {
  220. if len(bs) == 0 {
  221. logx.Info(err)
  222. } else {
  223. err = json.Unmarshal(bs, &m2Buckets)
  224. logx.Info(err)
  225. if len(m2Buckets.Buckets) > 0 {
  226. for _, v := range m2Buckets.Buckets {
  227. if v.Key != "" && len(v.EntId.Buckets) > 0 && len(v.BuyerId.Buckets) > 0 {
  228. if v.EntId.Buckets[0].Key == "" {
  229. noIds = append(noIds, v.Key)
  230. }
  231. 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}
  232. }
  233. }
  234. }
  235. }
  236. }
  237. }
  238. idName := T.NetworkCom.GetEntIdByName(noIds)
  239. for k, v := range m1 {
  240. v1 := v.(map[string]interface{})
  241. tmp := make(map[string]interface{})
  242. tmp["name"] = k
  243. nameId, _ := v1["nameId"].(string)
  244. if nameId == "" {
  245. nameId = idName[k]
  246. }
  247. tmp["nameId"] = nameId
  248. tmp["coop_size"] = v1["count"]
  249. tmp["coop_amount"] = v1["amount"]
  250. buyerId, _ := v1["buyerId"].(string)
  251. result1[buyerId] = append(result1[buyerId], tmp)
  252. }
  253. for k, v := range m2 {
  254. v1 := v.(map[string]interface{})
  255. tmp := make(map[string]interface{})
  256. tmp["name"] = k
  257. nameId, _ := v1["nameId"].(string)
  258. if nameId == "" {
  259. nameId = idName[k]
  260. }
  261. tmp["nameId"] = nameId
  262. tmp["coop_size"] = v1["count"]
  263. tmp["coop_amount"] = v1["amount"]
  264. buyerId, _ := v1["buyerId"].(string)
  265. result2[buyerId] = append(result2[buyerId], tmp)
  266. }
  267. return
  268. }
  269. type P_History struct {
  270. ProjectId string `ch:"project_id"`
  271. ProjectName string `ch:"project_name"`
  272. ZbTime int64 `ch:"zbtime"`
  273. Href string `ch:"href"`
  274. }
  275. // @Author jianghan
  276. // @Description 合作历史
  277. // @Date 2024/4/20
  278. func GetData3(source string, buyerId, winnerId string) (result []*P_History) {
  279. var rows driver.Rows
  280. if source == "1" {
  281. rows, _ = T.ClickhouseConn.Query(context.TODO(), sql_2_1_1, buyerId, winnerId)
  282. } else if source == "2" {
  283. rows, _ = T.ClickhouseConn.Query(context.TODO(), sql_2_1, buyerId, winnerId)
  284. }
  285. for rows.Next() {
  286. pHis := P_History{}
  287. _ = rows.ScanStruct(&pHis)
  288. pHis.Href = fmt.Sprintf("/article/content/%s.html", encrypt.CommonEncodeArticle("content", pHis.ProjectId))
  289. result = append(result, &pHis)
  290. }
  291. return
  292. }
  293. // @Author jianghan
  294. // @Description 上次合作时间
  295. // @Date 2024/4/24
  296. func LastTimeCoop(buyerId, ent, stype string) (bool, int64) {
  297. zbtime := int64(0)
  298. near := false
  299. if stype == "adiffb" {
  300. sql := `SELECT zbtime FROM information.transaction_info WHERE buyer_id = ? AND has(winner, ?) ORDER BY zbtime DESC LIMIT 1`
  301. _ = T.ClickhouseConn.QueryRow(context.TODO(), sql, buyerId, ent).Scan(&zbtime)
  302. } else if stype == "agency" {
  303. sql := `SELECT zbtime FROM information.transaction_info WHERE buyer_id = ? AND agency = ? ORDER BY zbtime DESC LIMIT 1`
  304. _ = T.ClickhouseConn.QueryRow(context.TODO(), sql, buyerId, ent).Scan(&zbtime)
  305. }
  306. timestamp := time.Now().AddDate(-3, 0, 0).Unix()
  307. if timestamp <= zbtime {
  308. near = true
  309. }
  310. return near, zbtime
  311. }