owner.go 32 KB

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