xingzai 5 månader sedan
förälder
incheckning
63848912d9

+ 440 - 0
controllers/statistic_report.go

@@ -17,6 +17,7 @@ import (
 	"hongze/hz_crm_api/services"
 	"hongze/hz_crm_api/services/alarm_msg"
 	contractService "hongze/hz_crm_api/services/contract"
+	cygxService "hongze/hz_crm_api/services/cygx"
 	fmsService "hongze/hz_crm_api/services/fms"
 	"hongze/hz_crm_api/services/statistic_report"
 	"hongze/hz_crm_api/utils"
@@ -6514,3 +6515,442 @@ func (this *StatisticReportController) UnusualRenewCompanyList() {
 	br.Msg = "获取成功"
 	br.Data = resp
 }
+
+// StackCompanyListRai
+// @Title 获取权益存量客户数据列表
+// @Description 获取权益存量客户数据列表接口
+// @Param   PageSize   query   int  true       "每页数据条数"
+// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
+// @Param   Keyword   query   string  true       "客户名称"
+// @Param   AdminId   query   string  true       "销售id,多个用英文逗号隔开,空字符串为全部"
+// @Param   RegionType   query   string  false       "所属区域:传空字符串或者不传为全部,'国内','海外'"
+// @Param   DataType   query   string  false       "报表类型,枚举值:`新签客户`,`续约客户`,`未续约客户`"
+// @Param   TryOutType   query   string  false       " '试用', '非试用' 非试用即为冻结/流失"
+// @Param   IsExport   query   bool  false       "是否导出excel,默认是false"
+// @Param   CompanyAscribeId   query   int  false       "归因ID"
+// @Success 200 {object} response.StackCompanyListResp
+// @router /stack_company_list_rai [get]
+func (this *StatisticReportController) StackCompanyListRai() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+
+	pageSize, _ := this.GetInt("PageSize")
+	currentIndex, _ := this.GetInt("CurrentIndex")
+
+	//是否导出报表
+	isExport, _ := this.GetBool("IsExport")
+	if isExport {
+		pageSize = 10000
+		currentIndex = 1
+	}
+
+	adminId := this.GetString("AdminId")
+	regionType := this.GetString("RegionType")
+	companyType := this.GetString("CompanyType")
+	dataType := this.GetString("DataType")
+	tryOutType := this.GetString("TryOutType")
+	keyword := this.GetString("Keyword")
+
+	companyAscribeId, _ := this.GetInt("CompanyAscribeId", -1) // CRM 13.9
+
+	var resp response.StackCompanyListResp
+	//历史统计数据
+	//获取实时统计数据(今天数据)
+	tmpResp, err := getTodayStackCompanyListV2Rai(sysUser, currentIndex, pageSize, companyAscribeId, adminId, regionType, companyType, dataType, tryOutType, keyword)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	resp = tmpResp
+
+	//导出excel
+	if isExport {
+		StackCompanyListExport(this, dataType, resp, br)
+		return
+	}
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = resp
+}
+
+func getTodayStackCompanyListV2Rai(sysUser *system.Admin, currentIndex, pageSize, companyAscribeId int, adminId, regionType, companyType, dataType, tryOutType, keyword string) (returnData response.StackCompanyListResp, err error) {
+	var startSize int
+	if pageSize <= 0 {
+		pageSize = utils.PageSize20
+	}
+	if currentIndex <= 0 {
+		currentIndex = 1
+	}
+	startSize = utils.StartIndex(currentIndex, pageSize)
+
+	var condition, listCondition string
+	var pars, listPars []interface{}
+
+	today := utils.GetToday(utils.FormatDate)
+	//条件
+	var conditionAscribRai string // 处理权益未续约客户检索列表SQL查询条件
+	var parsAscribeRai []interface{}
+
+	//归因ID CRM 13.9
+	if companyAscribeId > 0 {
+		var conditionAscribe string
+		var parsAscribe []interface{}
+		conditionAscribe = "  AND  company_ascribe_id = ? "
+		parsAscribe = append(parsAscribe, companyAscribeId)
+		companyNoRenewedAscribeList, e := company.GetCompanyNoRenewedAscribeList(conditionAscribe, parsAscribe, 0, 0)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
+			return
+		}
+		var companyIds []int
+		if len(companyNoRenewedAscribeList) == 0 {
+			companyIds = append(companyIds, 0) // 给一个不存在的ID
+		} else {
+			for _, v := range companyNoRenewedAscribeList {
+				companyIds = append(companyIds, v.CompanyId)
+			}
+		}
+		conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
+		parsAscribeRai = append(parsAscribeRai, companyIds)
+	}
+
+	if adminId != "" {
+		//condition += ` AND c.seller_id in  (` + adminId + `) `
+		//pars = append(pars, adminId)
+	} else {
+		//根据当前角色来获取查询条件
+		condition, pars = getQueryParams(condition, pars, sysUser, "c.")
+
+	}
+	if regionType != "" {
+		condition += ` AND b.region_type = ? `
+		pars = append(pars, regionType)
+	}
+	//关键字搜索
+	if keyword != "" {
+		condition += ` and b.company_name like "%` + keyword + `%" `
+	}
+
+	condition += ` AND a.product_id = ? `
+	pars = append(pars, 2)
+
+	var dataTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
+	var notRenewalTryOut, notRenewalNotTryOut int
+	var list []*models.IncrementalList
+	//新签客户数
+	{
+		condition1 := condition
+		if adminId != "" {
+			condition1 += ` AND a.seller_id_init in  (` + adminId + `) `
+		}
+		pars1 := pars
+		//condition1 += ` AND c.status = "正式"  `
+		condition1 += ` AND a.start_date <= ? AND a.end_date >= ? `
+		pars1 = append(pars1, today, today)
+		condition1 += ` AND a.contract_type = ? `
+		pars1 = append(pars1, "新签合同")
+
+		total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
+		if countErr != nil && countErr.Error() != utils.ErrNoRow() {
+			err = countErr
+			return
+		}
+		newCompanyTotal = total
+
+		if dataType == "新签客户" {
+			//页表页数据总和
+			total, countErr = models.GetTodayStackCompanyProductCount(condition1, pars1)
+			if countErr != nil && countErr.Error() != utils.ErrNoRow() {
+				err = countErr
+				return
+			}
+			dataTotal = total
+			listCondition = condition1
+			listPars = pars1
+		}
+	}
+
+	//续约客户数
+	{
+
+		condition1 := condition
+		if adminId != "" {
+			condition1 += ` AND a.seller_id_init in  (` + adminId + `) `
+		}
+		pars1 := pars
+		//condition1 += ` AND c.status  = "正式" `
+		condition1 += ` AND a.start_date <= ? AND a.end_date >= ? `
+		pars1 = append(pars1, today, today)
+		condition1 += ` AND a.contract_type = ? `
+		pars1 = append(pars1, "续约合同")
+
+		//额外条件(续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户)
+		pars1 = append(pars1, today)
+		total, countErr := models.GetIncrementalNewCompanyCountV2(condition1, pars1)
+		if countErr != nil && countErr.Error() != utils.ErrNoRow() {
+			err = countErr
+			return
+		}
+		renewalCompanyTotal = total
+
+		if dataType == "续约客户" {
+			//页表页数据总和
+			total, countErr = models.GetTodayStackCompanyProductCountV2(condition1, pars1)
+			if countErr != nil && countErr.Error() != utils.ErrNoRow() {
+				err = countErr
+				return
+			}
+			dataTotal = total
+			listCondition = condition1
+			listPars = pars1
+		}
+	}
+
+	//未续约客户数
+	{
+		if adminId != "" {
+			condition += ` AND c.seller_id in  (` + adminId + `) `
+		}
+		condition1 := condition
+		pars1 := pars
+		condition1 += ` AND c.status not in ("永续","正式") AND a.create_time <= ? `
+		pars1 = append(pars1, time.Now().Format(utils.FormatDateTime))
+		condition1 += ` AND a.operation = 'try_out' `
+
+		total, countErr := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
+		if countErr != nil && countErr.Error() != utils.ErrNoRow() {
+			err = countErr
+			return
+		}
+		notRenewalCompanyTotal = total
+		condition1 += conditionAscribRai
+		pars1 = append(pars1, parsAscribeRai)
+		if dataType == "未续约客户" {
+			//页表页数据总和
+			//统计数据
+			for _, v := range []string{"试用", "非试用"} {
+				totalCondition1 := condition1
+				totalPars1 := pars1
+				var tmpTotal int
+				if v == "试用" {
+					totalCondition1 += ` AND c.status = "试用" `
+					tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
+					if err != nil {
+						return
+					}
+					notRenewalTryOut = tmpTotal
+				} else if v == "非试用" {
+					totalCondition1 += ` AND c.status IN ("冻结","流失") `
+					tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
+					if err != nil && err.Error() != utils.ErrNoRow() {
+						return
+					}
+					notRenewalNotTryOut = tmpTotal
+				}
+
+			}
+			//列表数据数量
+			if tryOutType == "试用" {
+				condition1 += ` AND c.status = "试用" `
+				total = notRenewalTryOut
+			} else if tryOutType == "非试用" {
+				condition1 += ` AND c.status IN ("冻结","流失") `
+				total = notRenewalNotTryOut
+			}
+
+			//total, countErr := models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
+			//if countErr != nil && countErr.Error() != utils.ErrNoRow() {
+			//	err = countErr
+			//	return
+			//}
+
+			dataTotal = total
+			listCondition = condition1
+			listPars = pars1
+			if tryOutType == "试用" {
+				listCondition += ` AND c.status = "试用" `
+			} else if tryOutType == "非试用" {
+				listCondition += ` AND c.status IN ("冻结","流失") `
+			}
+			tmpList, countErr := models.GetIncrementalCompanyListByOperationRecord(listCondition, listPars, startSize, pageSize)
+			if countErr != nil {
+				err = countErr
+				return
+			}
+			for i := 0; i < len(tmpList); i++ {
+				endDateTime, parseErr := time.Parse(utils.FormatDateTime, tmpList[i].CreateTime)
+				if parseErr != nil {
+					err = parseErr
+					return
+				}
+				tmpList[i].EndDate = endDateTime.Format(utils.FormatDate)
+			}
+			list = tmpList
+
+		}
+	}
+
+	switch dataType {
+	case "新签客户":
+		tmpList, countErr := models.GetTodayStackCompanyList(listCondition, listPars, startSize, pageSize)
+		if countErr != nil {
+			err = countErr
+			return
+		}
+		list = tmpList
+	case "续约客户":
+		tmpList, countErr := models.GetTodayStackCompanyListV2(listCondition, listPars, startSize, pageSize)
+		if countErr != nil {
+			err = countErr
+			return
+		}
+		list = tmpList
+	}
+
+	if dataType == "续约客户" {
+		var ids []string
+		oldCompanyMap := make(map[int]*models.IncrementalList)
+		oldMoneyMap := make(map[int]float64)
+		countMap := make(map[int]int)
+		for _, item := range list {
+			ids = append(ids, strconv.Itoa(item.CompanyId))
+		}
+		if len(ids) > 0 {
+			idStr := strings.Join(ids, ",")
+			lists, contractErr := models.GetLastContractMoney(idStr)
+			if contractErr != nil {
+				err = contractErr
+				return
+			}
+
+			for _, item := range lists {
+				_, countOk := countMap[item.CompanyId]
+				_, ok := oldCompanyMap[item.CompanyId]
+				if !ok {
+					oldCompanyMap[item.CompanyId] = item
+					oldMoneyMap[item.CompanyId] = item.Money
+				} else if !countOk {
+					countMap[item.CompanyId] = 1
+					oldCompanyMap[item.CompanyId] = item
+				}
+			}
+
+			//给list赋值
+			for _, item := range list {
+				if item.ProductName == "权益" {
+					oldMoney, _ := oldMoneyMap[item.CompanyId]
+					lastContract, _ := oldCompanyMap[item.CompanyId]
+					if oldMoney > lastContract.Money {
+						item.PackageDifference = "增加套餐"
+					} else if oldMoney < lastContract.Money {
+						item.PackageDifference = "减少套餐"
+					} else {
+						item.PackageDifference = "维持套餐"
+					}
+				}
+			}
+		}
+	}
+
+	var ascribecompanyIds []int
+	for _, item := range list {
+		ascribecompanyIds = append(ascribecompanyIds, item.CompanyId)
+	}
+	//归因标签
+	mapGetCompanyAscribeContent, mapContent := services.GetCompanyAscribeContentMap(ascribecompanyIds)
+	mapNoRenewedNote := services.GetCompanyNoRenewedNoteMap(ascribecompanyIds)
+	for _, item := range list {
+		item.AscribeContent = mapGetCompanyAscribeContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
+		item.Content = mapContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
+		item.IsShowNoRenewedNote = mapNoRenewedNote[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
+	}
+
+	listLen := len(list)
+	var companyContractIds []int
+	for i := 0; i < listLen; i++ {
+		item := list[i]
+
+		//剩余可用天数
+		//expireDay := "0"
+		//endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
+		//var sub time.Duration
+		//if dataType != "未续约客户" {
+		//	endDateTime = endDateTime.AddDate(0, 0, 1)
+		//	sub = endDateTime.Sub(time.Now())
+		//	//if sub < 0 {
+		//	//	sub = 0
+		//	//}
+		//} else {
+		//	sub = time.Now().Sub(endDateTime)
+		//}
+		//expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
+		//list[i].ExpireDay = expireDay
+		companyContractIds = append(companyContractIds, item.CompanyContractId)
+	}
+
+	//合并合同所对应的权限
+	mappermissionName, err := cygxService.GetCompanyContractPermissionNameMapById(companyContractIds)
+	if err != nil {
+		return
+	}
+	for _, v := range list {
+		v.PermissionName = mappermissionName[v.CompanyContractId]
+	}
+
+	var stackCompanyStatisticList []*models.StackCompanyStatisticList
+	for _, v := range list {
+		stackCompanyStatistic := models.StackCompanyStatisticList{
+			Type:        dataType,
+			CompanyId:   v.CompanyId,
+			CompanyName: v.CompanyName,
+			ProductId:   v.ProductId,
+			ProductName: v.ProductName,
+			ContractNum: v.Count,
+			SellerId:    v.SellerId,
+			SellerName:  v.SellerNameInit,
+			ShareSeller: v.ShareSellerInit,
+			Date:        today,
+			StartDate:   v.StartDate,
+			EndDate:     v.EndDate,
+			RegionType:  v.RegionType,
+			//CreateTime   :v.CreateTime,
+			CreateTimeStr:       v.CreateTime,
+			ExpireDay:           v.ExpireDay,
+			RenewalReason:       v.RenewalReason,
+			RenewalTodo:         v.RenewalTodo,
+			Status:              v.Status,
+			PackageDifference:   v.PackageDifference,
+			AscribeContent:      v.AscribeContent,
+			IsShowNoRenewedNote: v.IsShowNoRenewedNote,
+			Content:             v.Content,
+			PermissionName:      mappermissionName[v.CompanyContractId],
+			Money:               v.Money,
+		}
+		stackCompanyStatisticList = append(stackCompanyStatisticList, &stackCompanyStatistic)
+	}
+	page := paging.GetPaging(currentIndex, pageSize, dataTotal)
+	resp := response.StackCompanyListResp{
+		Paging:                 page,
+		List:                   stackCompanyStatisticList,
+		NewCompanyTotal:        newCompanyTotal,
+		RenewalCompanyTotal:    renewalCompanyTotal,
+		NotRenewalCompanyTotal: notRenewalCompanyTotal,
+		NotRenewalTryOut:       notRenewalTryOut,
+		NotRenewalNotTryOut:    notRenewalNotTryOut,
+	}
+	return resp, err
+}

