12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289 |
- package service
- import (
- "context"
- "encoding/json"
- "fmt"
- "sort"
- "strings"
- "sync"
- "time"
- elastic "app.yhyue.com/moapp/jybase/es"
- "app.yhyue.com/moapp/jybase/encrypt"
- "app.yhyue.com/moapp/jybase/common"
- . "bp.jydev.jianyu360.cn/CRM/application/api/common"
- "bp.jydev.jianyu360.cn/CRM/application/entity"
- "github.com/gogf/gf/v2/util/gconv"
- "github.com/shopspring/decimal"
- "github.com/zeromicro/go-zero/core/logx"
- )
- const (
- EntINDEX = "ent_info"
- EntTYPE = "ent_info"
- )
- type OwnerService struct {
- PartyA string
- Supplier string
- Heterotophy string
- Intermediary string
- Agency string
- SearchEntName string
- SourceType string
- ProcessingStatus string
- Area string
- PositionId int64
- PageIndex int64
- PageSize int64
- BuyerId string
- BuyerName string
- WinnerId string
- WinnerName string
- CooperateType string
- EntAccountId int64
- ProjectType string
- Type string
- }
- type BuyerProject struct {
- BuyerId string
- BuyerName string
- Project ProjectEntity
- IsMonitor bool
- IsCreateCustomer bool
- IsIgnore bool
- Area string
- Zbtime int64
- BuyerType string
- CId string
- }
- type ProjectEntity struct {
- Number int64
- zbtime int64
- EstimatedAmount int64
- Connections []map[string]interface{}
- }
- type Recommend struct {
- BuyerId string `ch:"buyer_id"`
- Buyer string `ch:"buyer"`
- }
- type Project struct {
- BuyerId string `ch:"buyer_id"`
- Area string `ch:"area"`
- GroupCount uint64 `ch:"group_count"`
- Zbtime int64 `ch:"zbtime"`
- Money decimal.Decimal `ch:"money"`
- }
- func (t *OwnerService) OwnerlList() map[string]interface{} {
- //先查询采购单位列表
- startTime := time.Now().Unix()
- dataMap := &map[string]map[string]interface{}{}
- projectMap := &map[string]map[string]interface{}{}
- if t.PartyA != "" || t.Supplier != "" || t.Heterotophy != "" || t.Intermediary != "" || t.Agency != "" {
- dataMap = BuyerList(t.PartyA, t.Supplier, t.Heterotophy, t.Intermediary, t.Agency, t.PositionId)
- if len(*dataMap) == 0 {
- return map[string]interface{}{
- "connectionsNumber": 0,
- "highSuccessNumber": 0,
- "monitorNumber": 0,
- "list": []BuyerProject{},
- }
- }
- //处理状态初始化
- ProcessingStatusInit(t.PositionId, dataMap, t.ProcessingStatus)
- //监控状态处理
- MonitorStatusInit(t.PositionId, dataMap, t.SourceType)
- //项目数量查询
- buyerArr := []string{}
- for _, value := range *dataMap {
- buyerArr = append(buyerArr, fmt.Sprintf(`"%s"`, gconv.String(value["buyerName"])))
- }
- //项目数量处理
- projectMap, _, dataMap = ProjectHandle(buyerArr, t.EntAccountId, t.SearchEntName, t.Area, t.ProjectType, dataMap)
- } else if t.SearchEntName != "" {
- //1 只看转介绍成功率高2只看已监控的
- //先查找采购单位数据
- projectMap, dataMap, _ = ProjectHandle([]string{}, t.EntAccountId, t.SearchEntName, t.Area, t.ProjectType, dataMap)
- a7 := time.Now().Unix()
- fmt.Println("es用时", a7-startTime)
- ProcessingStatusInit(t.PositionId, dataMap, t.ProcessingStatus)
- a8 := time.Now().Unix()
- fmt.Println("状态用时", a8-a7)
- //监控状态处理
- MonitorStatusInit(t.PositionId, dataMap, t.SourceType)
- a9 := time.Now().Unix()
- fmt.Println("监控用时", a9-a8)
- }
- endTime := time.Now().Unix()
- fmt.Println("用时时间:", endTime-startTime)
- if len(*dataMap) == 0 {
- return map[string]interface{}{}
- }
- //采购单位和项目合并
- a1 := time.Now().Unix()
- returnData, connectionsNumber, highSuccessNumber, monitorNumber := BuyerProjectMerge(dataMap, projectMap, t.SourceType)
- a2 := time.Now().Unix()
- fmt.Println("组合数据", a2-a1)
- //数组排序
- //分页数据处理
- if t.PageSize == 0 {
- t.PageSize = 10
- }
- if t.PageIndex == 0 {
- t.PageIndex = 1
- }
- startIndex := (t.PageIndex - 1) * t.PageSize
- endIndex := t.PageIndex * t.PageSize
- sort.Slice(returnData, func(i, j int) bool {
- aa := fmt.Sprintf("%d%s", returnData[i].Zbtime, returnData[i].BuyerId)
- bb := fmt.Sprintf("%d%s", returnData[j].Zbtime, returnData[j].BuyerId)
- return aa > bb
- })
- if startIndex < gconv.Int64(len(returnData)) {
- if endIndex > gconv.Int64(len(returnData)) {
- endIndex = gconv.Int64(len(returnData))
- }
- returnData = returnData[startIndex:endIndex]
- } else {
- return map[string]interface{}{}
- }
- buyerIdArr := []string{}
- for _, value := range returnData {
- if value.BuyerId != "" {
- buyerIdArr = append(buyerIdArr, fmt.Sprintf("'%s'", value.BuyerId))
- }
- }
- //可介绍业主人脉处理
- a3 := time.Now().Unix()
- routeList := ConnectionsHandle(buyerIdArr, t.PositionId, false)
- a4 := time.Now().Unix()
- fmt.Println("组合数1111据", a4-a3)
- for _, v := range routeList {
- buyerId := gconv.String(v["a_id"])
- for i, v1 := range returnData {
- aBuyerId := v1.BuyerId
- if buyerId == aBuyerId {
- //组装数据
- returnData[i].Project.Connections = append(returnData[i].Project.Connections, v)
- }
- }
- }
- //返回数据组装
- return map[string]interface{}{
- "connectionsNumber": connectionsNumber,
- "highSuccessNumber": highSuccessNumber,
- "monitorNumber": monitorNumber,
- "list": returnData,
- }
- }
- // 可介绍业主人脉列表
- func ConnectionsHandle(buyerArr []string, positionId int64, isAll bool) []map[string]interface{} {
- returnData := []map[string]interface{}{}
- a1 := time.Now().Unix()
- //中间人
- returnData = FindMiddleman(buyerArr, positionId, returnData)
- a2 := time.Now().Unix()
- fmt.Println("中间人", a2-a1)
- if isAll && len(returnData) > 0 {
- return returnData
- }
- //采购单位 投资关系 管辖关系
- //采购单位
- a3 := time.Now().Unix()
- returnData = Findfirstparty(buyerArr, returnData)
- a4 := time.Now().Unix()
- fmt.Println("采购单位", a4-a3)
- if isAll && len(returnData) > 0 {
- return returnData
- }
- a5 := time.Now().Unix()
- returnData = append(returnData, Findwinner(buyerArr)...)
- a6 := time.Now().Unix()
- logx.Info("供应商", a6-a5)
- return returnData
- }
- // 供应商处理
- func Findwinner(buyerArr []string) []map[string]interface{} {
- returnData := []map[string]interface{}{}
- if len(buyerArr) == 0 {
- return returnData
- }
- //供应商 采购单位 供应商 招标代理机构 采购单位 招标代理机构 需要计算合作次数
- winnerSql := fmt.Sprintf(`select * from (select
- zbtime,
- project_id,
- project_name,
- buyer_id,
- buyer,
- entId,
- 'supplier' as entType
- from
- transaction_info ARRAY
- JOIN winner_id as entId
- where
- buyer_id in (%s)
- UNION ALL
- select
- zbtime,
- project_id,
- project_name,
- buyer_id,
- buyer,
- agency_id as entId,
- 'agent' as entType
- from
- transaction_info
- where
- buyer_id in (%s) and agency_id!='') order by zbtime DESC,project_id DESC `, strings.Join(buyerArr, ","), strings.Join(buyerArr, ","))
- winnerArr := SupplierFindConnectionsHandle(winnerSql)
- if winnerArr != nil && len(winnerArr) > 0 {
- //企业联系人处理
- entIdArr := []string{}
- for _, v := range winnerArr {
- if v.EntId != "" {
- entIdArr = append(entIdArr, fmt.Sprintf("'%s'", v.EntId))
- }
- }
- personMap := map[string]string{}
- entNameMap := map[string]string{}
- if len(entIdArr) > 0 {
- personSql := fmt.Sprintf(`select id,name as personName from ent_contact where id in (%s) ORDER by name`, strings.Join(entIdArr, ","))
- personArr := PersonFindConnectionsHandle(personSql)
- //联系人处理
- for _, v := range personArr {
- personMap[v.Id] = v.PersonName
- }
- entSql := fmt.Sprintf(`select id ,company_name as personName from ent_info where id in (%s) ORDER by company_name`, strings.Join(entIdArr, ","))
- entNameArr := PersonFindConnectionsHandle(entSql)
- for _, v := range entNameArr {
- entNameMap[v.Id] = v.PersonName
- }
- }
- winnerMap := map[string]map[string]interface{}{}
- agencyMap := map[string]map[string]interface{}{}
- agencyIdMap := map[string]bool{}
- for _, m := range winnerArr {
- if m.EntId == "" {
- continue
- }
- projectId := encrypt.EncodeArticleId2ByCheck(m.Project_id)
- projectName := m.Project_name
- zbtime := m.Zbtime
- key := fmt.Sprintf("%s_%s", m.Buyer_id, m.EntId)
- if m.EntType == "supplier" {
- buyerId := m.Buyer_id
- winner := entNameMap[m.EntId]
- buyer := m.Buyer
- if _, ok := winnerMap[key]; ok {
- data := winnerMap[key]
- data["count"] = gconv.Int64(data["count"]) + 1
- dataList := gconv.Maps(data["list"])
- dataList = append(dataList, map[string]interface{}{
- "zbtime": zbtime,
- "projectId": projectId,
- "projectName": projectName,
- })
- data["list"] = dataList
- data["zbtime"] = zbtime
- winnerMap[key] = data
- } else {
- winnerMap[key] = map[string]interface{}{
- "b_id": m.EntId,
- "b_name": entNameMap[m.EntId],
- "a_name": buyer,
- "a_id": buyerId,
- "sourceType": "supplier",
- "zbtime": zbtime,
- "personName": personMap[m.EntId],
- "count": 1,
- "list": []map[string]interface{}{
- {
- "zbtime": zbtime,
- "entName": winner,
- "projectId": projectId,
- "projectName": projectName,
- },
- },
- }
- }
- } else {
- agencyId := m.EntId
- key = fmt.Sprintf("%s_%s", m.Buyer_id, agencyId)
- if _, ok := agencyIdMap[key]; ok {
- data := agencyMap[key]
- data["count"] = gconv.Int64(data["count"]) + 1
- dataList := gconv.Maps(data["list"])
- dataList = append(dataList, map[string]interface{}{
- "zbtime": zbtime,
- "projectId": projectId,
- "projectName": projectName,
- })
- data["list"] = dataList
- data["zbtime"] = zbtime
- agencyMap[key] = data
- } else {
- agencyIdMap[key] = true
- agencyMap[key] = map[string]interface{}{
- "b_id": m.EntId,
- "b_name": entNameMap[m.EntId],
- "a_name": m.Buyer,
- "a_id": m.Buyer_id,
- "sourceType": "agency",
- "count": 1,
- "zbtime": zbtime,
- "personName": gconv.String(personMap[agencyId]),
- "list": []map[string]interface{}{
- {
- "zbtime": zbtime,
- "projectId": projectId,
- "projectName": projectName,
- },
- },
- }
- }
- }
- }
- for _, m := range winnerMap {
- returnData = append(returnData, map[string]interface{}{
- "b_id": gconv.String(m["b_id"]),
- "b_name": gconv.String(m["b_name"]),
- "a_name": gconv.String(m["a_name"]),
- "a_id": gconv.String(m["a_id"]),
- "sourceType": gconv.String(m["sourceType"]),
- "relationship": gconv.String(m["relationship"]),
- "count": gconv.Int64(m["count"]),
- "personName": gconv.String(m["personName"]),
- "list": m["list"],
- "zbtime": m["zbtime"],
- })
- }
- for _, m := range agencyMap {
- returnData = append(returnData, map[string]interface{}{
- "b_id": gconv.String(m["b_id"]),
- "b_name": gconv.String(m["b_name"]),
- "a_name": gconv.String(m["a_name"]),
- "a_id": gconv.String(m["a_id"]),
- "sourceType": gconv.String(m["sourceType"]),
- "relationship": gconv.String(m["relationship"]),
- "personName": gconv.String(m["personName"]),
- "count": gconv.Int64(m["count"]),
- "list": m["list"],
- "zbtime": m["zbtime"],
- })
- }
- }
- sort.Slice(returnData, func(i, j int) bool {
- aa := fmt.Sprintf("%s%s", gconv.String(returnData[i]["zbtime"]),
- gconv.String(returnData[i]["b_id"]))
- bb := fmt.Sprintf("%s%s", gconv.String(returnData[j]["zbtime"]),
- gconv.String(returnData[j]["b_id"]))
- return aa > bb
- })
- return returnData
- }
- // 中间人查询
- func FindMiddleman(buyerArr []string, positionId int64, returnData []map[string]interface{}) []map[string]interface{} {
- if len(buyerArr) == 0 {
- return returnData
- }
- //中间人 作为可介绍业主 企业名称
- companyArr := CrmMysql.SelectBySql(
- 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, ",")))
- for _, v := range *companyArr {
- companyId := gconv.String(v["company_id"])
- companyName := gconv.String(v["company_name"])
- relateName := gconv.String(v["relate_name"])
- relateId := gconv.String(v["relate_id"])
- returnData = append(returnData, map[string]interface{}{
- "b_id": companyId,
- "b_name": companyName,
- "a_name": relateName,
- "a_id": relateId,
- "sourceType": "middleman",
- "relationship": "业主的关系人",
- "personName": gconv.String(v["contact_person"]),
- })
- }
- return returnData
- }
- // 企业之间关系查询
- func Findfirstparty(buyerArr []string, returnData []map[string]interface{}) []map[string]interface{} {
- if len(buyerArr) == 0 {
- return returnData
- }
- buyerSql := fmt.Sprintf(`select DISTINCT
- a.a_id as a_id,
- a.b_id as b_id,
- a.a_name as a_name,
- a.b_name as b_name,
- 111 as status,
- a.code as code
- from
- ent_map_code a
- where
- a.a_id in (%s)
- and a.code in('0101', '0201')
- UNION ALL
- select
- a.b_id as a_id,
- a.a_id as b_id,
- a.b_name as a_name,
- a.a_name as b_name,
- 222 as status,
- a.code as code
- from
- ent_map_code a
- where
- a.b_id in (%s)
- and a.code in('0101', '0201')`,
- strings.Join(buyerArr, ","),
- strings.Join(buyerArr, ","))
- relationshipArr := BuyerFindConnectionsHandle(buyerSql)
- if relationshipArr != nil && len(relationshipArr) > 0 {
- entIdArr := []string{}
- for _, v := range relationshipArr {
- if v.Bid != "" {
- entIdArr = append(entIdArr, fmt.Sprintf("'%s'", v.Bid))
- }
- }
- personMap := map[string]string{}
- if len(entIdArr) > 0 {
- personSql := fmt.Sprintf(`select id,name as personName from ent_contact where id in (%s) ORDER by name`, strings.Join(entIdArr, ","))
- personArr := PersonFindConnectionsHandle(personSql)
- //联系人处理
- for _, v := range personArr {
- personMap[v.Id] = v.PersonName
- }
- }
- for _, v := range relationshipArr {
- code := v.Code
- status := v.Status
- if gconv.String(status) == "111" {
- //key := fmt.Sprintf("%s_%s", a_id, b_id)
- switch code {
- case "0101": //管辖关系
- returnData = append(returnData, map[string]interface{}{
- "b_id": v.Bid,
- "b_name": v.Bname,
- "a_name": v.Aname,
- "a_id": v.Aid,
- "sourceType": "firstparty",
- "relationship": "业主的下级机构",
- "personName": gconv.String(personMap[v.Bid]),
- })
- case "0201": //投资关系
- returnData = append(returnData, map[string]interface{}{
- "b_id": v.Bid,
- "b_name": v.Bname,
- "a_name": v.Aname,
- "a_id": v.Aid,
- "sourceType": "firstparty",
- "relationship": "业主的股东",
- "personName": gconv.String(personMap[v.Bid]),
- })
- }
- }
- if gconv.String(status) == "222" {
- //key := fmt.Sprintf("%s_%s", b_id, a_id)
- if code == "0101" {
- //"0101":管辖关系
- returnData = append(returnData, map[string]interface{}{
- "b_id": v.Bid,
- "b_name": v.Bname,
- "a_name": v.Aname,
- "a_id": v.Aid,
- "sourceType": "firstparty",
- "relationship": "业主的上级机构",
- "personName": gconv.String(personMap[v.Bid]),
- })
- }
- if code == "0201" {
- returnData = append(returnData, map[string]interface{}{
- "b_id": v.Bid,
- "b_name": v.Bname,
- "a_name": v.Aname,
- "a_id": v.Aid,
- "sourceType": "firstparty",
- "relationship": "业主的股东",
- "personName": gconv.String(personMap[v.Bid]),
- })
- }
- }
- }
- }
- return returnData
- }
- // 采购单位和项目合并
- func BuyerProjectMerge(dataMap, projectMap *map[string]map[string]interface{}, sourceType string) ([]BuyerProject, int64, int64, int64) {
- returnData := []BuyerProject{}
- connectionsNumber := int64(0)
- highSuccessNumber := int64(0)
- monitorNumber := int64(0)
- for buyerId, buyerMap := range *dataMap {
- buyerName := gconv.String(buyerMap["buyerName"])
- count := int64(0)
- if _, ok := (*projectMap)[buyerName]; ok {
- projectMap := (*projectMap)[buyerName]
- if isMonitor := gconv.Bool(buyerMap["isMonitor"]); isMonitor {
- monitorNumber++
- }
- count = gconv.Int64(projectMap["count"])
- money := gconv.Int64(projectMap["money"])
- zbtime := gconv.Int64(projectMap["zbtime"])
- if count >= 2 {
- highSuccessNumber++
- }
- if sourceType == "1" {
- if count < 2 {
- continue
- }
- }
- returnData = append(returnData, BuyerProject{
- BuyerId: buyerId,
- BuyerName: buyerName,
- BuyerType: gconv.String(buyerMap["buyerType"]),
- Project: ProjectEntity{
- Number: count,
- EstimatedAmount: money,
- Connections: []map[string]interface{}{},
- },
- Area: gconv.String(projectMap["area"]),
- Zbtime: zbtime,
- IsIgnore: gconv.Bool(buyerMap["isIgnore"]),
- IsMonitor: gconv.Bool(buyerMap["isMonitor"]),
- IsCreateCustomer: gconv.Bool(buyerMap["isCreateCustomer"]),
- CId: gconv.String(buyerMap["cId"]),
- })
- } else {
- if sourceType == "1" {
- if count < 2 {
- continue
- }
- }
- returnData = append(returnData, BuyerProject{
- BuyerId: buyerId,
- BuyerName: buyerName,
- BuyerType: gconv.String(buyerMap["buyerType"]),
- Project: ProjectEntity{
- Number: 0,
- EstimatedAmount: 0,
- Connections: []map[string]interface{}{},
- },
- Area: "",
- Zbtime: 0,
- IsIgnore: gconv.Bool(buyerMap["isIgnore"]),
- IsMonitor: gconv.Bool(buyerMap["isMonitor"]),
- IsCreateCustomer: gconv.Bool(buyerMap["isCreateCustomer"]),
- CId: gconv.String(buyerMap["cId"]),
- })
- }
- connectionsNumber++
- }
- return returnData, connectionsNumber, highSuccessNumber, monitorNumber
- }
- // 已监控数据处理
- func MonitorStatusInit(positionId int64, dataMap *map[string]map[string]interface{}, sourceType string) {
- monitorMap := map[string]bool{}
- query := map[string]interface{}{
- "userId": gconv.String(positionId),
- }
- clist, ok := Mgo.Find("follow_customer", query, ``, `{"name":1}`, false, -1, -1)
- if ok && clist != nil && len(*clist) > 0 {
- for _, v := range *clist {
- monitorMap[gconv.String(v["name"])] = true
- }
- }
- //采购单位和自己监控的对比
- newMap := &map[string]map[string]interface{}{}
- for k, v := range *dataMap {
- buyerName := gconv.String(v["buyerName"])
- if _, ok1 := monitorMap[gconv.String(buyerName)]; ok1 {
- v["isMonitor"] = true
- (*newMap)[k] = v
- } else {
- if sourceType != "2" {
- v["isMonitor"] = false
- (*newMap)[k] = v
- }
- }
- }
- if sourceType == "2" {
- *dataMap = *newMap
- return
- }
- if newMap != nil {
- *dataMap = *newMap
- }
- }
- func FindStatus(positionId int64) (map[string]bool, map[string]bool, map[string]bool) {
- //未处理
- untreatedMap := map[string]bool{}
- //已忽略
- ignoredMap := map[string]bool{}
- //已创建
- createdMap := map[string]bool{}
- processingArr := CrmMysql.Find(entity.CONNECTION_STATUS, map[string]interface{}{
- "itype": 1,
- "position_id": positionId,
- }, "relate_id,is_handle,is_ignore,is_create", "", -1, -1)
- if processingArr != nil && len(*processingArr) > 0 {
- for _, v := range *processingArr {
- entId := gconv.String(v["relate_id"])
- handle := gconv.Int64(v["is_handle"])
- ignore := gconv.Int64(v["is_ignore"])
- create := gconv.Int64(v["is_create"])
- if handle == 1 {
- untreatedMap[entId] = true
- }
- if ignore == 1 {
- ignoredMap[entId] = true
- }
- if create == 1 {
- createdMap[entId] = true
- }
- }
- }
- return untreatedMap, ignoredMap, createdMap
- }
- // 处理状态初始化
- func ProcessingStatusInit(positionId int64, dataMap *map[string]map[string]interface{}, processingStatus string) {
- //收录数据处理
- untreatedMap, ignoredMap, createdMap := FindStatus(positionId)
- newMap := &map[string]map[string]interface{}{}
- //所有采购单位和处理状态对比
- for buyerId, value := range *dataMap {
- if _, ok := ignoredMap[buyerId]; ok {
- value["isIgnore"] = true
- }
- if _, ok := createdMap[buyerId]; ok {
- value["isCreateCustomer"] = true
- }
- for _, v := range strings.Split(processingStatus, ",") {
- switch v {
- case "1":
- if _, ok := untreatedMap[buyerId]; !ok {
- (*newMap)[buyerId] = value
- }
- case "2":
- if _, ok := ignoredMap[buyerId]; ok {
- (*newMap)[buyerId] = value
- }
- case "3":
- if _, ok := createdMap[buyerId]; ok {
- (*newMap)[buyerId] = value
- }
- case "全部", "":
- (*newMap)[buyerId] = value
- }
- }
- }
- if newMap != nil {
- *dataMap = *newMap
- }
- }
- // 采购单位查询
- func BuyerList(partyA, supplier, heterotophy, intermediary, agency string, positionId int64) *map[string]map[string]interface{} {
- dataMap := &map[string]map[string]interface{}{}
- //甲方
- if partyA != "" {
- intermediaryArr := []string{}
- for _, v := range strings.Split(partyA, ",") {
- if v != "" {
- intermediaryArr = append(intermediaryArr, fmt.Sprintf("'%s'", v))
- }
- }
- if len(partyA) > 0 {
- partyASql := fmt.Sprintf(`select id as buyer_id,company_name as buyer from ent_info where id in (%s)`, strings.Join(intermediaryArr, ","))
- FindHandle(partyASql, dataMap, "firstparty")
- }
- }
- //供应商 //同甲异业
- findInSetArr := []string{}
- if supplier != "" {
- for _, v := range strings.Split(supplier, ",") {
- if v != "" {
- findInSetArr = append(findInSetArr, fmt.Sprintf("'%s'", v))
- }
- }
- }
- if len(findInSetArr) > 0 {
- sqlStr := fmt.Sprintf(`SELECT buyer_id,buyer FROM transaction_info where hasAny(winner_id,[%s]) `, strings.Join(findInSetArr, ","))
- FindHandle(sqlStr, dataMap, "supplier")
- }
- //同甲异业
- findheterotophyArr := []string{}
- if heterotophy != "" {
- for _, v := range strings.Split(heterotophy, ",") {
- if v != "" {
- findheterotophyArr = append(findheterotophyArr, fmt.Sprintf("'%s'", v))
- }
- }
- }
- if len(findheterotophyArr) > 0 {
- sqlStr := fmt.Sprintf(`SELECT buyer_id,buyer FROM transaction_info where hasAny(winner_id,[%s]) `, strings.Join(findheterotophyArr, ","))
- FindHandle(sqlStr, dataMap, "adiffb")
- }
- //中间人
- if intermediary != "" {
- wh, args := common.WhArgs(strings.Split(intermediary, ","))
- args = append(args, positionId)
- 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...)
- if intermediaryArr != nil && len(*intermediaryArr) > 0 {
- for _, m := range *intermediaryArr {
- buyerId := gconv.String(m["relate_id"])
- buyerName := gconv.String(m["relate_name"])
- (*dataMap)[buyerId] = map[string]interface{}{
- "buyerName": buyerName,
- "buyerType": "middleman",
- "cId": gconv.String(m["id"]),
- }
- }
- }
- }
- //招标代理
- if agency != "" {
- agencyArr := []string{}
- for _, s := range strings.Split(agency, ",") {
- agencyArr = append(agencyArr, fmt.Sprintf("'%s'", s))
- }
- sqlStr := fmt.Sprintf(`SELECT buyer_id,buyer FROM transaction_info where agency_id in (%s) `, strings.Join(agencyArr, ","))
- FindHandle(sqlStr, dataMap, "agency")
- }
- return dataMap
- }
- // 项目数量查询
- func ProjectHandle(buyerArr []string, entAccountId int64, entName, area, projectType string, dataMap *map[string]map[string]interface{}) (*map[string]map[string]interface{}, *map[string]map[string]interface{}, *map[string]map[string]interface{}) {
- projectMap := &map[string]map[string]interface{}{}
- returnMap := &map[string]map[string]interface{}{}
- sql := ""
- sqlStr := ""
- propertyFormStr := ""
- if projectType == "1" {
- propertyForm := ""
- m1 := CrmMysql.FindOne("config_tenant", map[string]interface{}{"account_id": entAccountId}, "probusfor", "")
- if m1 != nil && len(*m1) > 0 {
- propertyForm = common.ObjToString((*m1)["probusfor"])
- if propertyForm != "" {
- propertyFormStr = fmt.Sprintf(`,{"match":{"property_form":"%s"}}`, propertyForm)
- }
- }
- }
- if entName != "" {
- sql = `{"query":{"bool":{"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}`
- sqlStr = fmt.Sprintf(sql, entName, common.If(area != "", fmt.Sprintf(`,{"term":{"area":"%s"}}`, area), ""), common.If(projectType == "1", propertyFormStr, ""))
- } else {
- sql = `{"query":{"bool":{"must":[{"terms":{"buyer":[%s]}}%s%s]}},"aggs":{"buyer_count":{"terms":{"field":"buyer","size":500,"order":{"zbtime_count":"desc"}},"aggs":{"area_count":{"terms":{"field":"area"}},"buyer_id":{"terms":{"field":"buyer_id"}},"money_count":{"sum":{"field":"project_money"}},"zbtime_count":{"max":{"field":"zbtime"}}}}},"size":0}`
- sqlStr = fmt.Sprintf(sql, strings.Join(buyerArr, ","), common.If(area != "", fmt.Sprintf(`,{"term":{"area":"%s"}}`, area), ""), common.If(projectType == "1", propertyFormStr, ""))
- }
- startTime := time.Now().Unix()
- data, _, _ := elastic.GetAggs(INDEX_1, INDEX_1, sqlStr)
- endTime := time.Now().Unix()
- fmt.Println("es用时时间:", endTime-startTime)
- if len(data) == 0 {
- return projectMap, returnMap, dataMap
- }
- for _, object := range data {
- buyerArr := BuyerAggStruct{}
- bs, ok := object.MarshalJSON()
- if ok != nil {
- logx.Error("解析项目数据失败", object)
- continue
- }
- err := json.Unmarshal(bs, &buyerArr)
- if err != nil {
- logx.Error(err)
- }
- for _, v := range buyerArr.Buckets {
- buyerName := v.Key
- area := ""
- buyerId := ""
- for _, areaEntity := range v.Area_count.Buckets {
- area = Deduplication(area, areaEntity.Key)
- }
- for _, buyerIdEntity := range v.Buyer_id.Buckets {
- if buyerIdEntity.Key != "" {
- buyerId = buyerIdEntity.Key
- }
- }
- (*projectMap)[buyerName] = map[string]interface{}{
- "area": area,
- "zbtime": v.Zbtime_count.Value,
- "money": common.RetainDecimal(common.Float64All(v.Money_count.Value)/10000, 2),
- "count": v.Doc_count,
- "buyerId": buyerId,
- }
- (*returnMap)[buyerId] = map[string]interface{}{
- "buyerName": buyerName,
- "buyerType": "firstparty",
- }
- }
- }
- if projectType == "1" || area != "" {
- if entName == "" {
- for buyerId, v := range *dataMap {
- buyerName := gconv.String(v["buyerName"])
- if _, ok := (*projectMap)[buyerName]; !ok {
- delete(*dataMap, buyerId)
- }
- }
- } else {
- for buyerId, v := range *returnMap {
- buyerName := gconv.String(v["buyerName"])
- if _, ok := (*projectMap)[buyerName]; !ok {
- delete(*returnMap, buyerId)
- }
- }
- }
- }
- return projectMap, returnMap, dataMap
- }
- type BuyerAggStruct struct {
- Buckets []struct {
- Key string `json:"key,omitempty"`
- Doc_count int64 `json:"doc_count,omitempty"`
- Zbtime_count struct {
- Value interface{} `json:"value,omitempty"`
- } `json:"zbtime_count,omitempty"`
- Money_count struct {
- Value interface{} `json:"value,omitempty"`
- } `json:"money_count,omitempty"`
- Area_count struct {
- Buckets []struct {
- Key string `json:"key,omitempty"`
- Doc_count int64 `json:"doc_count,omitempty"`
- }
- } `json:"area_count"`
- Buyer_id struct {
- Buckets []struct {
- Key string `json:"key,omitempty"`
- Doc_count int64 `json:"doc_count,omitempty"`
- }
- } `json:"buyer_id"`
- }
- }
- // 采购单位查询sql
- func FindHandle(sqlStr string, dataMap *map[string]map[string]interface{}, buyerType string) {
- rows, err := ClickhouseConn.Query(context.Background(), sqlStr)
- if err != nil {
- logx.Error("查询失败", sqlStr, err)
- }
- for rows.Next() {
- data := Recommend{}
- rows.ScanStruct(&data)
- if data.BuyerId != "" {
- (*dataMap)[data.BuyerId] = map[string]interface{}{
- "buyerName": data.Buyer,
- "buyerType": buyerType,
- }
- }
- }
- return
- }
- type ConnectionsEntity struct {
- Aid string `ch:"a_id"`
- Bid string `ch:"b_id"`
- Aname string `ch:"a_name"`
- Bname string `ch:"b_name"`
- Status uint8 `ch:"status"`
- Code string `ch:"code"`
- Cperson string `ch:"c_person"`
- }
- type PersonEntity struct {
- Id string `ch:"id"`
- PersonName string `ch:"personName"`
- }
- type SupplierConnectionsEntity struct {
- Zbtime int64 `ch:"zbtime"`
- Project_id string `ch:"project_id"`
- Project_name string `ch:"project_name"`
- Buyer_id string `ch:"buyer_id"`
- Buyer string `ch:"buyer"`
- EntId string `ch:"entId"`
- EntType string `ch:"entType"`
- }
- type SupplierConnectionsEntitys struct {
- Zbtime int64
- Project_id string
- Project_name string
- Buyer_id string
- Buyer string
- EntId string
- EntType string
- }
- type TimeConnectionsEntity struct {
- Zbtime int64 `ch:"zbtime"`
- Project_id string `ch:"project_id"`
- Project_name string `ch:"project_name"`
- }
- // 采购单位人脉信息查询sql
- func BuyerFindConnectionsHandle(sqlStr string) []ConnectionsEntity {
- returnData := []ConnectionsEntity{}
- rows, err := ClickhouseConn.Query(context.Background(), sqlStr)
- if err != nil {
- logx.Error("查询失败", sqlStr, err)
- }
- for rows.Next() {
- data := ConnectionsEntity{}
- err := rows.ScanStruct(&data)
- logx.Info(err)
- returnData = append(returnData, data)
- }
- return returnData
- }
- func PersonFindConnectionsHandle(sqlStr string) []PersonEntity {
- returnData := []PersonEntity{}
- rows, err := ClickhouseConn.Query(context.Background(), sqlStr)
- if err != nil {
- logx.Error("查询失败", sqlStr, err)
- }
- for rows.Next() {
- data := PersonEntity{}
- rows.ScanStruct(&data)
- returnData = append(returnData, data)
- }
- return returnData
- }
- // 供应商
- func SupplierFindConnectionsHandle(sqlStr string) []SupplierConnectionsEntitys {
- returnData := []SupplierConnectionsEntitys{}
- rows, err := ClickhouseConn.Query(context.Background(), sqlStr)
- if err != nil {
- logx.Error("查询失败", sqlStr, err)
- }
- for rows.Next() {
- data := SupplierConnectionsEntity{}
- err = rows.ScanStruct(&data)
- if err != nil {
- logx.Error(err)
- }
- returnData = append(returnData, SupplierConnectionsEntitys{
- Zbtime: data.Zbtime,
- Project_id: data.Project_id,
- Project_name: data.Project_name,
- Buyer_id: data.Buyer_id,
- Buyer: data.Buyer,
- EntId: data.EntId,
- EntType: data.EntType,
- })
- }
- return returnData
- }
- // 合作时间查询
- func TimeFindConnectionsHandle(sqlStr string) []TimeConnectionsEntity {
- returnData := []TimeConnectionsEntity{}
- rows, err := ClickhouseConn.Query(context.Background(), sqlStr)
- if err != nil {
- logx.Error("查询失败", sqlStr, err)
- }
- for rows.Next() {
- data := TimeConnectionsEntity{}
- rows.ScanStruct(&data)
- returnData = append(returnData, data)
- }
- return returnData
- }
- // 去重处理
- func Deduplication(a, b string) string {
- newArr := []string{}
- if b == "全国" {
- return a
- }
- if a != "" {
- newArr = append(newArr, a)
- }
- if b != "" {
- newArr = append(newArr, b)
- }
- return strings.Join(newArr, ",")
- }
- // 路径列表
- func (t *OwnerService) OwnerRoute() []map[string]interface{} {
- if t.BuyerId == "" {
- return []map[string]interface{}{}
- }
- routeList := ConnectionsHandle([]string{
- fmt.Sprintf("'%s'", t.BuyerId),
- }, t.PositionId, false)
- for i, routeMap := range routeList {
- sourceType := gconv.String(routeMap["sourceType"])
- if sourceType == "agency" || sourceType == "supplier" {
- data := routeList[i]
- data["cooperateCount"] = len(gconv.Maps(data["list"]))
- delete(data, "list")
- routeList[i] = data
- }
- }
- return routeList
- }
- // 合作列表
- func (t *OwnerService) OwnerCooperate() []map[string]interface{} {
- returData := []map[string]interface{}{}
- dataArr := []TimeConnectionsEntity{}
- if t.CooperateType == "supplier" {
- //供应商
- supplierSql := fmt.Sprintf(`SELECT
- zbtime,
- project_id,
- project_name
-
- FROM
- transaction_info
- ARRAY
- JOIN winner_id as winnerId
- where buyer_id= '%s' and winnerId='%s' order by zbtime DESC,project_id DESC `, t.BuyerId, t.WinnerId)
- dataArr = TimeFindConnectionsHandle(supplierSql)
- } else if t.CooperateType == "agency" {
- //代理机构
- 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)
- dataArr = TimeFindConnectionsHandle(agentSql)
- }
- if dataArr != nil && len(dataArr) > 0 {
- for _, m := range dataArr {
- zbtime := m.Zbtime
- returData = append(returData, map[string]interface{}{
- "zbtime": common.If(zbtime == 0, "", time.Unix(zbtime, 10).Format("2006.01.02")),
- "entName": t.WinnerName,
- "projectId": encrypt.EncodeArticleId2ByCheck(m.Project_id),
- "projectName": m.Project_name,
- })
- }
- }
- return returData
- }
- // 候选渠道
- func (t *OwnerService) CandidateChannel() (*ResultDatas, int, int, int, int) {
- returnData := []*ResultData{}
- dataMap := &map[string]map[string]interface{}{}
- if t.PartyA != "" || t.Supplier != "" || t.Heterotophy != "" || t.Intermediary != "" || t.Agency != "" {
- dataMap = BuyerList(t.PartyA, t.Supplier, t.Heterotophy, t.Intermediary, t.Agency,
- t.PositionId)
- }
- a1, a2, a3, a4 := 0, 0, 0, 0
- if len(*dataMap) > 0 && dataMap != nil {
- propertyForm := NetworkCom.GetMyProbusfor(t.EntAccountId)
- buyerIds := []string{}
- for buyerId := range *dataMap {
- buyerIds = append(buyerIds, buyerId)
- }
- if len(buyerIds) > 300 {
- buyerIds = buyerIds[:300]
- }
- logx.Info("CandidateChannel start ", t.PositionId)
- buyerIdsTemp := []string{}
- rs1, rs2 := map[string][]map[string]interface{}{}, map[string][]map[string]interface{}{}
- for _, v := range buyerIds {
- buyerIdsTemp = append(buyerIdsTemp, v)
- if len(buyerIdsTemp) == 50 {
- rs1Temp, rs2Temp := GetData(propertyForm, strings.Join(buyerIdsTemp, ","))
- for kk, vv := range rs1Temp {
- rs1[kk] = vv
- }
- for kk, vv := range rs2Temp {
- rs2[kk] = vv
- }
- buyerIdsTemp = []string{}
- }
- }
- if len(buyerIdsTemp) > 0 {
- rs1Temp, rs2Temp := GetData(propertyForm, strings.Join(buyerIdsTemp, ","))
- for kk, vv := range rs1Temp {
- rs1[kk] = vv
- }
- for kk, vv := range rs2Temp {
- rs2[kk] = vv
- }
- }
- logx.Info("CandidateChannel GetData over ", t.PositionId)
- winners, agency := []string{}, []string{}
- for buyerId := range *dataMap {
- for _, m := range rs1[buyerId] {
- winners = append(winners, common.ObjToString(m["name"]))
- }
- for _, m := range rs2[buyerId] {
- agency = append(agency, common.ObjToString(m["name"]))
- }
- }
- logx.Info("CandidateChannel LastTimeCoopBath start ", t.PositionId, " ", len(buyerIds), " ", len(winners), " ", len(agency))
- if len(winners) > 300 {
- winners = winners[:300]
- }
- if len(agency) > 300 {
- agency = agency[:300]
- }
- ltcs1, ltcs2 := LastTimeCoopBath(t.PositionId, buyerIds, winners, agency)
- logx.Info("CandidateChannel LastTimeCoopBath over ", t.PositionId)
- pool := make(chan bool, 3)
- wait := &sync.WaitGroup{}
- lock := &sync.Mutex{}
- maxByIdCount := 0
- for buyerId := range *dataMap {
- if ltcs1[buyerId] != nil {
- for _, m := range rs1[buyerId] {
- ltc := ltcs1[buyerId][common.ObjToString(m["name"])]
- if ltc == nil {
- continue
- }
- tmp := ResultData{
- SourceType: "adiffb",
- EntId: common.ObjToString(m["nameId"]),
- EntName: common.ObjToString(m["name"]),
- ProjectNum: common.IntAll(m["coop_size"]),
- TotalAmount: common.Float64All(m["coop_amount"]),
- BuyerId: buyerId,
- RecentTime: ltc.ZbTime,
- NearlyYears: ltc.Near,
- }
- if tmp.EntId == "" || tmp.BuyerId == "" {
- continue
- }
- a1++
- returnData = append(returnData, &tmp)
- }
- }
- if ltcs2[buyerId] != nil {
- for _, m := range rs2[buyerId] {
- ltc := ltcs1[buyerId][common.ObjToString(m["name"])]
- if ltc == nil {
- continue
- }
- tmp := ResultData{
- SourceType: "agency",
- EntName: common.ObjToString(m["name"]),
- ProjectNum: common.IntAll(m["coop_size"]),
- TotalAmount: common.Float64All(m["coop_amount"]),
- RecentTime: ltc.ZbTime,
- NearlyYears: ltc.Near,
- EntId: common.ObjToString(m["nameId"]),
- BuyerId: buyerId,
- }
- if tmp.EntId == "" || tmp.BuyerId == "" {
- continue
- }
- a2++
- returnData = append(returnData, &tmp)
- }
- }
- maxByIdCount++
- if maxByIdCount > 50 {
- break
- }
- pool <- true
- wait.Add(1)
- go func(byId string) {
- defer common.Catch()
- defer func() {
- <-pool
- wait.Done()
- }()
- // 中间人可介绍业主
- var r3 []map[string]interface{}
- r3 = FindMiddleman([]string{fmt.Sprintf("'%s'", byId)}, t.PositionId, r3)
- lock.Lock()
- if r3 != nil && len(r3) > 0 {
- for _, m := range r3 {
- tmp := ResultData{
- SourceType: "middleman",
- EntName: common.ObjToString(m["b_name"]),
- EntPerson: common.ObjToString(m["personName"]),
- Relationship: "业主的关系人",
- EntId: common.ObjToString(m["b_id"]),
- BuyerId: byId,
- }
- if tmp.EntId == "" || tmp.BuyerId == "" {
- continue
- }
- a3++
- returnData = append(returnData, &tmp)
- }
- }
- lock.Unlock()
- // 关联单位
- var r4 []map[string]interface{}
- r4 = Findfirstparty([]string{fmt.Sprintf("'%s'", byId)}, r4)
- lock.Lock()
- if r4 != nil && len(r4) > 0 {
- for _, m := range r4 {
- tmp := ResultData{
- SourceType: "sup_sub",
- EntName: common.ObjToString(m["b_name"]),
- EntPerson: common.ObjToString(m["personName"]),
- Relationship: common.ObjToString(m["relationship"]),
- EntId: common.ObjToString(m["b_id"]),
- BuyerId: byId,
- }
- if tmp.EntId == "" || tmp.BuyerId == "" {
- continue
- }
- a4++
- returnData = append(returnData, &tmp)
- }
- }
- lock.Unlock()
- }(buyerId)
- }
- wait.Wait()
- }
- logx.Info("CandidateChannel over", t.PositionId)
- //状态处理
- result := &ResultDatas{}
- if len(returnData) > 0 {
- monitorMap := NetworkCom.EntMonitor(gconv.String(t.PositionId))
- _, ignoredMap, createdMap := FindStatus(t.PositionId)
- for k, value := range returnData {
- if _, ok := ignoredMap[value.EntId]; ok {
- value.IsIgnore = true
- }
- if _, ok := createdMap[value.EntId]; ok {
- value.IsCreateCustomer = true
- }
- if _, ok := monitorMap[value.EntName]; ok {
- value.IsMonitor = true
- }
- returnData[k] = value
- if t.Type != "" && t.Type != value.SourceType {
- continue
- }
- *result = append(*result, value)
- }
- }
- sort.Sort(result)
- return result, a1, a2, a3, a4
- }
|