owner.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "sort"
  7. "strings"
  8. "time"
  9. "app.yhyue.com/moapp/jybase/common"
  10. "app.yhyue.com/moapp/jybase/encrypt"
  11. "app.yhyue.com/moapp/jybase/redis"
  12. . "bp.jydev.jianyu360.cn/CRM/networkManage/api/common"
  13. T "bp.jydev.jianyu360.cn/CRM/networkManage/api/common"
  14. "bp.jydev.jianyu360.cn/CRM/networkManage/entity"
  15. "github.com/gogf/gf/v2/util/gconv"
  16. "github.com/shopspring/decimal"
  17. "github.com/zeromicro/go-zero/core/logx"
  18. )
  19. const (
  20. EntINDEX = "ent_info"
  21. EntTYPE = "ent_info"
  22. NetworkManageOwnerlList = "networkManage_ownerlList_%d_%s"
  23. )
  24. type OwnerService struct {
  25. PartyA string
  26. Supplier string
  27. Heterotophy string
  28. Intermediary string
  29. Agency string
  30. SearchEntName string
  31. SourceType string
  32. Area string
  33. PositionId int64
  34. PageIndex int64
  35. PageSize int64
  36. BuyerId string
  37. BuyerName string
  38. WinnerId string
  39. WinnerName string
  40. CooperateType string
  41. EntAccountId int64
  42. ProjectType string
  43. Type string
  44. EntId int64
  45. UserId string
  46. }
  47. type BuyerProject struct {
  48. BuyerId string
  49. BuyerName string
  50. Project ProjectEntity
  51. IsMonitor bool
  52. Area string
  53. Zbtime int64
  54. BuyerType string
  55. CId string
  56. }
  57. type ProjectEntity struct {
  58. Number int64
  59. zbtime int64
  60. EstimatedAmount int64
  61. Connections []map[string]interface{}
  62. }
  63. type Recommend struct {
  64. BuyerId string `ch:"buyer_id"`
  65. Buyer string `ch:"buyer"`
  66. }
  67. type Project struct {
  68. BuyerId string `ch:"buyer_id"`
  69. Area string `ch:"area"`
  70. GroupCount uint64 `ch:"group_count"`
  71. Zbtime int64 `ch:"zbtime"`
  72. Money decimal.Decimal `ch:"money"`
  73. }
  74. type OwnerlListRes struct {
  75. ReturnData []BuyerProject
  76. ConnectionsNumber int64
  77. }
  78. // OwnerlList 执行主要的业务逻辑
  79. func (t *OwnerService) OwnerlList() *OwnerlListRes {
  80. // 先查询采购单位列表
  81. businessStr := FindBusiness(t.EntId, t.UserId)
  82. // 初始化分页参数
  83. if t.PageSize == 0 {
  84. t.PageSize = 10
  85. }
  86. if t.PageIndex == 0 {
  87. t.PageIndex = 1
  88. }
  89. olr := &OwnerlListRes{
  90. ReturnData: []BuyerProject{},
  91. }
  92. // 如果没有业务字符串,直接返回空数据
  93. if businessStr == "" {
  94. return olr
  95. }
  96. logx.Info(t.PositionId, " OwnerlList start 。。。")
  97. //监控状态处理
  98. monitorMap := NetworkCom.EntMonitor(gconv.String(t.PositionId))
  99. comKey := common.GetMd5String(fmt.Sprintf("%+v business:%s", t, businessStr))
  100. listKey := fmt.Sprintf(NetworkManageOwnerlList, t.PositionId, comKey)
  101. getFromCache := false
  102. monitorBuyers := []string{}
  103. if t.SourceType != "2" {
  104. // 检查 Redis 中是否存在列表缓存
  105. if rb, err := redis.GetNewBytes("newother", listKey); err == nil && rb != nil {
  106. if json.Unmarshal(*rb, &olr) == nil {
  107. getFromCache = true
  108. }
  109. }
  110. } else {
  111. for k, _ := range monitorMap {
  112. monitorBuyers = append(monitorBuyers, k)
  113. }
  114. }
  115. // 没有缓存时的处理逻辑
  116. if !getFromCache {
  117. dataMap := BuyerList(t.PartyA, t.Intermediary, t.PositionId)
  118. if len(*dataMap) == 0 && t.Supplier == "" && t.Heterotophy == "" && t.Agency == "" {
  119. return olr
  120. }
  121. logx.Info(t.PositionId, " BuyerList over 。。。")
  122. // 项目数量查询
  123. buyerArr := getBuyerArr(dataMap)
  124. // 项目数量处理
  125. logx.Info(t.PositionId, " ProjectHandle start 。。。")
  126. projectMap, connectionsNumber := t.ProjectHandle(buyerArr, businessStr, monitorBuyers)
  127. logx.Info(t.PositionId, " ProjectHandle over 。。。")
  128. if len(*projectMap) == 0 {
  129. return olr
  130. }
  131. olr.ConnectionsNumber = connectionsNumber
  132. // 采购单位和项目合并
  133. a1 := time.Now().Unix()
  134. olr.ReturnData = BuyerProjectMerge(dataMap, projectMap)
  135. a2 := time.Now().Unix()
  136. fmt.Println("组合数据", a2-a1)
  137. /*if len(returnData) > 0 {
  138. //redis.Put("newother", comKey, returnData, C.CacheTimeOut)
  139. sort.Slice(returnData, func(i, j int) bool {
  140. aa := fmt.Sprintf("%d%s", (returnData)[i].Zbtime, (returnData)[i].BuyerId)
  141. bb := fmt.Sprintf("%d%s", (returnData)[j].Zbtime, (returnData)[j].BuyerId)
  142. return aa > bb
  143. })
  144. }*/
  145. buyerIdArr := []string{}
  146. for _, value := range olr.ReturnData {
  147. if value.BuyerId != "" {
  148. buyerIdArr = append(buyerIdArr, value.BuyerId)
  149. }
  150. }
  151. // 可介绍业主人脉处理
  152. logx.Info(t.PositionId, " ConnectionsHandle start 。。。")
  153. routeList := ConnectionsHandle(t.PositionId, buyerIdArr)
  154. logx.Info(t.PositionId, " ConnectionsHandle over 。。。")
  155. updateReturnDataWithRoutes(olr.ReturnData, routeList)
  156. PersonFindConnectionsHandle(t.PositionId, olr.ReturnData, 1)
  157. }
  158. if len(olr.ReturnData) > 0 {
  159. for k, value := range olr.ReturnData {
  160. if _, ok := monitorMap[value.BuyerName]; ok {
  161. olr.ReturnData[k].IsMonitor = true
  162. } else {
  163. olr.ReturnData[k].IsMonitor = false
  164. }
  165. }
  166. redis.Put("newother", listKey, olr, NetworkCom.CacheTimeout())
  167. }
  168. // 返回数据组装
  169. return olr
  170. }
  171. // getBuyerArr 从数据映射中获取买家数组
  172. func getBuyerArr(dataMap *map[string]map[string]interface{}) []string {
  173. buyerArr := []string{}
  174. for k, _ := range *dataMap {
  175. buyerArr = append(buyerArr, k)
  176. }
  177. return buyerArr
  178. }
  179. // updateReturnDataWithRoutes 将路线信息更新到返回数据中
  180. func updateReturnDataWithRoutes(returnData []BuyerProject, routeList []map[string]interface{}) {
  181. for _, v := range routeList {
  182. buyerId := gconv.String(v["a_id"])
  183. for i, v1 := range returnData {
  184. aBuyerId := v1.BuyerId
  185. if buyerId == aBuyerId {
  186. // 组装数据
  187. returnData[i].Project.Connections = append(returnData[i].Project.Connections, v)
  188. }
  189. }
  190. }
  191. }
  192. // 可介绍业主人脉列表
  193. func ConnectionsHandle(positionId int64, buyerArr []string) []map[string]interface{} {
  194. returnData := []map[string]interface{}{}
  195. //中间人
  196. logx.Info(positionId, " ConnectionsHandle start 。。。")
  197. FindMiddleman(positionId, buyerArr, returnData)
  198. logx.Info(positionId, " FindMiddleman over 。。。")
  199. //采购单位 投资关系 管辖关系
  200. //采购单位
  201. Findfirstparty(positionId, buyerArr, returnData)
  202. logx.Info(positionId, " Findfirstparty over 。。。")
  203. returnData = append(returnData, Findwinner(positionId, buyerArr)...)
  204. logx.Info(positionId, " Findwinner over 。。。")
  205. return returnData
  206. }
  207. // 供应商处理
  208. func Findwinner(positionId int64, buyerArr []string) []map[string]interface{} {
  209. returnData := []map[string]interface{}{}
  210. if len(buyerArr) == 0 {
  211. return returnData
  212. }
  213. wh1, args1 := common.WhArgs(buyerArr)
  214. //供应商 采购单位 供应商 招标代理机构 采购单位 招标代理机构 需要计算合作次数
  215. winnerSql := `select zbtime,project_id,project_name,buyer_id,buyer,wr_id,wr,agency_id,agency from transaction_info_all ARRAY JOIN winner_id as wr_id,winner as wr prewhere buyer_id in (` + wh1 + `) and LENGTH(winner)=LENGTH(winner_id)`
  216. logx.Info(positionId, " Findwinner 合作 sql ", winnerSql, args1)
  217. winnerArr := SupplierFindConnectionsHandle(winnerSql, args1...)
  218. if winnerArr == nil || len(winnerArr) == 0 {
  219. return returnData
  220. }
  221. winnerMap := map[string]map[string]interface{}{}
  222. agencyMap := map[string]map[string]interface{}{}
  223. agencyIdMap := map[string]bool{}
  224. for _, m := range winnerArr {
  225. if m.Winner_id == "" && m.Agency_id == "" {
  226. continue
  227. }
  228. projectId := encrypt.EncodeArticleId2ByCheck(m.Project_id)
  229. projectName := m.Project_name
  230. zbtime := m.Zbtime
  231. if m.Winner_id != "" {
  232. key := fmt.Sprintf("%s_%s", m.Buyer_id, m.Winner_id)
  233. if _, ok := winnerMap[key]; ok {
  234. data := winnerMap[key]
  235. data["count"] = gconv.Int64(data["count"]) + 1
  236. dataList := gconv.Maps(data["list"])
  237. dataList = append(dataList, map[string]interface{}{
  238. "zbtime": zbtime,
  239. "projectId": projectId,
  240. "projectName": projectName,
  241. })
  242. data["list"] = dataList
  243. data["zbtime"] = zbtime
  244. winnerMap[key] = data
  245. } else {
  246. winnerMap[key] = map[string]interface{}{
  247. "b_id": m.Winner_id,
  248. "b_name": m.Winner,
  249. "a_name": m.Buyer,
  250. "a_id": m.Buyer_id,
  251. "sourceType": "supplier",
  252. "zbtime": zbtime,
  253. "count": 1,
  254. "list": []map[string]interface{}{
  255. {
  256. "zbtime": zbtime,
  257. "entName": m.Winner,
  258. "projectId": projectId,
  259. "projectName": projectName,
  260. },
  261. },
  262. }
  263. }
  264. }
  265. if m.Agency_id != "" {
  266. key := fmt.Sprintf("%s_%s", m.Buyer_id, m.Agency_id)
  267. if _, ok := agencyIdMap[key]; ok {
  268. data := agencyMap[key]
  269. data["count"] = gconv.Int64(data["count"]) + 1
  270. dataList := gconv.Maps(data["list"])
  271. dataList = append(dataList, map[string]interface{}{
  272. "zbtime": zbtime,
  273. "projectId": projectId,
  274. "projectName": projectName,
  275. })
  276. data["list"] = dataList
  277. data["zbtime"] = zbtime
  278. agencyMap[key] = data
  279. } else {
  280. agencyIdMap[key] = true
  281. agencyMap[key] = map[string]interface{}{
  282. "b_id": m.Agency_id,
  283. "b_name": m.Agency,
  284. "a_name": m.Buyer,
  285. "a_id": m.Buyer_id,
  286. "sourceType": "agency",
  287. "count": 1,
  288. "zbtime": zbtime,
  289. "list": []map[string]interface{}{
  290. {
  291. "zbtime": zbtime,
  292. "projectId": projectId,
  293. "projectName": projectName,
  294. },
  295. },
  296. }
  297. }
  298. }
  299. }
  300. for _, m := range winnerMap {
  301. returnData = append(returnData, map[string]interface{}{
  302. "b_id": gconv.String(m["b_id"]),
  303. "b_name": gconv.String(m["b_name"]),
  304. "a_name": gconv.String(m["a_name"]),
  305. "a_id": gconv.String(m["a_id"]),
  306. "sourceType": gconv.String(m["sourceType"]),
  307. "relationship": gconv.String(m["relationship"]),
  308. "count": gconv.Int64(m["count"]),
  309. "personName": gconv.String(m["personName"]),
  310. "list": m["list"],
  311. "zbtime": m["zbtime"],
  312. })
  313. }
  314. for _, m := range agencyMap {
  315. returnData = append(returnData, map[string]interface{}{
  316. "b_id": gconv.String(m["b_id"]),
  317. "b_name": gconv.String(m["b_name"]),
  318. "a_name": gconv.String(m["a_name"]),
  319. "a_id": gconv.String(m["a_id"]),
  320. "sourceType": gconv.String(m["sourceType"]),
  321. "relationship": gconv.String(m["relationship"]),
  322. "personName": gconv.String(m["personName"]),
  323. "count": gconv.Int64(m["count"]),
  324. "list": m["list"],
  325. "zbtime": m["zbtime"],
  326. })
  327. }
  328. sort.Slice(returnData, func(i, j int) bool {
  329. aa := fmt.Sprintf("%s%s", gconv.String(returnData[i]["zbtime"]), gconv.String(returnData[i]["b_id"]))
  330. bb := fmt.Sprintf("%s%s", gconv.String(returnData[j]["zbtime"]), gconv.String(returnData[j]["b_id"]))
  331. return aa > bb
  332. })
  333. return returnData
  334. }
  335. // 中间人查询
  336. func FindMiddleman(positionId int64, buyerArr []string, returnData []map[string]interface{}) {
  337. if len(buyerArr) == 0 {
  338. return
  339. }
  340. //中间人 作为可介绍业主 企业名称
  341. wh, args := common.WhArgs(buyerArr)
  342. newArgs := []interface{}{positionId}
  343. newArgs = append(newArgs, args...)
  344. companyArr := CrmMysql.SelectBySql(`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 in (`+wh+`) and a.itype =1 and b.itype=4 and b.status=1`, newArgs...)
  345. for _, v := range *companyArr {
  346. companyId := gconv.String(v["company_id"])
  347. companyName := gconv.String(v["company_name"])
  348. relateName := gconv.String(v["relate_name"])
  349. relateId := gconv.String(v["relate_id"])
  350. returnData = append(returnData, map[string]interface{}{
  351. "b_id": companyId,
  352. "b_name": companyName,
  353. "a_name": relateName,
  354. "a_id": relateId,
  355. "sourceType": "middleman",
  356. "relationship": "业主的关系人",
  357. "personName": gconv.String(v["contact_person"]),
  358. })
  359. }
  360. return
  361. }
  362. // 企业之间关系查询
  363. func Findfirstparty(positionId int64, buyerArr []string, returnData []map[string]interface{}) {
  364. if len(buyerArr) == 0 {
  365. return
  366. }
  367. wh1, args1 := common.WhArgs(buyerArr)
  368. args1 = append(args1, args1...)
  369. buyerSql := `select DISTINCT
  370. a.a_id as a_id,
  371. a.b_id as b_id,
  372. a.a_name as a_name,
  373. a.b_name as b_name,
  374. 111 as status,
  375. a.code as code
  376. from
  377. ent_map_code a
  378. prewhere
  379. a.a_id in (` + wh1 + `)
  380. and a.code in('0101', '0201')
  381. UNION ALL
  382. select
  383. a.b_id as a_id,
  384. a.a_id as b_id,
  385. a.b_name as a_name,
  386. a.a_name as b_name,
  387. 222 as status,
  388. a.code as code
  389. from
  390. ent_map_code a
  391. prewhere
  392. a.b_id in (` + wh1 + `)
  393. and a.code in('0101', '0201')`
  394. relationshipArr := BuyerFindConnectionsHandle(buyerSql, args1...)
  395. if relationshipArr == nil || len(relationshipArr) == 0 {
  396. return
  397. }
  398. for _, v := range relationshipArr {
  399. code := v.Code
  400. status := v.Status
  401. if gconv.String(status) == "111" {
  402. //key := fmt.Sprintf("%s_%s", a_id, b_id)
  403. switch code {
  404. case "0101": //管辖关系
  405. returnData = append(returnData, map[string]interface{}{
  406. "b_id": v.Bid,
  407. "b_name": v.Bname,
  408. "a_name": v.Aname,
  409. "a_id": v.Aid,
  410. "sourceType": "firstparty",
  411. "relationship": "业主的下级机构",
  412. })
  413. case "0201": //投资关系
  414. returnData = append(returnData, map[string]interface{}{
  415. "b_id": v.Bid,
  416. "b_name": v.Bname,
  417. "a_name": v.Aname,
  418. "a_id": v.Aid,
  419. "sourceType": "firstparty",
  420. "relationship": "业主的股东",
  421. })
  422. }
  423. }
  424. if gconv.String(status) == "222" {
  425. //key := fmt.Sprintf("%s_%s", b_id, a_id)
  426. if code == "0101" {
  427. //"0101":管辖关系
  428. returnData = append(returnData, map[string]interface{}{
  429. "b_id": v.Bid,
  430. "b_name": v.Bname,
  431. "a_name": v.Aname,
  432. "a_id": v.Aid,
  433. "sourceType": "firstparty",
  434. "relationship": "业主的上级机构",
  435. })
  436. }
  437. if code == "0201" {
  438. returnData = append(returnData, map[string]interface{}{
  439. "b_id": v.Bid,
  440. "b_name": v.Bname,
  441. "a_name": v.Aname,
  442. "a_id": v.Aid,
  443. "sourceType": "firstparty",
  444. "relationship": "业主的股东",
  445. })
  446. }
  447. }
  448. }
  449. return
  450. }
  451. // 采购单位和项目合并
  452. func BuyerProjectMerge(dataMap, projectMap *map[string]map[string]interface{}) []BuyerProject {
  453. returnData := []BuyerProject{}
  454. for buyerName, project := range *projectMap {
  455. buyerId := gconv.String(project["buyerId"])
  456. data := (*dataMap)[buyerId]
  457. returnData = append(returnData, BuyerProject{
  458. BuyerId: buyerId,
  459. BuyerName: buyerName,
  460. BuyerType: gconv.String(data["buyerType"]),
  461. Project: ProjectEntity{
  462. Number: gconv.Int64(project["count"]),
  463. EstimatedAmount: gconv.Int64(project["money"]),
  464. Connections: []map[string]interface{}{},
  465. },
  466. Area: gconv.String(project["area"]),
  467. Zbtime: gconv.Int64(project["area"]),
  468. IsMonitor: gconv.Bool(data["isMonitor"]),
  469. CId: gconv.String(data["cId"]),
  470. })
  471. }
  472. return returnData
  473. }
  474. func FindStatus(positionId int64) (map[string]bool, map[string]bool, map[string]bool) {
  475. //未处理
  476. untreatedMap := map[string]bool{}
  477. //已忽略
  478. ignoredMap := map[string]bool{}
  479. //已创建
  480. createdMap := map[string]bool{}
  481. processingArr := CrmMysql.Find(entity.CONNECTION_STATUS, map[string]interface{}{
  482. "itype": 1,
  483. "position_id": positionId,
  484. }, "relate_id,is_handle,is_ignore,is_create", "", -1, -1)
  485. if processingArr != nil && len(*processingArr) > 0 {
  486. for _, v := range *processingArr {
  487. entId := gconv.String(v["relate_id"])
  488. handle := gconv.Int64(v["is_handle"])
  489. ignore := gconv.Int64(v["is_ignore"])
  490. create := gconv.Int64(v["is_create"])
  491. if handle == 1 {
  492. untreatedMap[entId] = true
  493. }
  494. if ignore == 1 {
  495. ignoredMap[entId] = true
  496. }
  497. if create == 1 {
  498. createdMap[entId] = true
  499. }
  500. }
  501. }
  502. return untreatedMap, ignoredMap, createdMap
  503. }
  504. // 采购单位查询
  505. func BuyerList(partyA, intermediary string, positionId int64) *map[string]map[string]interface{} {
  506. dataMap := &map[string]map[string]interface{}{}
  507. //甲方
  508. if partyA != "" {
  509. for _, v := range strings.Split(partyA, ",") {
  510. (*dataMap)[v] = map[string]interface{}{
  511. "buyerType": "firstparty",
  512. }
  513. }
  514. // intermediaryArr := []string{}
  515. // for _, v := range strings.Split(partyA, ",") {
  516. // if v != "" {
  517. // intermediaryArr = append(intermediaryArr, fmt.Sprintf("'%s'", v))
  518. // }
  519. // }
  520. // if len(partyA) > 0 {
  521. // partyASql := fmt.Sprintf(`select id as buyer_id,company_name as buyer from ent_info where id in (%s)`, strings.Join(intermediaryArr, ","))
  522. // FindHandle(partyASql, dataMap, "firstparty")
  523. // }
  524. }
  525. //供应商 //同甲异业
  526. // findInSetArr := []string{}
  527. // if supplier != "" {
  528. // for _, v := range strings.Split(supplier, ",") {
  529. // if v != "" {
  530. // findInSetArr = append(findInSetArr, fmt.Sprintf("'%s'", v))
  531. // }
  532. // }
  533. // }
  534. // if len(findInSetArr) > 0 {
  535. // sqlStr := fmt.Sprintf(`SELECT buyer_id,buyer FROM transaction_info_all where hasAny(winner_id,[%s]) `, strings.Join(findInSetArr, ","))
  536. // FindHandle(sqlStr, dataMap, "supplier")
  537. // }
  538. //同甲异业
  539. // findheterotophyArr := []string{}
  540. // if heterotophy != "" {
  541. // for _, v := range strings.Split(heterotophy, ",") {
  542. // if v != "" {
  543. // findheterotophyArr = append(findheterotophyArr, fmt.Sprintf("'%s'", v))
  544. // }
  545. // }
  546. // }
  547. // if len(findheterotophyArr) > 0 {
  548. // sqlStr := fmt.Sprintf(`SELECT buyer_id,buyer FROM transaction_info_all where hasAny(winner_id,[%s]) `, strings.Join(findheterotophyArr, ","))
  549. // FindHandle(sqlStr, dataMap, "adiffb")
  550. // }
  551. //中间人
  552. if intermediary != "" {
  553. wh, args := common.WhArgs(strings.Split(intermediary, ","))
  554. args = append(args, positionId)
  555. intermediaryArr := CrmMysql.SelectBySql(`select a.id,b.relate_id as relate_id,b.relate_name as relate_name from crm.connection a inner join crm.connection_introduce b on ( a.id in (`+wh+`) and a.position_id=? and a.id=b.connection_id and b.itype=1)`, args...)
  556. if intermediaryArr != nil && len(*intermediaryArr) > 0 {
  557. for _, m := range *intermediaryArr {
  558. buyerId := gconv.String(m["relate_id"])
  559. buyerName := gconv.String(m["relate_name"])
  560. (*dataMap)[buyerId] = map[string]interface{}{
  561. "buyerName": buyerName,
  562. "buyerType": "middleman",
  563. "cId": gconv.String(m["id"]),
  564. }
  565. }
  566. }
  567. }
  568. //招标代理
  569. // if agency != "" {
  570. // agencyArr := []string{}
  571. // for _, s := range strings.Split(agency, ",") {
  572. // agencyArr = append(agencyArr, fmt.Sprintf("'%s'", s))
  573. // }
  574. // sqlStr := fmt.Sprintf(`SELECT buyer_id,buyer FROM transaction_info_all where agency_id in (%s) `, strings.Join(agencyArr, ","))
  575. // FindHandle(sqlStr, dataMap, "agency")
  576. // }
  577. return dataMap
  578. }
  579. // 项目数量查
  580. func (t *OwnerService) ProjectHandle(buyerArr []string, businessStr string, monitorBuyers []string) (*map[string]map[string]interface{}, int64) {
  581. projectMap := &map[string]map[string]interface{}{}
  582. startIndex := (t.PageIndex - 1) * t.PageSize
  583. whBs, allArgs := common.WhArgs(strings.Split(businessStr, ","))
  584. allArgs = append(allArgs, allArgs...)
  585. sqlStr := `select buyer,buyer_id,groupUniqArray(area) as areaStr,count(if(project_bidstatus>1 and hasAny(topscopeclass,[`
  586. sqlStr += whBs + `])=1,1,null)) as ocount,SUM(if(project_bidstatus>1 and hasAny(topscopeclass,[`
  587. sqlStr += whBs + `])=1,project_money,0)) as project_money,MAX(zbtime) as maxzbtime from transaction_info_all`
  588. ors1 := []string{}
  589. if len(buyerArr) > 0 {
  590. wh, args := common.WhArgs(buyerArr)
  591. ors1 = append(ors1, `buyer_id in (`+wh+`)`)
  592. allArgs = append(allArgs, args...)
  593. }
  594. wm := map[string]bool{}
  595. winner_ids := []string{}
  596. if t.Supplier != "" {
  597. for _, v := range strings.Split(t.Supplier, ",") {
  598. if wm[v] {
  599. continue
  600. }
  601. winner_ids = append(winner_ids, v)
  602. wm[v] = true
  603. }
  604. }
  605. if t.Heterotophy != "" {
  606. for _, v := range strings.Split(t.Heterotophy, ",") {
  607. if wm[v] {
  608. continue
  609. }
  610. winner_ids = append(winner_ids, v)
  611. wm[v] = true
  612. }
  613. }
  614. ors2 := []string{}
  615. if len(winner_ids) > 0 {
  616. wh, args := common.WhArgs(winner_ids)
  617. ors2 = append(ors2, `hasAny(winner_id,[`+wh+`])`)
  618. allArgs = append(allArgs, args...)
  619. }
  620. if t.Agency != "" {
  621. wh, args := common.WhArgs(strings.Split(t.Agency, ","))
  622. ors2 = append(ors2, `agency_id in (`+wh+`)`)
  623. allArgs = append(allArgs, args...)
  624. }
  625. if len(ors2) > 0 {
  626. ors1 = append(ors1, `(buyer_id in (select DISTINCT buyer_id from transaction_info_all prewhere (`+strings.Join(ors2, " or ")+`) and buyer_id<>''))`)
  627. }
  628. allArgs = append(allArgs, NetworkCom.ProjectYearLimit())
  629. ands := []string{}
  630. if len(monitorBuyers) > 0 {
  631. wh, args := common.WhArgs(monitorBuyers)
  632. ands = append(ands, `buyer in (`+wh+`)`)
  633. allArgs = append(allArgs, args...)
  634. }
  635. if t.Area != "" {
  636. wh, args := common.WhArgs(strings.Split(t.Area, ","))
  637. ands = append(ands, `area in (`+wh+`)`)
  638. allArgs = append(allArgs, args...)
  639. }
  640. sqlStr += " prewhere (" + strings.Join(ors1, " or ") + ") and zbtime>?"
  641. if len(ands) > 0 {
  642. sqlStr += " and " + strings.Join(ands, " and ")
  643. }
  644. sqlStr += " GROUP by buyer,buyer_id"
  645. if t.SourceType == "1" {
  646. sqlStr += " HAVING ocount>2 "
  647. }
  648. countSql := fmt.Sprintf("select count(1) as count from (%s) b ", sqlStr)
  649. sqlStr += fmt.Sprintf(" order by maxzbtime desc limit %d,%d", startIndex, t.PageSize)
  650. logx.Info(t.PositionId, " ProjectHandle sql ", sqlStr, allArgs)
  651. //总数查询
  652. ass := []BuyerAggStruct{}
  653. rows, err1 := ClickhouseConn.Query(context.TODO(), sqlStr, allArgs...)
  654. if err1 != nil {
  655. logx.Error(err1)
  656. return projectMap, 0
  657. }
  658. defer rows.Close()
  659. for rows.Next() {
  660. as := BuyerAggStruct{}
  661. if err := rows.ScanStruct(&as); err != nil {
  662. logx.Error(err)
  663. continue
  664. }
  665. ass = append(ass, as)
  666. }
  667. for _, object := range ass {
  668. buyerName := object.Buyer
  669. buyerId := object.BuyerId
  670. projectMoney, _ := object.ProjectMoney.Float64()
  671. (*projectMap)[buyerName] = map[string]interface{}{
  672. "area": strings.Join(object.Area, ","),
  673. "zbtime": object.MaxZbtime,
  674. "money": common.RetainDecimal(projectMoney/10000, 2),
  675. "count": object.Ocount,
  676. "buyerId": buyerId,
  677. "buyerName": buyerName,
  678. }
  679. }
  680. logx.Info(t.PositionId, " ProjectHandle sql over 。。。")
  681. count := T.NetworkCom.Count(countSql, allArgs...)
  682. logx.Info(t.PositionId, " ProjectHandle count over 。。。")
  683. return projectMap, count
  684. }
  685. type BuyerAggStruct struct {
  686. Buyer string `ch:"buyer"`
  687. BuyerId string `ch:"buyer_id"`
  688. Area []string `ch:"areaStr"`
  689. ProjectMoney decimal.Decimal `ch:"project_money"`
  690. MaxZbtime int64 `ch:"maxzbtime"`
  691. Ocount uint64 `ch:"ocount"`
  692. }
  693. // 采购单位查询sql
  694. func FindHandle(sqlStr string, dataMap *map[string]map[string]interface{}, buyerType string) {
  695. rows, err := ClickhouseConn.Query(context.Background(), sqlStr)
  696. if err != nil {
  697. logx.Error("查询失败", sqlStr, err)
  698. }
  699. for rows.Next() {
  700. data := Recommend{}
  701. rows.ScanStruct(&data)
  702. if data.BuyerId != "" {
  703. (*dataMap)[data.BuyerId] = map[string]interface{}{
  704. "buyerName": data.Buyer,
  705. "buyerType": buyerType,
  706. }
  707. }
  708. }
  709. return
  710. }
  711. type ConnectionsEntity struct {
  712. Aid string `ch:"a_id"`
  713. Bid string `ch:"b_id"`
  714. Aname string `ch:"a_name"`
  715. Bname string `ch:"b_name"`
  716. Status uint8 `ch:"status"`
  717. Code string `ch:"code"`
  718. Cperson string `ch:"c_person"`
  719. }
  720. type PersonEntity struct {
  721. Id string `ch:"id"`
  722. PersonName string `ch:"personName"`
  723. }
  724. type SupplierConnectionsEntity struct {
  725. Zbtime int64 `ch:"zbtime"`
  726. Project_id string `ch:"project_id"`
  727. Project_name string `ch:"project_name"`
  728. Buyer_id string `ch:"buyer_id"`
  729. Buyer string `ch:"buyer"`
  730. Winner_id string `ch:"wr_id"`
  731. Winner string `ch:"wr"`
  732. Agency_id string `ch:"agency_id"`
  733. Agency string `ch:"agency"`
  734. }
  735. type TimeConnectionsEntity struct {
  736. Zbtime int64 `ch:"zbtime"`
  737. Project_id string `ch:"project_id"`
  738. Project_name string `ch:"project_name"`
  739. }
  740. // 采购单位人脉信息查询sql
  741. func BuyerFindConnectionsHandle(sqlStr string, args ...interface{}) []ConnectionsEntity {
  742. returnData := []ConnectionsEntity{}
  743. rows, err := ClickhouseConn.Query(context.Background(), sqlStr, args...)
  744. if err != nil {
  745. logx.Error("查询失败", sqlStr, err)
  746. }
  747. for rows.Next() {
  748. data := ConnectionsEntity{}
  749. err := rows.ScanStruct(&data)
  750. logx.Info(err)
  751. returnData = append(returnData, data)
  752. }
  753. return returnData
  754. }
  755. func PersonFindConnectionsHandle(positionId int64, bps []BuyerProject, contactCount int) {
  756. if contactCount == 0 {
  757. return
  758. }
  759. //企业联系人处理
  760. entIdArr := []string{}
  761. entIdMap := map[string]bool{}
  762. for _, v := range bps {
  763. for kk, vv := range v.Project.Connections {
  764. b_id, _ := vv["b_id"].(string)
  765. if b_id == "" || entIdMap[b_id] {
  766. continue
  767. }
  768. entIdMap[b_id] = true
  769. entIdArr = append(entIdArr, b_id)
  770. if kk == contactCount-1 {
  771. break
  772. }
  773. }
  774. }
  775. personMap := map[string]string{}
  776. if len(entIdArr) > 0 {
  777. wh2, args2 := common.WhArgs(entIdArr)
  778. personSql := `select id,name as personName from ent_contact prewhere id in (` + wh2 + `) ORDER by name`
  779. logx.Info(positionId, " Findwinner 联系人 sql ", personSql, args2)
  780. pes := []PersonEntity{}
  781. rows, err := ClickhouseConn.Query(context.Background(), personSql, args2...)
  782. if err != nil {
  783. logx.Error("查询失败", personSql, err)
  784. }
  785. for rows.Next() {
  786. data := PersonEntity{}
  787. rows.ScanStruct(&data)
  788. pes = append(pes, data)
  789. }
  790. //联系人处理
  791. for _, v := range pes {
  792. personMap[v.Id] = v.PersonName
  793. }
  794. }
  795. for _, v := range bps {
  796. for kk, vv := range v.Project.Connections {
  797. b_id, _ := vv["b_id"].(string)
  798. vv["personName"] = personMap[b_id]
  799. if kk == contactCount-1 {
  800. break
  801. }
  802. }
  803. }
  804. }
  805. // 供应商
  806. func SupplierFindConnectionsHandle(sqlStr string, args ...interface{}) []SupplierConnectionsEntity {
  807. returnData := []SupplierConnectionsEntity{}
  808. rows, err := ClickhouseConn.Query(context.Background(), sqlStr, args...)
  809. if err != nil {
  810. logx.Error("查询失败", sqlStr, err)
  811. }
  812. for rows.Next() {
  813. data := SupplierConnectionsEntity{}
  814. err = rows.ScanStruct(&data)
  815. if err != nil {
  816. logx.Error(err)
  817. }
  818. returnData = append(returnData, data)
  819. }
  820. return returnData
  821. }
  822. // 合作时间查询
  823. func TimeFindConnectionsHandle(sqlStr string) []TimeConnectionsEntity {
  824. returnData := []TimeConnectionsEntity{}
  825. rows, err := ClickhouseConn.Query(context.Background(), sqlStr)
  826. if err != nil {
  827. logx.Error("查询失败", sqlStr, err)
  828. }
  829. for rows.Next() {
  830. data := TimeConnectionsEntity{}
  831. rows.ScanStruct(&data)
  832. returnData = append(returnData, data)
  833. }
  834. return returnData
  835. }
  836. // 去重处理
  837. func Deduplication(a, b string) string {
  838. newArr := []string{}
  839. if b == "全国" {
  840. return a
  841. }
  842. if a != "" {
  843. newArr = append(newArr, a)
  844. }
  845. if b != "" {
  846. newArr = append(newArr, b)
  847. }
  848. return strings.Join(newArr, ",")
  849. }
  850. // 路径列表
  851. func (t *OwnerService) OwnerRoute() []map[string]interface{} {
  852. if t.BuyerId == "" {
  853. return []map[string]interface{}{}
  854. }
  855. routeList := ConnectionsHandle(t.PositionId, []string{t.BuyerId})
  856. bps := []BuyerProject{
  857. BuyerProject{
  858. Project: ProjectEntity{
  859. Connections: routeList,
  860. },
  861. },
  862. }
  863. PersonFindConnectionsHandle(t.PositionId, bps, -1)
  864. for i, routeMap := range routeList {
  865. sourceType := gconv.String(routeMap["sourceType"])
  866. if sourceType == "agency" || sourceType == "supplier" {
  867. data := routeList[i]
  868. data["cooperateCount"] = len(gconv.Maps(data["list"]))
  869. delete(data, "list")
  870. routeList[i] = data
  871. }
  872. }
  873. return routeList
  874. }
  875. // 合作列表
  876. func (t *OwnerService) OwnerCooperate() []map[string]interface{} {
  877. returData := []map[string]interface{}{}
  878. dataArr := []TimeConnectionsEntity{}
  879. if t.CooperateType == "supplier" {
  880. //供应商
  881. supplierSql := fmt.Sprintf(`SELECT
  882. zbtime,
  883. project_id,
  884. project_name
  885. FROM
  886. transaction_info_all
  887. ARRAY
  888. JOIN winner_id as winnerId
  889. prewhere buyer_id= '%s' and winnerId='%s' order by zbtime DESC,project_id DESC `, t.BuyerId, t.WinnerId)
  890. dataArr = TimeFindConnectionsHandle(supplierSql)
  891. } else if t.CooperateType == "agency" {
  892. //代理机构
  893. agentSql := fmt.Sprintf(`select zbtime,project_id,project_name from transaction_info_all prewhere buyer_id ='%s' and agency_id ='%s' order by zbtime DESC,project_id DESC `, t.BuyerId, t.WinnerId)
  894. dataArr = TimeFindConnectionsHandle(agentSql)
  895. }
  896. if dataArr != nil && len(dataArr) > 0 {
  897. for _, m := range dataArr {
  898. zbtime := m.Zbtime
  899. returData = append(returData, map[string]interface{}{
  900. "zbtime": common.If(zbtime == 0, "", time.Unix(zbtime, 10).Format("2006.01.02")),
  901. "entName": t.WinnerName,
  902. "projectId": encrypt.EncodeArticleId2ByCheck(m.Project_id),
  903. "projectName": m.Project_name,
  904. })
  905. }
  906. }
  907. return returData
  908. }
  909. // 物业业务类型查询
  910. func FindBusiness(endId int64, userId string) string {
  911. businessStr := ""
  912. if endId != 0 {
  913. //企业
  914. entInfo := JianyuMysql.FindOne("entniche_info", map[string]interface{}{
  915. "id": endId,
  916. }, "", "")
  917. if (*entInfo)["identity_info"] != nil {
  918. entMap := gconv.Map((*entInfo)["identity_info"])
  919. businessStr = gconv.String(entMap["business"])
  920. }
  921. } else {
  922. //个人
  923. user, ok := Mgo.FindById("user", userId, "")
  924. if ok && user != nil && len(*user) > 0 {
  925. if _, ok1 := (*user)["identity_info"]; !ok1 {
  926. return ""
  927. }
  928. identityInfo := gconv.Map((*user)["identity_info"])
  929. if _, ok1 := identityInfo["is_init"]; !ok1 {
  930. return ""
  931. }
  932. if !gconv.Bool(identityInfo["is_init"]) {
  933. //设置过
  934. businessStr = gconv.String(identityInfo["ent_businessType"])
  935. }
  936. }
  937. }
  938. return businessStr
  939. }