owner.go 30 KB

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