owner.go 31 KB

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