owner.go 33 KB

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