owner.go 30 KB

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