owner.go 30 KB

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