CoopHistoryService.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. winners, agency := []string{}, []string{}
  128. for _, m := range r1 {
  129. winners = append(winners, common.ObjToString(m["name"]))
  130. }
  131. for _, m := range r2 {
  132. agency = append(agency, common.ObjToString(m["name"]))
  133. }
  134. logx.Info("CandidateChannel LastTimeCoopBath start ", req.PositionId, " ", pTmp.BuyerId, " ", len(winners), " ", len(agency))
  135. ltcs1, ltcs2 := LastTimeCoopBath(req.PositionId, pTmp.BuyerId, winners, agency)
  136. logx.Info("CandidateChannel LastTimeCoopBath over ", req.PositionId)
  137. if r1 != nil && len(r1) > 0 {
  138. size_1 = int64(len(r1))
  139. if req.ChannelType == "0" || req.ChannelType == "1" {
  140. for _, m := range r1 {
  141. tmp := ResultData{
  142. SourceType: "adiffb",
  143. EntName: common.ObjToString(m["name"]),
  144. ProjectNum: common.IntAll(m["coop_size"]),
  145. TotalAmount: common.Float64All(m["coop_amount"]),
  146. BuyerId: pTmp.BuyerId,
  147. }
  148. if ltc := ltcs1[common.ObjToString(m["name"])]; ltc != nil {
  149. tmp.NearlyYears = ltc.Near
  150. tmp.RecentTime = ltc.ZbTime
  151. }
  152. result = append(result, &tmp)
  153. }
  154. }
  155. }
  156. if r2 != nil && len(r2) > 0 {
  157. size_3 = int64(len(r2))
  158. if req.ChannelType == "0" || req.ChannelType == "3" {
  159. for _, m := range r2 {
  160. tmp := ResultData{
  161. SourceType: "agency",
  162. EntName: common.ObjToString(m["name"]),
  163. ProjectNum: common.IntAll(m["coop_size"]),
  164. TotalAmount: common.Float64All(m["coop_amount"]),
  165. BuyerId: pTmp.BuyerId,
  166. }
  167. if ltc := ltcs2[common.ObjToString(m["name"])]; ltc != nil {
  168. tmp.NearlyYears = ltc.Near
  169. tmp.RecentTime = ltc.ZbTime
  170. }
  171. result = append(result, &tmp)
  172. }
  173. }
  174. }
  175. }
  176. return
  177. }
  178. func GetData(scopeClass []string, bid string) (result1, result2 map[string][]map[string]interface{}) {
  179. result1, result2 = map[string][]map[string]interface{}{}, map[string][]map[string]interface{}{}
  180. type AggStruct struct {
  181. Buckets []struct {
  182. Key string `json:"key,omitempty"`
  183. Doc_count int64 `json:"doc_count,omitempty"`
  184. Amount_all struct {
  185. Value float64 `json:"value,omitempty"`
  186. } `json:"amount_all"`
  187. EntId struct {
  188. Buckets []struct {
  189. Key string `json:"key,omitempty"`
  190. Doc_count int64 `json:"doc_count,omitempty"`
  191. } `json:"buckets"`
  192. } `json:"ent_id"`
  193. BuyerId struct {
  194. Buckets []struct {
  195. Key string `json:"key,omitempty"`
  196. Doc_count int64 `json:"doc_count,omitempty"`
  197. } `json:"buckets"`
  198. } `json:"buyer_id"`
  199. } `json:"buckets"`
  200. }
  201. m1 := make(map[string]interface{}) //采购单位-中标单位
  202. m2 := 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. //代理机构
  237. aggs1, _, _ := elastic.GetAggs(INDEX_1, INDEX_1, fmt.Sprintf(es_query1, strings.ReplaceAll(bid, ",", `","`)))
  238. var m2Buckets = AggStruct{}
  239. if aggs1 != nil && aggs1["agency_count"] != nil {
  240. bs, err := aggs1["agency_count"].MarshalJSON()
  241. if err != nil {
  242. logx.Info(err)
  243. } else {
  244. if len(bs) == 0 {
  245. logx.Info(err)
  246. } else {
  247. err = json.Unmarshal(bs, &m2Buckets)
  248. logx.Info(err)
  249. if len(m2Buckets.Buckets) > 0 {
  250. for _, v := range m2Buckets.Buckets {
  251. if v.Key != "" && len(v.EntId.Buckets) > 0 && len(v.BuyerId.Buckets) > 0 {
  252. if v.EntId.Buckets[0].Key == "" {
  253. noIds = append(noIds, v.Key)
  254. }
  255. 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}
  256. }
  257. }
  258. }
  259. }
  260. }
  261. }
  262. idName := T.NetworkCom.GetEntIdByName(noIds)
  263. for k, v := range m1 {
  264. v1 := v.(map[string]interface{})
  265. tmp := make(map[string]interface{})
  266. tmp["name"] = k
  267. nameId, _ := v1["nameId"].(string)
  268. if nameId == "" {
  269. nameId = idName[k]
  270. }
  271. tmp["nameId"] = nameId
  272. tmp["coop_size"] = v1["count"]
  273. tmp["coop_amount"] = v1["amount"]
  274. buyerId, _ := v1["buyerId"].(string)
  275. result1[buyerId] = append(result1[buyerId], tmp)
  276. }
  277. for k, v := range m2 {
  278. v1 := v.(map[string]interface{})
  279. tmp := make(map[string]interface{})
  280. tmp["name"] = k
  281. nameId, _ := v1["nameId"].(string)
  282. if nameId == "" {
  283. nameId = idName[k]
  284. }
  285. tmp["nameId"] = nameId
  286. tmp["coop_size"] = v1["count"]
  287. tmp["coop_amount"] = v1["amount"]
  288. buyerId, _ := v1["buyerId"].(string)
  289. result2[buyerId] = append(result2[buyerId], tmp)
  290. }
  291. return
  292. }
  293. type P_History struct {
  294. ProjectId string `ch:"project_id"`
  295. ProjectName string `ch:"project_name"`
  296. ZbTime int64 `ch:"zbtime"`
  297. Href string `ch:"href"`
  298. }
  299. // @Author jianghan
  300. // @Description 合作历史
  301. // @Date 2024/4/20
  302. func GetData3(source string, buyerId, winnerId string) (result []*P_History) {
  303. var rows driver.Rows
  304. if source == "1" {
  305. rows, _ = T.ClickhouseConn.Query(context.TODO(), sql_2_1_1, buyerId, winnerId)
  306. } else if source == "2" {
  307. rows, _ = T.ClickhouseConn.Query(context.TODO(), sql_2_1, buyerId, winnerId)
  308. }
  309. for rows.Next() {
  310. pHis := P_History{}
  311. _ = rows.ScanStruct(&pHis)
  312. pHis.Href = fmt.Sprintf("/article/content/%s.html", encrypt.CommonEncodeArticle("content", pHis.ProjectId))
  313. result = append(result, &pHis)
  314. }
  315. return
  316. }
  317. // @Author jianghan
  318. // @Description 上次合作时间
  319. // @Date 2024/4/24
  320. func LastTimeCoop(buyerId, ent, stype string) (bool, int64) {
  321. zbtime := int64(0)
  322. near := false
  323. if stype == "adiffb" {
  324. sql := `SELECT zbtime FROM information.transaction_info WHERE buyer_id = ? AND has(winner, ?) ORDER BY zbtime DESC LIMIT 1`
  325. _ = T.ClickhouseConn.QueryRow(context.TODO(), sql, buyerId, ent).Scan(&zbtime)
  326. } else if stype == "agency" {
  327. sql := `SELECT zbtime FROM information.transaction_info WHERE buyer_id = ? AND agency = ? ORDER BY zbtime DESC LIMIT 1`
  328. _ = T.ClickhouseConn.QueryRow(context.TODO(), sql, buyerId, ent).Scan(&zbtime)
  329. }
  330. timestamp := time.Now().AddDate(-3, 0, 0).Unix()
  331. if timestamp <= zbtime {
  332. near = true
  333. }
  334. return near, zbtime
  335. }
  336. func LastTimeCoopBath(positionId int64, buyerId string, winners, agencys []string) (map[string]*Cooperate, map[string]*Cooperate) {
  337. adiffb, agency := map[string]*Cooperate{}, map[string]*Cooperate{}
  338. if buyerId == "" {
  339. return adiffb, agency
  340. }
  341. var toSearch = func(tp int, query string, ws []string) {
  342. logx.Info("LastTimeCoopBath once start ", positionId)
  343. defer logx.Info("LastTimeCoopBath once over ", positionId)
  344. wh, newArgs := T.NetworkCom.WhArgs(ws)
  345. query = fmt.Sprintf(query, wh)
  346. args := []interface{}{buyerId}
  347. args = append(args, newArgs...)
  348. rows, err := T.ClickhouseConn.Query(context.Background(), query, args...)
  349. if err != nil {
  350. logx.Error(err)
  351. return
  352. }
  353. for rows.Next() {
  354. var (
  355. one string
  356. zbtime int64
  357. )
  358. if err := rows.Scan(&one, &zbtime); err != nil {
  359. logx.Error(err)
  360. continue
  361. }
  362. c := &Cooperate{
  363. ZbTime: zbtime,
  364. }
  365. timestamp := time.Now().AddDate(-3, 0, 0).Unix()
  366. if timestamp <= c.ZbTime {
  367. c.Near = true
  368. }
  369. if tp == 1 {
  370. adiffb[one] = c
  371. } else {
  372. agency[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 winner_one,max(zbtime) FROM information.transaction_info ARRAY JOIN winner AS winner_one WHERE buyer_id=? AND hasAny(winner,[%s])) group by winner_one`
  382. wns := []string{}
  383. for _, v := range winners {
  384. wns = append(wns, v)
  385. if len(wns) == 50 {
  386. toSearch(1, sql, wns)
  387. wns = []string{}
  388. }
  389. }
  390. if len(wns) > 0 {
  391. toSearch(1, sql, wns)
  392. }
  393. }
  394. if len(agencys) > 0 {
  395. sql := `SELECT agency,max(zbtime) FROM information.transaction_info WHERE buyer_id=? AND agency in (%s) group by agency`
  396. acs := []string{}
  397. for _, v := range agencys {
  398. acs = append(acs, v)
  399. if len(acs) == 50 {
  400. toSearch(2, sql, acs)
  401. acs = []string{}
  402. }
  403. }
  404. if len(acs) > 0 {
  405. toSearch(2, sql, acs)
  406. }
  407. }
  408. return adiffb, agency
  409. }