owner.go 31 KB

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