owner.go 33 KB

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