CoopHistoryService.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. "app.yhyue.com/moapp/jybase/redis"
  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/shopspring/decimal"
  15. "github.com/zeromicro/go-zero/core/logx"
  16. )
  17. const (
  18. NetworkManageCoopHistory = "networkManage_coopHistory_%d_%s"
  19. )
  20. var (
  21. INDEX_1 = "transaction_info_all"
  22. sql_2_0 = `SELECT buyer_id FROM information.transaction_info_all WHERE project_id = ?`
  23. sql_2_2 = `select id as buyer_id from ent_info where company_name=? order by id desc limit 1`
  24. sql_2_1 = `SELECT project_id, project_name, zbtime FROM information.transaction_info_all WHERE buyer_id = ? AND has(winner, ?) ORDER BY zbtime DESC`
  25. sql_2_1_1 = `SELECT project_id, project_name, zbtime FROM information.transaction_info_all WHERE buyer_id = ? AND agency = ? ORDER BY zbtime DESC`
  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. BuyerId string `ch:"buyer_id"`
  58. }
  59. type Cooperate struct {
  60. Near bool
  61. ZbTime int64
  62. }
  63. type AggStruct struct {
  64. Id string `ch:"id"`
  65. Name string `ch:"name"`
  66. Sum uint64 `ch:"sum"`
  67. ProjectMoney decimal.Decimal `ch:"project_money"`
  68. Zbtime int64 `ch:"zbtime"`
  69. }
  70. type PrListRes struct {
  71. Result []*ResultData
  72. Size_1 int64
  73. Size_2 int64
  74. Size_3 int64
  75. Size_4 int64
  76. }
  77. func GetPrList(req *types.CoopHistoryReq) *PrListRes {
  78. redisFlag := ""
  79. if req.Buyer != "" {
  80. redisFlag = req.Buyer
  81. } else if req.Pid != "" {
  82. redisFlag = req.Pid
  83. }
  84. redisKey := fmt.Sprintf(NetworkManageCoopHistory, req.PositionId, req.ChannelType+"_"+redisFlag)
  85. prListRes := &PrListRes{}
  86. if rBt, rErr := redis.GetNewBytes("newother", redisKey); rErr == nil && rBt != nil {
  87. json.Unmarshal(*rBt, &prListRes)
  88. return prListRes
  89. }
  90. pTmp := ProjectTmp{}
  91. var err error
  92. if req.Buyer != "" {
  93. err = T.ClickhouseConn.QueryRow(context.TODO(), sql_2_2, req.Buyer).ScanStruct(&pTmp)
  94. } else if req.Pid != "" {
  95. err = T.ClickhouseConn.QueryRow(context.TODO(), sql_2_0, req.Pid).ScanStruct(&pTmp)
  96. } else {
  97. return prListRes
  98. }
  99. if err != nil || pTmp.BuyerId == "" {
  100. return prListRes
  101. }
  102. // firstparty:甲方 supplier:供应商 adiffb:同甲异业 middleman:中间人 agency:招标代理机构 sup_sub: 上下级
  103. // 1、同甲异业数据/ 3、招标代理机构渠道
  104. // 中间人可介绍业主
  105. var r3 []map[string]interface{}
  106. r3 = FindMiddleman([]string{fmt.Sprintf("'%s'", pTmp.BuyerId)}, req.PositionId, r3)
  107. prListRes.Size_4 = int64(len(r3))
  108. if req.ChannelType == "0" || req.ChannelType == "4" {
  109. for _, m := range r3 {
  110. tmp := ResultData{
  111. SourceType: "middleman",
  112. EntName: common.ObjToString(m["b_name"]),
  113. EntId: common.ObjToString(m["b_id"]),
  114. EntPerson: common.ObjToString(m["personName"]),
  115. Relationship: "业主的关系人",
  116. BuyerId: pTmp.BuyerId,
  117. }
  118. prListRes.Result = append(prListRes.Result, &tmp)
  119. }
  120. }
  121. // 关联单位
  122. var r4 []map[string]interface{}
  123. r4 = Findfirstparty([]string{fmt.Sprintf("'%s'", pTmp.BuyerId)}, r4)
  124. prListRes.Size_2 = int64(len(r4))
  125. if req.ChannelType == "0" || req.ChannelType == "2" {
  126. for _, m := range r4 {
  127. tmp := ResultData{
  128. SourceType: "sup_sub",
  129. EntName: common.ObjToString(m["b_name"]),
  130. EntId: common.ObjToString(m["b_id"]),
  131. EntPerson: common.ObjToString(m["personName"]),
  132. Relationship: common.ObjToString(m["relationship"]),
  133. BuyerId: pTmp.BuyerId,
  134. }
  135. prListRes.Result = append(prListRes.Result, &tmp)
  136. }
  137. }
  138. scopeClass := FindBusiness(req.EntId, req.EntUserId)
  139. r1 := GetWinnerData(scopeClass, pTmp.BuyerId)
  140. prListRes.Size_1 = int64(len(r1))
  141. if req.ChannelType == "0" || req.ChannelType == "1" {
  142. for _, m := range r1 {
  143. tmp := ResultData{
  144. SourceType: "adiffb",
  145. EntName: m.Name,
  146. ProjectNum: int(m.Sum),
  147. BuyerId: pTmp.BuyerId,
  148. RecentTime: m.Zbtime,
  149. }
  150. tmp.TotalAmount, _ = m.ProjectMoney.Float64()
  151. if time.Now().AddDate(-3, 0, 0).Unix() <= tmp.RecentTime {
  152. tmp.NearlyYears = true
  153. }
  154. prListRes.Result = append(prListRes.Result, &tmp)
  155. }
  156. }
  157. r2 := GetAgencyData(pTmp.BuyerId)
  158. prListRes.Size_3 = int64(len(r2))
  159. if req.ChannelType == "0" || req.ChannelType == "3" {
  160. for _, m := range r2 {
  161. tmp := ResultData{
  162. SourceType: "agency",
  163. EntName: m.Name,
  164. ProjectNum: int(m.Sum),
  165. BuyerId: pTmp.BuyerId,
  166. RecentTime: m.Zbtime,
  167. }
  168. tmp.TotalAmount, _ = m.ProjectMoney.Float64()
  169. if time.Now().AddDate(-3, 0, 0).Unix() <= tmp.RecentTime {
  170. tmp.NearlyYears = true
  171. }
  172. prListRes.Result = append(prListRes.Result, &tmp)
  173. }
  174. }
  175. redis.Put("newother", redisKey, prListRes, T.C.CacheTimeOut)
  176. return prListRes
  177. }
  178. func GetWinnerData(scopeClass string, bid string) []AggStruct {
  179. ass := []AggStruct{}
  180. if scopeClass == "" {
  181. return ass
  182. }
  183. args := []interface{}{bid, bid}
  184. wh, newArgs := common.WhArgs(strings.Split(scopeClass, ","))
  185. args = append(args, newArgs...)
  186. rows, err1 := T.ClickhouseConn.Query(context.TODO(), `select winner as name,winner_id as id,sum(1) as sum,sum(project_money) as project_money,max(zbtime) as zbtime from information.transaction_info_all ARRAY JOIN winner_id,winner
  187. WHERE buyer_id IN (SELECT buyer_id from information.transaction_info_all WHERE has(winner_id,?) and buyer_id<>'') and winner_id<>? AND hasAny(topscopeclass,[`+wh+`])=0 group by winner,winner_id`, args...)
  188. if err1 != nil {
  189. logx.Error(err1)
  190. return ass
  191. }
  192. for rows.Next() {
  193. as := AggStruct{}
  194. if err := rows.ScanStruct(&as); err != nil {
  195. logx.Error(err)
  196. continue
  197. }
  198. ass = append(ass, as)
  199. }
  200. rows.Close()
  201. if err := rows.Err(); err != nil {
  202. logx.Error(err)
  203. }
  204. return ass
  205. }
  206. //代理机构
  207. func GetAgencyData(bid string) []AggStruct {
  208. ass := []AggStruct{}
  209. rows, err1 := T.ClickhouseConn.Query(context.TODO(), `select agency as name,agency_id as id,sum(1) as sum,sum(project_money) as project_money,max(zbtime) as zbtime from information.transaction_info_all where buyer_id=? and agency<>'' and agency_id<>'' GROUP by agency,agency_id`, bid)
  210. if err1 != nil {
  211. logx.Error(err1)
  212. return ass
  213. }
  214. for rows.Next() {
  215. as := AggStruct{}
  216. if err := rows.ScanStruct(&as); err != nil {
  217. logx.Error(err)
  218. continue
  219. }
  220. ass = append(ass, as)
  221. }
  222. rows.Close()
  223. if err := rows.Err(); err != nil {
  224. logx.Error(err)
  225. }
  226. return ass
  227. }
  228. type P_History struct {
  229. ProjectId string `ch:"project_id"`
  230. ProjectName string `ch:"project_name"`
  231. ZbTime int64 `ch:"zbtime"`
  232. Href string `ch:"href"`
  233. }
  234. // @Author jianghan
  235. // @Description 合作历史
  236. // @Date 2024/4/20
  237. func GetData3(source string, buyerId, winnerId string) (result []*P_History) {
  238. var rows driver.Rows
  239. if source == "1" {
  240. rows, _ = T.ClickhouseConn.Query(context.TODO(), sql_2_1_1, buyerId, winnerId)
  241. } else if source == "2" {
  242. rows, _ = T.ClickhouseConn.Query(context.TODO(), sql_2_1, buyerId, winnerId)
  243. }
  244. for rows.Next() {
  245. pHis := P_History{}
  246. _ = rows.ScanStruct(&pHis)
  247. pHis.Href = fmt.Sprintf("/article/content/%s.html", encrypt.CommonEncodeArticle("content", pHis.ProjectId))
  248. result = append(result, &pHis)
  249. }
  250. return
  251. }
  252. // @Author jianghan
  253. // @Description 上次合作时间
  254. // @Date 2024/4/24
  255. func LastTimeCoop(buyerId, ent, stype string) (bool, int64) {
  256. zbtime := int64(0)
  257. near := false
  258. if stype == "adiffb" {
  259. sql := `SELECT zbtime FROM information.transaction_info_all WHERE buyer_id = ? AND has(winner, ?) ORDER BY zbtime DESC LIMIT 1`
  260. _ = T.ClickhouseConn.QueryRow(context.TODO(), sql, buyerId, ent).Scan(&zbtime)
  261. } else if stype == "agency" {
  262. sql := `SELECT zbtime FROM information.transaction_info_all WHERE buyer_id = ? AND agency = ? ORDER BY zbtime DESC LIMIT 1`
  263. _ = T.ClickhouseConn.QueryRow(context.TODO(), sql, buyerId, ent).Scan(&zbtime)
  264. }
  265. timestamp := time.Now().AddDate(-3, 0, 0).Unix()
  266. if timestamp <= zbtime {
  267. near = true
  268. }
  269. return near, zbtime
  270. }
  271. func LastTimeCoopBath(positionId int64, buyerId string, winners, agencys []string) (map[string]*Cooperate, map[string]*Cooperate) {
  272. adiffb, agency := map[string]*Cooperate{}, map[string]*Cooperate{}
  273. if buyerId == "" {
  274. return adiffb, agency
  275. }
  276. var toSearch = func(tp int, query string, ws []string) {
  277. logx.Info("LastTimeCoopBath once start ", positionId)
  278. defer logx.Info("LastTimeCoopBath once over ", positionId)
  279. wh, newArgs := common.WhArgs(ws)
  280. query = fmt.Sprintf(query, wh)
  281. args := []interface{}{buyerId}
  282. args = append(args, newArgs...)
  283. rows, err := T.ClickhouseConn.Query(context.Background(), query, args...)
  284. if err != nil {
  285. logx.Error(err)
  286. return
  287. }
  288. for rows.Next() {
  289. var (
  290. one string
  291. zbtime int64
  292. )
  293. if err := rows.Scan(&one, &zbtime); err != nil {
  294. logx.Error(err)
  295. continue
  296. }
  297. c := &Cooperate{
  298. ZbTime: zbtime,
  299. }
  300. timestamp := time.Now().AddDate(-3, 0, 0).Unix()
  301. if timestamp <= c.ZbTime {
  302. c.Near = true
  303. }
  304. if tp == 1 {
  305. adiffb[one] = c
  306. } else {
  307. agency[one] = c
  308. }
  309. }
  310. rows.Close()
  311. if err := rows.Err(); err != nil {
  312. logx.Error(err)
  313. }
  314. }
  315. if len(winners) > 0 {
  316. key := fmt.Sprintf("networkManage_lastTimeCoop_winner_%s", common.GetMd5String(buyerId+"_"+strings.Join(winners, ",")))
  317. wb, err := redis.GetBytes("newother", key)
  318. if err == nil {
  319. json.Unmarshal(*wb, &adiffb)
  320. } else {
  321. 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`
  322. wns := []string{}
  323. for _, v := range winners {
  324. wns = append(wns, v)
  325. if len(wns) == 50 {
  326. toSearch(1, sql, wns)
  327. wns = []string{}
  328. }
  329. }
  330. if len(wns) > 0 {
  331. toSearch(1, sql, wns)
  332. }
  333. redis.Put("newother", key, adiffb, T.C.CacheTimeOut)
  334. }
  335. }
  336. if len(agencys) > 0 {
  337. key := fmt.Sprintf("networkManage_lastTimeCoop_agency_%s", common.GetMd5String(buyerId+"_"+strings.Join(agencys, ",")))
  338. wb, err := redis.GetBytes("newother", key)
  339. if err == nil {
  340. json.Unmarshal(*wb, &agency)
  341. } else {
  342. sql := `SELECT agency,max(zbtime) FROM information.transaction_info_all WHERE buyer_id=? AND agency in (%s) group by agency`
  343. acs := []string{}
  344. for _, v := range agencys {
  345. acs = append(acs, v)
  346. if len(acs) == 50 {
  347. toSearch(2, sql, acs)
  348. acs = []string{}
  349. }
  350. }
  351. if len(acs) > 0 {
  352. toSearch(2, sql, acs)
  353. }
  354. redis.Put("newother", key, agency, T.C.CacheTimeOut)
  355. }
  356. }
  357. return adiffb, agency
  358. }