owner.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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,winner_id,winner,agency_id,agency from transaction_info_all prewhere buyer_id in (` + wh1 + `)`
  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 (len(m.Winner_id) == 0 || len(m.Winner_id) != len(m.Winner)) && m.Agency_id == "" {
  226. continue
  227. }
  228. projectId := encrypt.EncodeArticleId2ByCheck(m.Project_id)
  229. projectName := m.Project_name
  230. zbtime := m.Zbtime
  231. if len(m.Winner_id) == len(m.Winner) {
  232. for k, v := range m.Winner_id {
  233. key := fmt.Sprintf("%s_%s", m.Buyer_id, v)
  234. if _, ok := winnerMap[key]; ok {
  235. data := winnerMap[key]
  236. data["count"] = gconv.Int64(data["count"]) + 1
  237. dataList := gconv.Maps(data["list"])
  238. dataList = append(dataList, map[string]interface{}{
  239. "zbtime": zbtime,
  240. "projectId": projectId,
  241. "projectName": projectName,
  242. })
  243. data["list"] = dataList
  244. data["zbtime"] = zbtime
  245. winnerMap[key] = data
  246. } else {
  247. winnerMap[key] = map[string]interface{}{
  248. "b_id": v,
  249. "b_name": m.Winner[k],
  250. "a_name": m.Buyer,
  251. "a_id": m.Buyer_id,
  252. "sourceType": "supplier",
  253. "zbtime": zbtime,
  254. "count": 1,
  255. "list": []map[string]interface{}{
  256. {
  257. "zbtime": zbtime,
  258. "entName": m.Winner[k],
  259. "projectId": projectId,
  260. "projectName": projectName,
  261. },
  262. },
  263. }
  264. }
  265. }
  266. }
  267. if m.Agency_id != "" {
  268. key := fmt.Sprintf("%s_%s", m.Buyer_id, m.Agency_id)
  269. if _, ok := agencyIdMap[key]; ok {
  270. data := agencyMap[key]
  271. data["count"] = gconv.Int64(data["count"]) + 1
  272. dataList := gconv.Maps(data["list"])
  273. dataList = append(dataList, map[string]interface{}{
  274. "zbtime": zbtime,
  275. "projectId": projectId,
  276. "projectName": projectName,
  277. })
  278. data["list"] = dataList
  279. data["zbtime"] = zbtime
  280. agencyMap[key] = data
  281. } else {
  282. agencyIdMap[key] = true
  283. agencyMap[key] = map[string]interface{}{
  284. "b_id": m.Agency_id,
  285. "b_name": m.Agency,
  286. "a_name": m.Buyer,
  287. "a_id": m.Buyer_id,
  288. "sourceType": "agency",
  289. "count": 1,
  290. "zbtime": zbtime,
  291. "list": []map[string]interface{}{
  292. {
  293. "zbtime": zbtime,
  294. "projectId": projectId,
  295. "projectName": projectName,
  296. },
  297. },
  298. }
  299. }
  300. }
  301. }
  302. for _, m := range winnerMap {
  303. returnData = append(returnData, map[string]interface{}{
  304. "b_id": gconv.String(m["b_id"]),
  305. "b_name": gconv.String(m["b_name"]),
  306. "a_name": gconv.String(m["a_name"]),
  307. "a_id": gconv.String(m["a_id"]),
  308. "sourceType": gconv.String(m["sourceType"]),
  309. "relationship": gconv.String(m["relationship"]),
  310. "count": gconv.Int64(m["count"]),
  311. "personName": gconv.String(m["personName"]),
  312. "list": m["list"],
  313. "zbtime": m["zbtime"],
  314. })
  315. }
  316. for _, m := range agencyMap {
  317. returnData = append(returnData, map[string]interface{}{
  318. "b_id": gconv.String(m["b_id"]),
  319. "b_name": gconv.String(m["b_name"]),
  320. "a_name": gconv.String(m["a_name"]),
  321. "a_id": gconv.String(m["a_id"]),
  322. "sourceType": gconv.String(m["sourceType"]),
  323. "relationship": gconv.String(m["relationship"]),
  324. "personName": gconv.String(m["personName"]),
  325. "count": gconv.Int64(m["count"]),
  326. "list": m["list"],
  327. "zbtime": m["zbtime"],
  328. })
  329. }
  330. sort.Slice(returnData, func(i, j int) bool {
  331. aa := fmt.Sprintf("%s%s", gconv.String(returnData[i]["zbtime"]), gconv.String(returnData[i]["b_id"]))
  332. bb := fmt.Sprintf("%s%s", gconv.String(returnData[j]["zbtime"]), gconv.String(returnData[j]["b_id"]))
  333. return aa > bb
  334. })
  335. return returnData
  336. }
  337. // 中间人查询
  338. func FindMiddleman(positionId int64, buyerArr []string, returnData []map[string]interface{}) {
  339. if len(buyerArr) == 0 {
  340. return
  341. }
  342. //中间人 作为可介绍业主 企业名称
  343. wh, args := common.WhArgs(buyerArr)
  344. newArgs := []interface{}{positionId}
  345. newArgs = append(newArgs, args...)
  346. 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...)
  347. for _, v := range *companyArr {
  348. companyId := gconv.String(v["company_id"])
  349. companyName := gconv.String(v["company_name"])
  350. relateName := gconv.String(v["relate_name"])
  351. relateId := gconv.String(v["relate_id"])
  352. returnData = append(returnData, map[string]interface{}{
  353. "b_id": companyId,
  354. "b_name": companyName,
  355. "a_name": relateName,
  356. "a_id": relateId,
  357. "sourceType": "middleman",
  358. "relationship": "业主的关系人",
  359. "personName": gconv.String(v["contact_person"]),
  360. })
  361. }
  362. return
  363. }
  364. // 企业之间关系查询
  365. func Findfirstparty(positionId int64, buyerArr []string, returnData []map[string]interface{}) {
  366. if len(buyerArr) == 0 {
  367. return
  368. }
  369. wh1, args1 := common.WhArgs(buyerArr)
  370. args1 = append(args1, args1...)
  371. buyerSql := `select DISTINCT
  372. a.a_id as a_id,
  373. a.b_id as b_id,
  374. a.a_name as a_name,
  375. a.b_name as b_name,
  376. 111 as status,
  377. a.code as code
  378. from
  379. ent_map_code a
  380. prewhere
  381. a.a_id in (` + wh1 + `)
  382. and a.code in('0101', '0201')
  383. UNION ALL
  384. select
  385. a.b_id as a_id,
  386. a.a_id as b_id,
  387. a.b_name as a_name,
  388. a.a_name as b_name,
  389. 222 as status,
  390. a.code as code
  391. from
  392. ent_map_code a
  393. prewhere
  394. a.b_id in (` + wh1 + `)
  395. and a.code in('0101', '0201')`
  396. relationshipArr := BuyerFindConnectionsHandle(buyerSql, args1...)
  397. if relationshipArr == nil || len(relationshipArr) == 0 {
  398. return
  399. }
  400. for _, v := range relationshipArr {
  401. code := v.Code
  402. status := v.Status
  403. if gconv.String(status) == "111" {
  404. //key := fmt.Sprintf("%s_%s", a_id, b_id)
  405. switch code {
  406. case "0101": //管辖关系
  407. returnData = append(returnData, map[string]interface{}{
  408. "b_id": v.Bid,
  409. "b_name": v.Bname,
  410. "a_name": v.Aname,
  411. "a_id": v.Aid,
  412. "sourceType": "firstparty",
  413. "relationship": "业主的下级机构",
  414. })
  415. case "0201": //投资关系
  416. returnData = append(returnData, map[string]interface{}{
  417. "b_id": v.Bid,
  418. "b_name": v.Bname,
  419. "a_name": v.Aname,
  420. "a_id": v.Aid,
  421. "sourceType": "firstparty",
  422. "relationship": "业主的股东",
  423. })
  424. }
  425. }
  426. if gconv.String(status) == "222" {
  427. //key := fmt.Sprintf("%s_%s", b_id, a_id)
  428. if code == "0101" {
  429. //"0101":管辖关系
  430. returnData = append(returnData, map[string]interface{}{
  431. "b_id": v.Bid,
  432. "b_name": v.Bname,
  433. "a_name": v.Aname,
  434. "a_id": v.Aid,
  435. "sourceType": "firstparty",
  436. "relationship": "业主的上级机构",
  437. })
  438. }
  439. if code == "0201" {
  440. returnData = append(returnData, map[string]interface{}{
  441. "b_id": v.Bid,
  442. "b_name": v.Bname,
  443. "a_name": v.Aname,
  444. "a_id": v.Aid,
  445. "sourceType": "firstparty",
  446. "relationship": "业主的股东",
  447. })
  448. }
  449. }
  450. }
  451. return
  452. }
  453. // 采购单位和项目合并
  454. func BuyerProjectMerge(dataMap, projectMap *map[string]map[string]interface{}) []BuyerProject {
  455. returnData := []BuyerProject{}
  456. for buyerName, project := range *projectMap {
  457. buyerId := gconv.String(project["buyerId"])
  458. data := (*dataMap)[buyerId]
  459. returnData = append(returnData, BuyerProject{
  460. BuyerId: buyerId,
  461. BuyerName: buyerName,
  462. BuyerType: gconv.String(data["buyerType"]),
  463. Project: ProjectEntity{
  464. Number: gconv.Int64(project["count"]),
  465. EstimatedAmount: gconv.Int64(project["money"]),
  466. Connections: []map[string]interface{}{},
  467. },
  468. Area: gconv.String(project["area"]),
  469. Zbtime: gconv.Int64(project["area"]),
  470. IsMonitor: gconv.Bool(data["isMonitor"]),
  471. CId: gconv.String(data["cId"]),
  472. })
  473. }
  474. return returnData
  475. }
  476. func FindStatus(positionId int64) (map[string]bool, map[string]bool, map[string]bool) {
  477. //未处理
  478. untreatedMap := map[string]bool{}
  479. //已忽略
  480. ignoredMap := map[string]bool{}
  481. //已创建
  482. createdMap := map[string]bool{}
  483. processingArr := CrmMysql.Find(entity.CONNECTION_STATUS, map[string]interface{}{
  484. "itype": 1,
  485. "position_id": positionId,
  486. }, "relate_id,is_handle,is_ignore,is_create", "", -1, -1)
  487. if processingArr != nil && len(*processingArr) > 0 {
  488. for _, v := range *processingArr {
  489. entId := gconv.String(v["relate_id"])
  490. handle := gconv.Int64(v["is_handle"])
  491. ignore := gconv.Int64(v["is_ignore"])
  492. create := gconv.Int64(v["is_create"])
  493. if handle == 1 {
  494. untreatedMap[entId] = true
  495. }
  496. if ignore == 1 {
  497. ignoredMap[entId] = true
  498. }
  499. if create == 1 {
  500. createdMap[entId] = true
  501. }
  502. }
  503. }
  504. return untreatedMap, ignoredMap, createdMap
  505. }
  506. // 采购单位查询
  507. func BuyerList(partyA, intermediary string, positionId int64) *map[string]map[string]interface{} {
  508. dataMap := &map[string]map[string]interface{}{}
  509. //甲方
  510. if partyA != "" {
  511. for _, v := range strings.Split(partyA, ",") {
  512. (*dataMap)[v] = map[string]interface{}{
  513. "buyerType": "firstparty",
  514. }
  515. }
  516. // intermediaryArr := []string{}
  517. // for _, v := range strings.Split(partyA, ",") {
  518. // if v != "" {
  519. // intermediaryArr = append(intermediaryArr, fmt.Sprintf("'%s'", v))
  520. // }
  521. // }
  522. // if len(partyA) > 0 {
  523. // partyASql := fmt.Sprintf(`select id as buyer_id,company_name as buyer from ent_info where id in (%s)`, strings.Join(intermediaryArr, ","))
  524. // FindHandle(partyASql, dataMap, "firstparty")
  525. // }
  526. }
  527. //供应商 //同甲异业
  528. // findInSetArr := []string{}
  529. // if supplier != "" {
  530. // for _, v := range strings.Split(supplier, ",") {
  531. // if v != "" {
  532. // findInSetArr = append(findInSetArr, fmt.Sprintf("'%s'", v))
  533. // }
  534. // }
  535. // }
  536. // if len(findInSetArr) > 0 {
  537. // sqlStr := fmt.Sprintf(`SELECT buyer_id,buyer FROM transaction_info_all where hasAny(winner_id,[%s]) `, strings.Join(findInSetArr, ","))
  538. // FindHandle(sqlStr, dataMap, "supplier")
  539. // }
  540. //同甲异业
  541. // findheterotophyArr := []string{}
  542. // if heterotophy != "" {
  543. // for _, v := range strings.Split(heterotophy, ",") {
  544. // if v != "" {
  545. // findheterotophyArr = append(findheterotophyArr, fmt.Sprintf("'%s'", v))
  546. // }
  547. // }
  548. // }
  549. // if len(findheterotophyArr) > 0 {
  550. // sqlStr := fmt.Sprintf(`SELECT buyer_id,buyer FROM transaction_info_all where hasAny(winner_id,[%s]) `, strings.Join(findheterotophyArr, ","))
  551. // FindHandle(sqlStr, dataMap, "adiffb")
  552. // }
  553. //中间人
  554. if intermediary != "" {
  555. wh, args := common.WhArgs(strings.Split(intermediary, ","))
  556. args = append(args, positionId)
  557. 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...)
  558. if intermediaryArr != nil && len(*intermediaryArr) > 0 {
  559. for _, m := range *intermediaryArr {
  560. buyerId := gconv.String(m["relate_id"])
  561. buyerName := gconv.String(m["relate_name"])
  562. (*dataMap)[buyerId] = map[string]interface{}{
  563. "buyerName": buyerName,
  564. "buyerType": "middleman",
  565. "cId": gconv.String(m["id"]),
  566. }
  567. }
  568. }
  569. }
  570. //招标代理
  571. // if agency != "" {
  572. // agencyArr := []string{}
  573. // for _, s := range strings.Split(agency, ",") {
  574. // agencyArr = append(agencyArr, fmt.Sprintf("'%s'", s))
  575. // }
  576. // sqlStr := fmt.Sprintf(`SELECT buyer_id,buyer FROM transaction_info_all where agency_id in (%s) `, strings.Join(agencyArr, ","))
  577. // FindHandle(sqlStr, dataMap, "agency")
  578. // }
  579. return dataMap
  580. }
  581. // 项目数量查
  582. func (t *OwnerService) ProjectHandle(buyerArr []string, businessStr string, monitorBuyers []string) (*map[string]map[string]interface{}, int64) {
  583. projectMap := &map[string]map[string]interface{}{}
  584. startIndex := (t.PageIndex - 1) * t.PageSize
  585. whBs, allArgs := common.WhArgs(strings.Split(businessStr, ","))
  586. allArgs = append(allArgs, allArgs...)
  587. sqlStr := `select buyer,buyer_id,groupUniqArray(area) as areaStr,count(if(project_bidstatus>1 and hasAny(topscopeclass,[`
  588. sqlStr += whBs + `])=1,1,null)) as ocount,SUM(if(project_bidstatus>1 and hasAny(topscopeclass,[`
  589. sqlStr += whBs + `])=1,project_money,0)) as project_money,MAX(zbtime) as maxzbtime from transaction_info_all`
  590. ors1 := []string{}
  591. if len(buyerArr) > 0 {
  592. wh, args := common.WhArgs(buyerArr)
  593. ors1 = append(ors1, `buyer_id in (`+wh+`)`)
  594. allArgs = append(allArgs, args...)
  595. }
  596. wm := map[string]bool{}
  597. winner_ids := []string{}
  598. if t.Supplier != "" {
  599. for _, v := range strings.Split(t.Supplier, ",") {
  600. if wm[v] {
  601. continue
  602. }
  603. winner_ids = append(winner_ids, v)
  604. wm[v] = true
  605. }
  606. }
  607. if t.Heterotophy != "" {
  608. for _, v := range strings.Split(t.Heterotophy, ",") {
  609. if wm[v] {
  610. continue
  611. }
  612. winner_ids = append(winner_ids, v)
  613. wm[v] = true
  614. }
  615. }
  616. ors2 := []string{}
  617. if len(winner_ids) > 0 {
  618. wh, args := common.WhArgs(winner_ids)
  619. ors2 = append(ors2, `hasAny(winner_id,[`+wh+`])`)
  620. allArgs = append(allArgs, args...)
  621. }
  622. if t.Agency != "" {
  623. wh, args := common.WhArgs(strings.Split(t.Agency, ","))
  624. ors2 = append(ors2, `agency_id in (`+wh+`)`)
  625. allArgs = append(allArgs, args...)
  626. }
  627. if len(ors2) > 0 {
  628. ors1 = append(ors1, `(buyer_id in (select DISTINCT buyer_id from transaction_info_all prewhere (`+strings.Join(ors2, " or ")+`) and buyer_id<>''))`)
  629. }
  630. allArgs = append(allArgs, NetworkCom.ProjectYearLimit())
  631. ands := []string{}
  632. if len(monitorBuyers) > 0 {
  633. wh, args := common.WhArgs(monitorBuyers)
  634. ands = append(ands, `buyer in (`+wh+`)`)
  635. allArgs = append(allArgs, args...)
  636. }
  637. if t.Area != "" {
  638. wh, args := common.WhArgs(strings.Split(t.Area, ","))
  639. ands = append(ands, `area in (`+wh+`)`)
  640. allArgs = append(allArgs, args...)
  641. }
  642. sqlStr += " prewhere (" + strings.Join(ors1, " or ") + ") and zbtime>?"
  643. if len(ands) > 0 {
  644. sqlStr += " and " + strings.Join(ands, " and ")
  645. }
  646. sqlStr += " GROUP by buyer,buyer_id"
  647. if t.SourceType == "1" {
  648. sqlStr += " HAVING ocount>2 "
  649. }
  650. countSql := fmt.Sprintf("select count(1) as count from (%s) b ", sqlStr)
  651. sqlStr += fmt.Sprintf(" order by maxzbtime desc limit %d,%d", startIndex, t.PageSize)
  652. logx.Info(t.PositionId, " ProjectHandle sql ", sqlStr, allArgs)
  653. //总数查询
  654. ass := []BuyerAggStruct{}
  655. rows, err1 := ClickhouseConn.Query(context.TODO(), sqlStr, allArgs...)
  656. if err1 != nil {
  657. logx.Error(err1)
  658. return projectMap, 0
  659. }
  660. defer rows.Close()
  661. for rows.Next() {
  662. as := BuyerAggStruct{}
  663. if err := rows.ScanStruct(&as); err != nil {
  664. logx.Error(err)
  665. continue
  666. }
  667. ass = append(ass, as)
  668. }
  669. for _, object := range ass {
  670. buyerName := object.Buyer
  671. buyerId := object.BuyerId
  672. projectMoney, _ := object.ProjectMoney.Float64()
  673. (*projectMap)[buyerName] = map[string]interface{}{
  674. "area": strings.Join(object.Area, ","),
  675. "zbtime": object.MaxZbtime,
  676. "money": common.RetainDecimal(projectMoney/10000, 2),
  677. "count": object.Ocount,
  678. "buyerId": buyerId,
  679. "buyerName": buyerName,
  680. }
  681. }
  682. logx.Info(t.PositionId, " ProjectHandle sql over 。。。")
  683. count := T.NetworkCom.Count(countSql, allArgs...)
  684. logx.Info(t.PositionId, " ProjectHandle count over 。。。")
  685. return projectMap, count
  686. }
  687. type BuyerAggStruct struct {
  688. Buyer string `ch:"buyer"`
  689. BuyerId string `ch:"buyer_id"`
  690. Area []string `ch:"areaStr"`
  691. ProjectMoney decimal.Decimal `ch:"project_money"`
  692. MaxZbtime int64 `ch:"maxzbtime"`
  693. Ocount uint64 `ch:"ocount"`
  694. }
  695. // 采购单位查询sql
  696. func FindHandle(sqlStr string, dataMap *map[string]map[string]interface{}, buyerType string) {
  697. rows, err := ClickhouseConn.Query(context.Background(), sqlStr)
  698. if err != nil {
  699. logx.Error("查询失败", sqlStr, err)
  700. }
  701. for rows.Next() {
  702. data := Recommend{}
  703. rows.ScanStruct(&data)
  704. if data.BuyerId != "" {
  705. (*dataMap)[data.BuyerId] = map[string]interface{}{
  706. "buyerName": data.Buyer,
  707. "buyerType": buyerType,
  708. }
  709. }
  710. }
  711. return
  712. }
  713. type ConnectionsEntity struct {
  714. Aid string `ch:"a_id"`
  715. Bid string `ch:"b_id"`
  716. Aname string `ch:"a_name"`
  717. Bname string `ch:"b_name"`
  718. Status uint8 `ch:"status"`
  719. Code string `ch:"code"`
  720. Cperson string `ch:"c_person"`
  721. }
  722. type PersonEntity struct {
  723. Id string `ch:"id"`
  724. PersonName string `ch:"personName"`
  725. }
  726. type SupplierConnectionsEntity struct {
  727. Zbtime int64 `ch:"zbtime"`
  728. Project_id string `ch:"project_id"`
  729. Project_name string `ch:"project_name"`
  730. Buyer_id string `ch:"buyer_id"`
  731. Buyer string `ch:"buyer"`
  732. Winner_id []string `ch:"winner_id"`
  733. Winner []string `ch:"winner"`
  734. Agency_id string `ch:"agency_id"`
  735. Agency string `ch:"agency"`
  736. }
  737. type TimeConnectionsEntity struct {
  738. Zbtime int64 `ch:"zbtime"`
  739. Project_id string `ch:"project_id"`
  740. Project_name string `ch:"project_name"`
  741. }
  742. // 采购单位人脉信息查询sql
  743. func BuyerFindConnectionsHandle(sqlStr string, args ...interface{}) []ConnectionsEntity {
  744. returnData := []ConnectionsEntity{}
  745. rows, err := ClickhouseConn.Query(context.Background(), sqlStr, args...)
  746. if err != nil {
  747. logx.Error("查询失败", sqlStr, err)
  748. }
  749. for rows.Next() {
  750. data := ConnectionsEntity{}
  751. err := rows.ScanStruct(&data)
  752. logx.Info(err)
  753. returnData = append(returnData, data)
  754. }
  755. return returnData
  756. }
  757. func PersonFindConnectionsHandle(positionId int64, bps []BuyerProject, contactCount int) {
  758. if contactCount == 0 {
  759. return
  760. }
  761. //企业联系人处理
  762. entIdArr := []string{}
  763. entIdMap := map[string]bool{}
  764. for _, v := range bps {
  765. for kk, vv := range v.Project.Connections {
  766. b_id, _ := vv["b_id"].(string)
  767. if b_id == "" || entIdMap[b_id] {
  768. continue
  769. }
  770. entIdMap[b_id] = true
  771. entIdArr = append(entIdArr, b_id)
  772. if kk == contactCount-1 {
  773. break
  774. }
  775. }
  776. }
  777. personMap := map[string]string{}
  778. if len(entIdArr) > 0 {
  779. wh2, args2 := common.WhArgs(entIdArr)
  780. personSql := `select id,name as personName from ent_contact prewhere id in (` + wh2 + `) ORDER by name`
  781. logx.Info(positionId, " Findwinner 联系人 sql ", personSql, args2)
  782. pes := []PersonEntity{}
  783. rows, err := ClickhouseConn.Query(context.Background(), personSql, args2...)
  784. if err != nil {
  785. logx.Error("查询失败", personSql, err)
  786. }
  787. for rows.Next() {
  788. data := PersonEntity{}
  789. rows.ScanStruct(&data)
  790. pes = append(pes, data)
  791. }
  792. //联系人处理
  793. for _, v := range pes {
  794. personMap[v.Id] = v.PersonName
  795. }
  796. }
  797. for _, v := range bps {
  798. for kk, vv := range v.Project.Connections {
  799. b_id, _ := vv["b_id"].(string)
  800. vv["personName"] = personMap[b_id]
  801. if kk == contactCount-1 {
  802. break
  803. }
  804. }
  805. }
  806. }
  807. // 供应商
  808. func SupplierFindConnectionsHandle(sqlStr string, args ...interface{}) []SupplierConnectionsEntity {
  809. returnData := []SupplierConnectionsEntity{}
  810. rows, err := ClickhouseConn.Query(context.Background(), sqlStr, args...)
  811. if err != nil {
  812. logx.Error("查询失败", sqlStr, err)
  813. }
  814. for rows.Next() {
  815. data := SupplierConnectionsEntity{}
  816. err = rows.ScanStruct(&data)
  817. if err != nil {
  818. logx.Error(err)
  819. }
  820. returnData = append(returnData, data)
  821. }
  822. return returnData
  823. }
  824. // 合作时间查询
  825. func TimeFindConnectionsHandle(sqlStr string) []TimeConnectionsEntity {
  826. returnData := []TimeConnectionsEntity{}
  827. rows, err := ClickhouseConn.Query(context.Background(), sqlStr)
  828. if err != nil {
  829. logx.Error("查询失败", sqlStr, err)
  830. }
  831. for rows.Next() {
  832. data := TimeConnectionsEntity{}
  833. rows.ScanStruct(&data)
  834. returnData = append(returnData, data)
  835. }
  836. return returnData
  837. }
  838. // 去重处理
  839. func Deduplication(a, b string) string {
  840. newArr := []string{}
  841. if b == "全国" {
  842. return a
  843. }
  844. if a != "" {
  845. newArr = append(newArr, a)
  846. }
  847. if b != "" {
  848. newArr = append(newArr, b)
  849. }
  850. return strings.Join(newArr, ",")
  851. }
  852. // 路径列表
  853. func (t *OwnerService) OwnerRoute() []map[string]interface{} {
  854. if t.BuyerId == "" {
  855. return []map[string]interface{}{}
  856. }
  857. routeList := ConnectionsHandle(t.PositionId, []string{t.BuyerId})
  858. bps := []BuyerProject{
  859. BuyerProject{
  860. Project: ProjectEntity{
  861. Connections: routeList,
  862. },
  863. },
  864. }
  865. PersonFindConnectionsHandle(t.PositionId, bps, -1)
  866. for i, routeMap := range routeList {
  867. sourceType := gconv.String(routeMap["sourceType"])
  868. if sourceType == "agency" || sourceType == "supplier" {
  869. data := routeList[i]
  870. data["cooperateCount"] = len(gconv.Maps(data["list"]))
  871. delete(data, "list")
  872. routeList[i] = data
  873. }
  874. }
  875. return routeList
  876. }
  877. // 合作列表
  878. func (t *OwnerService) OwnerCooperate() []map[string]interface{} {
  879. returData := []map[string]interface{}{}
  880. dataArr := []TimeConnectionsEntity{}
  881. if t.CooperateType == "supplier" {
  882. //供应商
  883. supplierSql := fmt.Sprintf(`SELECT
  884. zbtime,
  885. project_id,
  886. project_name
  887. FROM
  888. transaction_info_all
  889. ARRAY
  890. JOIN winner_id as winnerId
  891. prewhere buyer_id= '%s' and winnerId='%s' order by zbtime DESC,project_id DESC `, t.BuyerId, t.WinnerId)
  892. dataArr = TimeFindConnectionsHandle(supplierSql)
  893. } else if t.CooperateType == "agency" {
  894. //代理机构
  895. 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)
  896. dataArr = TimeFindConnectionsHandle(agentSql)
  897. }
  898. if dataArr != nil && len(dataArr) > 0 {
  899. for _, m := range dataArr {
  900. zbtime := m.Zbtime
  901. returData = append(returData, map[string]interface{}{
  902. "zbtime": common.If(zbtime == 0, "", time.Unix(zbtime, 10).Format("2006.01.02")),
  903. "entName": t.WinnerName,
  904. "projectId": encrypt.EncodeArticleId2ByCheck(m.Project_id),
  905. "projectName": m.Project_name,
  906. })
  907. }
  908. }
  909. return returData
  910. }
  911. // 物业业务类型查询
  912. func FindBusiness(endId int64, userId string) string {
  913. businessStr := ""
  914. if endId != 0 {
  915. //企业
  916. entInfo := JianyuMysql.FindOne("entniche_info", map[string]interface{}{
  917. "id": endId,
  918. }, "", "")
  919. if (*entInfo)["identity_info"] != nil {
  920. entMap := gconv.Map((*entInfo)["identity_info"])
  921. businessStr = gconv.String(entMap["business"])
  922. }
  923. } else {
  924. //个人
  925. user, ok := Mgo.FindById("user", userId, "")
  926. if ok && user != nil && len(*user) > 0 {
  927. if _, ok1 := (*user)["identity_info"]; !ok1 {
  928. return ""
  929. }
  930. identityInfo := gconv.Map((*user)["identity_info"])
  931. if _, ok1 := identityInfo["is_init"]; !ok1 {
  932. return ""
  933. }
  934. if !gconv.Bool(identityInfo["is_init"]) {
  935. //设置过
  936. businessStr = gconv.String(identityInfo["ent_businessType"])
  937. }
  938. }
  939. }
  940. return businessStr
  941. }