+ 3 - 0
models/stack_company_statistic.go

@@ -90,6 +90,7 @@ type StackCompanyStatisticList struct {
 	ContractNum         int       `description:"第几份合同,默认是:1"`
 	SellerId            int       `description:"所属销售id"`
 	SellerName          string    `description:"所属销售名称"`
+	ShareSeller         string    `description:"共享销售员"`
 	GroupId             int       `description:"所属销售分组id"`
 	DepartmentId        int       `description:"所属销售部门id"`
 	Date                string    `description:"记录日期"`
@@ -106,6 +107,8 @@ type StackCompanyStatisticList struct {
 	AscribeContent      string    `description:"归因标签说明"`
 	IsShowNoRenewedNote bool      `description:"是否展示未续约备注按钮"`
 	Content             string    `description:"归因内容说明"`
+	PermissionName      string    `description:"权限名"`
+	Money               float64   `description:"合同金额"`
 }
 
 func GetStackCompanyList(condition, orderBy string, pars []interface{}, startSize, pageSize int) (items []*StackCompanyStatisticList, err error) {

+ 3 - 2
models/statistic_report.go

@@ -406,8 +406,9 @@ type IncrementalList struct {
 	PermissionNameStatus string                             `description:"权限状态"`
 	CompanyProductStatus string                             `description:"客户状态"`
 	//CompanyContractIdGroup string                             `description:"表company_contract合并的 company_contract_id"`
-	IsUserMaker    int    `description:"近四周之内是否包含决策人互动过 ,0否,1是"`
-	SellerNameInit string `description:"权益初始化销售"`
+	IsUserMaker     int    `description:"近四周之内是否包含决策人互动过 ,0否,1是"`
+	SellerNameInit  string `description:"权益初始化销售"`
+	ShareSellerInit string `description:"共享销售员"`
 }
 
 // GetIncrementalNewCompanyCount 获取增量客户报表列表统计数据(根据合同来展示)

+ 9 - 0
routers/commentsRouter.go

@@ -11113,6 +11113,15 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:StatisticReportController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:StatisticReportController"],
+        beego.ControllerComments{
+            Method: "StackCompanyListRai",
+            Router: `/stack_company_list_rai`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:StatisticReportController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:StatisticReportController"],
         beego.ControllerComments{
             Method: "WillExpireList",