瀏覽代碼

Merge branch 'crm/crm_14.3' of http://8.136.199.33:3000/hongze/hz_crm_api

xingzai 1 年之前
父節點
當前提交
5a4b1e4143

+ 107 - 0
controllers/company_apply.go

@@ -2306,3 +2306,110 @@ func (this *CompanyApplyController) GetLastContractDetailWithoutDate() {
 	br.Msg = "获取成功"
 	br.Data = contractInfo
 }
+
+// @Title 申请服务更新-签约历史(单个详情)
+// @Description 申请服务更新-签约历史接口(单个详情)
+// @Param   ContractCode   query   string  true       "合同编码"
+// @Success 200 {object} company.CompanyContractHistoryResp
+// @router /apply/contract/history/detail [get]
+func (this *CompanyApplyController) ApplyContractHistoryDetail() {
+	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
+	}
+	contractCode := this.GetString("ContractCode")
+	if contractCode == "" {
+		br.Msg = "参数错误"
+		br.ErrMsg = "参数错误,客户id小于等于0"
+		return
+	}
+	roleTypeCode := sysUser.RoleTypeCode
+	productId := services.GetProductId(roleTypeCode)
+
+	list, err := company.GetCompanyContractHistoryListByContractCode(contractCode)
+	if err != nil {
+		br.Msg = "获取信息失败"
+		br.ErrMsg = "获取信息失败,Err:" + err.Error()
+		return
+	}
+	listLen := len(list)
+	if listLen == 0 {
+		br.Msg = "获取信息失败"
+		br.ErrMsg = "签约信息不存在 contractCode:" + contractCode
+		return
+	}
+	expMap := map[int]string{0: "(3w)", 1: "(5w)"} // 买方研选价格
+	for i := 0; i < listLen; i++ {
+		companyContract := list[i]
+		list[i].ModifyTimeStr = companyContract.ModifyTime.Format(utils.FormatDateTime)
+		productId = list[i].ProductId
+		if productId == utils.COMPANY_PRODUCT_RAI_ID {
+			//classifyName := "权益"
+			checkList := make([]int, 0)
+			plist := new(company.ContractPermissionList)
+			hasPermissions, e := company.GetCompanyContractPermissionByCompanyContractId(companyContract.CompanyContractId)
+			if e != nil {
+				br.Msg = "获取失败"
+				br.ErrMsg = "获取合同权限信息失败,Err:" + e.Error()
+				return
+			}
+			hasMap := make(map[int]*company.CompanyContractPermission)
+			for _, p := range hasPermissions {
+				hasMap[p.ChartPermissionId] = p
+			}
+			checkItems := make([]*company.PermissionLookItem, 0)
+			// PS:本来想把这个移到循环外面去优化一下...但是发现有指针引用变量被改掉的问题, BUG太多了改不完了先这样吧=_=!
+			raiPermissions, e := company.GetPermissionLookItemsExt("2", utils.COMPANY_PRODUCT_RAI_NAME)
+			if e != nil {
+				br.Msg = "获取失败"
+				br.ErrMsg = "获取权益权限列表失败, Err: " + e.Error()
+				return
+			}
+
+			for _, n := range raiPermissions {
+				match := hasMap[n.ChartPermissionId]
+				if match == nil {
+					continue
+				}
+				// 升级
+				if match.IsUpgrade == 1 {
+					n.IsUpgrade = 1
+					checkList = append(checkList, n.ChartPermissionId)
+					checkItems = append(checkItems, n)
+					continue
+				}
+				// 买方研选(3w/5w)
+				if n.PermissionName == utils.CHART_PERMISSION_NAME_MF_YANXUAN {
+					n.PermissionName += expMap[match.ExpensiveYx]
+					checkList = append(checkList, n.ChartPermissionId)
+					checkItems = append(checkItems, n)
+					continue
+				}
+				checkList = append(checkList, n.ChartPermissionId)
+				checkItems = append(checkItems, n)
+			}
+			plist.Items = checkItems
+			plist.ClassifyName = utils.COMPANY_PRODUCT_RAI_NAME
+			plist.CheckList = checkList
+			list[i].PermissionList = append(list[i].PermissionList, plist)
+
+			// CRM8.8-权限主客观合并
+			newPermissionLookList := contractService.HandleEquityContractPermissionList(list[i].PermissionList)
+			list[i].PermissionList = newPermissionLookList
+		}
+	}
+	resp := new(company.CompanyContractHistoryResp)
+	resp.List = list
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = resp
+}

+ 1198 - 0
controllers/cygx/contract_allocation.go

@@ -0,0 +1,1198 @@
+package cygx
+
+import (
+	"encoding/json"
+	"fmt"
+	"github.com/rdlucklib/rdluck_tools/paging"
+	"github.com/tealeg/xlsx"
+	"hongze/hz_crm_api/controllers"
+	"hongze/hz_crm_api/models"
+	"hongze/hz_crm_api/models/company"
+	"hongze/hz_crm_api/models/contract"
+	"hongze/hz_crm_api/models/cygx"
+	"hongze/hz_crm_api/models/system"
+	cygxService "hongze/hz_crm_api/services/cygx"
+	"hongze/hz_crm_api/utils"
+	"os"
+	"path/filepath"
+	"strconv"
+	"strings"
+	"time"
+)
+
+// ContractAllocationController 权益合同派单
+type ContractAllocationController struct {
+	controllers.BaseAuthController
+}
+
+// getQueryParams 获取基础查询信息
+func getQueryParams(condition string, pars []interface{}, sysUser *system.Admin, tableAlias string) (newCondition string, newPars []interface{}) {
+	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
+		condition += " AND " + tableAlias + "product_id=?"
+		pars = append(pars, 1)
+	} else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
+		condition += " AND " + tableAlias + "product_id=?"
+		pars = append(pars, 2)
+	} else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FINANCE {
+		//超级管理员账户,不做条件限制
+	} else {
+		//如果不是研究员,那么去找对应的 部门、小组、销售
+		if sysUser.Authority == 0 {
+			//普通用户
+			condition += " AND " + tableAlias + "seller_id=?"
+			pars = append(pars, sysUser.AdminId)
+		} else if sysUser.Authority == 1 {
+			//部门主管
+			condition += " AND " + tableAlias + "department_id=?"
+			pars = append(pars, sysUser.DepartmentId)
+		} else if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
+			//权益小组负责人
+			condition += " AND " + tableAlias + "group_id=?"
+			pars = append(pars, sysUser.GroupId)
+		} else if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
+			//ficc销售主管
+			pid, err := company.GetParentIdFromGroup(sysUser.GroupId)
+			if err != nil {
+				fmt.Println(err.Error())
+				return
+			}
+			var ids []*string
+			if pid != nil && *pid != 0 {
+				ids, err = company.GetGroupIdsByParentId(*pid)
+				if err != nil {
+					fmt.Println(err.Error())
+				}
+			} else {
+				ids, err = company.GetGroupIdsByParentId(sysUser.GroupId)
+				if err != nil {
+					fmt.Println(err.Error())
+				}
+			}
+			var idSlice []string
+			var sid string
+			for _, id := range ids {
+				idSlice = append(idSlice, *id)
+			}
+			//加入父级groupId
+			if *pid > 0 {
+				idSlice = append(idSlice, strconv.Itoa(*pid))
+			} else {
+				idSlice = append(idSlice, strconv.Itoa(sysUser.GroupId))
+			}
+			sid = strings.Join(idSlice, ",")
+			condition += " AND " + tableAlias + `group_id IN (` + sid + `) `
+			fmt.Println("condition:", condition)
+			//pars = append(pars, sysUser.GroupId)
+		} else if sysUser.Authority == 4 {
+			//ficc小组负责人
+			condition += " AND " + tableAlias + "group_id=?"
+			pars = append(pars, sysUser.GroupId)
+		} else {
+			//不知道什么类型的用户(后面新增的位置类型客户)
+			condition += " AND " + tableAlias + "seller_id=?"
+			pars = append(pars, sysUser.AdminId)
+		}
+	}
+	newCondition = condition
+	newPars = pars
+	return
+}
+
+// @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   StartDate   query   string  false       "开始日期"
+// @Param   EndDate   query   string  false       "结束日期"
+// @Param   ContractType   query   string  false       "合同类型,枚举值:“,`新签合同`,`续约合同`,`补充协议`"
+// @Param   FormalType   query   string  false     "转正类型,枚举值:“,`标准`,`非标`"
+// @Param   IsExport   query   bool  false       "是否导出excel,默认是false"
+// @Param   ResearcherRealName   query   string  false       "研究员姓名"
+// @Param   IsAllocation   query   int  false       "派点状态: -1-默认全部; 0-未派点; 1-已派点"
+// @Success 200 {object}  cygx.CompanyContractListResp
+// @router /allocation/company_contract_list [get]
+func (this *ContractAllocationController) CompanyContractList() {
+	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")
+	adminId := this.GetString("AdminId")
+	formalType := this.GetString("FormalType")
+	contractType := this.GetString("ContractType")
+	keyword := this.GetString("Keyword")
+	startDate := this.GetString("StartDate")
+	endDate := this.GetString("EndDate")
+	researcherRealName := this.GetString("ResearcherRealName")
+	isAllocation, _ := this.GetInt("IsAllocation", -1) // CRM 13.9
+	if startDate == "" {
+		startDate = "2015-01-01"
+	}
+
+	var startSize int
+	if pageSize <= 0 {
+		pageSize = utils.PageSize20
+	}
+	if currentIndex <= 0 {
+		currentIndex = 1
+	}
+	startSize = utils.StartIndex(currentIndex, pageSize)
+	//是否导出报表
+	isExport, _ := this.GetBool("IsExport")
+	if isExport {
+		pageSize = 10000
+		currentIndex = 1
+	}
+
+	var condition string
+	var pars []interface{}
+
+	if endDate != "" {
+		condition += ` AND a.start_date >= ? AND a.start_date <= ? `
+		pars = append(pars, startDate+" 00:00:01", endDate+" 23:59:59")
+	}
+
+	//条件
+	if adminId != "" {
+		condition += ` AND c.seller_id in  (` + adminId + `) `
+		//pars = append(pars, adminId)
+	}
+
+	//权益申请销售只能看到自己名下的客户的申请
+	companyIds, err := cygxService.GetAdminLookUserCompanyIdsBySelf(sysUser)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,GetAdminLookUserCompanyIds Err:" + err.Error()
+		return
+	}
+	lencompanyIds := len(companyIds)
+	if lencompanyIds > 0 {
+		condition += ` AND c.company_id IN (` + utils.GetOrmInReplace(lencompanyIds) + `)`
+		pars = append(pars, companyIds)
+	}
+
+	//关键字搜索
+	if keyword != "" {
+		condition += ` and b.company_name like "%` + keyword + `%" `
+	}
+
+	//是否派点
+	if isAllocation != -1 {
+		condition += ` AND a.is_allocation = ? `
+		pars = append(pars, isAllocation)
+	}
+
+	// 标准非标查询
+	switch formalType {
+	case "标准":
+		condition += ` AND a.source = ? `
+		pars = append(pars, "系统合同")
+	case "非标":
+		condition += ` AND a.source = ? `
+		pars = append(pars, "上传附件")
+	}
+
+	if contractType != "" {
+		condition += ` AND a.contract_type = ? `
+		pars = append(pars, contractType)
+	}
+
+	//默认只查询权益 2023-06-01 之后的合同
+	condition += ` AND c.product_id = ?  AND a.start_date > ? `
+	pars = append(pars, 2, "2023-06-01")
+
+	mapMoneyPoint := make(map[int]float64)
+	//研究员姓名查询
+	if researcherRealName != "" {
+		var conditionAllocation string
+		var parsAllocation []interface{}
+
+		conditionAllocation = " AND  real_name = ? AND money != 0 "
+		parsAllocation = append(parsAllocation, researcherRealName)
+		allocationCompanyContractList, err := cygx.GetCygxAllocationCompanyContractList(conditionAllocation, parsAllocation)
+		if err != nil {
+			br.Msg = "获取失败"
+			br.ErrMsg = "获取失败,GetCygxAllocationCompanyContractListErr:" + err.Error()
+			return
+		}
+		var companyContractIds []int
+		for _, v := range allocationCompanyContractList {
+			companyContractIds = append(companyContractIds, v.CompanyContractId)
+			mapMoneyPoint[v.CompanyContractId] = v.Money
+		}
+		lenCon := len(companyContractIds)
+		if lenCon == 0 {
+			condition += ` AND a.company_contract_id = 0 `
+		} else {
+			condition += ` AND a.company_contract_id IN   (` + utils.GetOrmInReplace(lenCon) + `)`
+			pars = append(pars, companyContractIds)
+		}
+	}
+
+	var list []*cygx.CompanyContractResp
+
+	total, err := cygx.GetCompanyContractCountJoinCompany(condition, pars)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	//列表页数据
+	list, err = cygx.GetCompanyContractListJoinCompany(condition, pars, startSize, pageSize)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	//mapCompamy := make(map[int]string)
+	listLen := len(list)
+	if listLen == 0 {
+		list = make([]*cygx.CompanyContractResp, 0)
+	} else {
+
+		var contractCodes []string
+		var companyContractIds []int
+		for _, v := range list {
+			switch v.Source {
+			case "系统合同":
+				v.FormalType = "标准"
+			case "上传附件":
+				v.FormalType = "非标"
+			}
+			contractCodes = append(contractCodes, v.ContractCode)
+			companyContractIds = append(companyContractIds, v.CompanyContractId)
+			//mapCompamy[v.CompanyId] = strconv.Itoa(v.CompanyContractId)
+		}
+		lencontractCodes := len(contractCodes)
+		if lencontractCodes > 0 {
+			//获取标准合同的ID,这里上面的查询已经关联了三张表,拆分吧。。。
+			condition = ""
+			joinStr := ""
+			pars = make([]interface{}, 0)
+			condition = " AND  a.contract_code  IN (" + utils.GetOrmInReplace(lencontractCodes) + ") "
+			pars = append(pars, contractCodes)
+			listContract, err := contract.GetContractList(condition, joinStr, pars, 0, lencontractCodes)
+			if err != nil {
+				br.Msg = "获取合同列表失败!"
+				br.ErrMsg = "获取合同列表失败,Err:" + err.Error()
+				return
+			}
+
+			mapContractCode := make(map[string]int)
+			for _, v := range listContract {
+				mapContractCode[v.ContractCode] = v.ContractId
+			}
+
+			mapIsGray, err := cygxService.GetMapIsGrayByCompanyContractIds(companyContractIds)
+			if err != nil {
+				br.Msg = "获取合同列表失败!"
+				br.ErrMsg = "获取合同列表失败,GetMapIsGrayByCompanyContractIds Err:" + err.Error()
+				return
+			}
+
+			//合并合同所对应的权限
+			mappermissionName, err := cygxService.GetCompanyContractPermissionNameMapById(companyContractIds)
+			if err != nil {
+				br.Msg = "获取失败"
+				br.ErrMsg = "获取失败,Err:" + err.Error()
+				return
+			}
+
+			for _, v := range list {
+				v.ContractId = mapContractCode[v.ContractCode]
+				v.MoneyPoint = mapMoneyPoint[v.CompanyContractId]
+				v.PermissionName = mappermissionName[v.CompanyContractId]
+				v.IsGray = mapIsGray[v.CompanyContractId]
+			}
+		}
+	}
+
+	page := paging.GetPaging(currentIndex, pageSize, total)
+	resp := cygx.CompanyContractListResp{
+		Paging: page,
+		List:   list,
+	}
+	//导出excel
+	if isExport {
+		CompanyContractListExport(this, resp, br)
+		return
+	}
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = resp
+}
+
+// CompanyContractListExport 导出Excel
+func CompanyContractListExport(this *ContractAllocationController, resp cygx.CompanyContractListResp, br *models.BaseResponse) {
+	dir, err := os.Executable()
+	exPath := filepath.Dir(dir)
+	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
+	xlsxFile := xlsx.NewFile()
+	if err != nil {
+		br.Msg = "生成文件失败"
+		br.ErrMsg = "生成文件失败"
+		return
+	}
+	style := xlsx.NewStyle()
+	alignment := xlsx.Alignment{
+		Horizontal: "center",
+		Vertical:   "center",
+		WrapText:   true,
+	}
+
+	style.Alignment = alignment
+	style.ApplyAlignment = true
+
+	sheel, err := xlsxFile.AddSheet("派点导出数据")
+	if err != nil {
+		br.Msg = "新增Sheet失败"
+		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
+		return
+	}
+	sheel.SetColWidth(0, 0, 30)
+	sheel.SetColWidth(1, 1, 15)
+	sheel.SetColWidth(2, 2, 15)
+	sheel.SetColWidth(3, 3, 18)
+
+	titleRow := sheel.AddRow()
+
+	cellA := titleRow.AddCell()
+	cellA.SetStyle(style)
+	cellA.SetValue("合同编号")
+
+	cellB := titleRow.AddCell()
+	cellB.SetStyle(style)
+	cellB.SetValue("转正类型")
+
+	cellC := titleRow.AddCell()
+	cellC.SetStyle(style)
+	cellC.SetValue("合同类型")
+
+	cellD := titleRow.AddCell()
+	cellD.SetStyle(style)
+	cellD.SetValue("公司名称")
+
+	cellE := titleRow.AddCell()
+	cellE.SetStyle(style)
+	cellE.SetValue("所属销售")
+
+	cellF := titleRow.AddCell()
+	cellF.SetStyle(style)
+	cellF.SetValue("合同金额")
+
+	cellG := titleRow.AddCell()
+	cellG.SetStyle(style)
+	cellG.SetValue("合同期限")
+
+	cellH := titleRow.AddCell()
+	cellH.SetStyle(style)
+	cellH.SetValue("签约套餐")
+
+	cellI := titleRow.AddCell()
+	cellI.SetStyle(style)
+	cellI.SetValue("状态")
+
+	for _, v := range resp.List {
+		dataRow := sheel.AddRow()
+		dataRow.SetHeight(20)
+
+		cellA := dataRow.AddCell()
+		cellA.SetStyle(style)
+		cellA.SetValue(v.ContractCode)
+
+		cellB := dataRow.AddCell()
+		cellB.SetStyle(style)
+		cellB.SetValue(v.FormalType)
+
+		cellC := dataRow.AddCell()
+		cellC.SetStyle(style)
+		cellC.SetValue(v.ContractType)
+
+		cellD := dataRow.AddCell()
+		cellD.SetStyle(style)
+		cellD.SetValue(v.CompanyName)
+
+		cellE := dataRow.AddCell()
+		cellE.SetStyle(style)
+		cellE.SetValue(v.SellerName)
+
+		cellF := dataRow.AddCell()
+		cellF.SetStyle(style)
+		cellF.SetValue(v.Money)
+
+		cellG := dataRow.AddCell()
+		cellG.SetStyle(style)
+		cellG.SetValue(fmt.Sprint(v.StartDate, " ~  ", v.EndDate))
+
+		cellH := dataRow.AddCell()
+		cellH.SetStyle(style)
+		cellH.SetValue(v.PermissionName)
+
+		cellI := dataRow.AddCell()
+		cellI.SetStyle(style)
+		if v.IsAllocation == 1 {
+			cellI.SetValue("已派点")
+		} else {
+			cellI.SetValue("未派点")
+		}
+	}
+	err = xlsxFile.Save(downLoadnFilePath)
+	if err != nil {
+		br.Msg = "保存文件失败"
+		br.ErrMsg = "保存文件失败"
+		return
+	}
+	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
+	downloadFileName := "派点导出数据_" + randStr + ".xlsx"
+	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
+	defer func() {
+		os.Remove(downLoadnFilePath)
+	}()
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "导出成功"
+}
+
+// @Title  详情
+// @Description 获取详情接口
+// @Param   CompanyContractId   query   int  true       "ID"
+// @Param   ShowDetail   query   bool  false      "是否是派点详情展示"
+// @Success Ret=200 {object} cygx.CygxAllocationCompanyContractDetailResp
+// @router /allocation/detail [get]
+func (this *ContractAllocationController) CompanyContracDetail() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	AdminUser := this.SysUser
+	if AdminUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,用户信息为空"
+		br.Ret = 408
+		return
+	}
+	resp := new(cygx.CygxAllocationCompanyContractDetailResp)
+	companyContractId, _ := this.GetInt("CompanyContractId")
+	if companyContractId < 1 {
+		br.Msg = "请输入详情ID"
+		return
+	}
+	showDetail, _ := this.GetBool("ShowDetail", false)
+	contractItem, err := company.GetCompanyContractById(companyContractId)
+	if err != nil {
+		br.Msg = "获取信息失败"
+		br.ErrMsg = "获取合同信息失败,Err:" + err.Error()
+		return
+	}
+	total, err := cygx.GetCygxAllocationCompanyContractCountByCompanyContractId(companyContractId)
+	if err != nil {
+		br.Msg = "获取信息失败"
+		br.ErrMsg = "获取合同信息失败,GetCygxAllocationCompanyContractCountByCompanyContractId Err:" + err.Error()
+		return
+	}
+
+	//var contractPermissionList []*company.ContractPermissionList
+	expMap := map[int]string{0: "(3w)", 1: "(5w)"} // 买方研选价格
+	hasPermissions, e := company.GetCompanyContractPermissionByCompanyContractId(companyContractId)
+	if e != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取合同权限信息失败,Err:" + e.Error()
+		return
+	}
+	hasMap := make(map[int]*company.CompanyContractPermission)
+	for _, p := range hasPermissions {
+		hasMap[p.ChartPermissionId] = p
+	}
+
+	raiPermissions, e := company.GetPermissionLookItemsExt("2", utils.COMPANY_PRODUCT_RAI_NAME)
+	if e != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取权益权限列表失败, Err: " + e.Error()
+		return
+	}
+	mapPermissionNameHave := make(map[string]bool) // 判断合同是否存在某一行业权限种类
+	var expensiveYx int
+	for _, n := range raiPermissions {
+		match := hasMap[n.ChartPermissionId]
+		if match == nil {
+			continue
+		}
+
+		mapPermissionNameHave[n.PermissionName] = true
+		// 买方研选(3w/5w)
+		if n.PermissionName == utils.CHART_PERMISSION_NAME_MF_YANXUAN {
+			expensiveYx = match.ExpensiveYx
+			n.PermissionName += expMap[match.ExpensiveYx]
+			continue
+		}
+	}
+
+	resp.Money = contractItem.Money / 10000
+	//有研选时,对研选套餐类型做文案处理
+	respItemYx := new(cygx.AllocationPermissionListResp)
+	if mapPermissionNameHave[utils.CHART_PERMISSION_NAME_MF_YANXUAN] {
+		var moneyYx float64
+		if expensiveYx == 0 {
+			moneyYx = 3
+		}
+		if expensiveYx == 1 {
+			moneyYx = 5
+		}
+		resp.TotalPointsContent = fmt.Sprint(resp.Money, "W,", "其中", moneyYx, "w默认归属买方研选,请对剩余", resp.Money-moneyYx, "w按照100%进行比值分配")
+		if showDetail {
+			resp.TotalPointsContent = fmt.Sprint(resp.Money, "W")
+		}
+		resp.Money = resp.Money - moneyYx
+		respItemYx.Proportion = 0
+		respItemYx.Money = moneyYx
+		respItemYx.ChartPermissionName = utils.CHART_PERMISSION_NAME_MF_YANXUAN
+		respItemYx.List = append(respItemYx.List, &cygx.AllocationRealNameListResp{utils.CHART_PERMISSION_NAME_MF_YANXUAN, 0, moneyYx})
+	} else {
+		resp.TotalPointsContent = fmt.Sprint(resp.Money, "W")
+	}
+	sysUserList, err := cygx.GetAskEmailList()
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,GetAskEmailList Err: " + err.Error()
+		return
+	}
+	mapPermissionUser := make(map[string][]*cygx.AllocationRealNameListResp)
+
+	var respList []*cygx.AllocationPermissionListResp
+	if total == 0 {
+		for _, v := range sysUserList {
+			if !mapPermissionNameHave[v.ChartPermissionName] {
+				continue
+			}
+			item := new(cygx.AllocationRealNameListResp)
+			item.RealName = v.Name
+			mapPermissionUser[v.ChartPermissionName] = append(mapPermissionUser[v.ChartPermissionName], item)
+		}
+
+		for k, v := range mapPermissionUser {
+			respItem := new(cygx.AllocationPermissionListResp)
+			respItem.ChartPermissionName = k
+			respItem.List = v
+			respList = append(respList, respItem)
+		}
+		if respItemYx.ChartPermissionName != "" {
+			respList = append(respList, respItemYx)
+		}
+	} else {
+		listUser, err := cygx.GetCygxAllocationCompanyContractListById(companyContractId)
+		if err != nil {
+			br.Msg = "获取失败"
+			br.ErrMsg = "获取失败,GetCygxAllocationCompanyContractListById Err: " + err.Error()
+			return
+		}
+		for _, v := range listUser {
+			if showDetail && v.Money == 0 {
+				continue
+			}
+			item := new(cygx.AllocationRealNameListResp)
+			item.RealName = v.RealName
+			item.Money = v.Money
+			item.Proportion = v.Proportion
+			mapPermissionUser[v.ChartPermissionName] = append(mapPermissionUser[v.ChartPermissionName], item)
+		}
+		listPermission, err := cygx.GetCygxAllocationCompanyContractPermissionListById(companyContractId)
+		if err != nil {
+			br.Msg = "获取失败"
+			br.ErrMsg = "获取失败,GetCygxAllocationCompanyContractPermissionListById Err: " + err.Error()
+			return
+		}
+		for _, v := range listPermission {
+			if showDetail && v.Money == 0 {
+				continue
+			}
+			respItem := new(cygx.AllocationPermissionListResp)
+			respItem.ChartPermissionName = v.ChartPermissionName
+			respItem.Money = v.Money
+			respItem.Proportion = v.Proportion
+			respItem.List = mapPermissionUser[v.ChartPermissionName]
+			respList = append(respList, respItem)
+		}
+	}
+	//处理是否置灰
+	mapIsGray, err := cygxService.GetMapIsGrayByCompanyContractIds([]int{companyContractId})
+	if err != nil {
+		br.Msg = "获取合同列表失败!"
+		br.ErrMsg = "获取合同列表失败,GetMapIsGrayByCompanyContractIds Err:" + err.Error()
+		return
+	}
+
+	permissionNameArr := []string{"医药", "消费", "科技", "智造", "策略", "买方研选"}
+	for _, v := range permissionNameArr {
+		for _, v2 := range respList {
+			if v2.ChartPermissionName == v {
+				resp.List = append(resp.List, v2)
+			}
+		}
+	}
+	resp.IsGray = mapIsGray[companyContractId]
+	//resp.List = respList
+	resp.CompanyContractId = companyContractId
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = resp
+}
+
+// @Title 更新派点
+// @Description 更新派点接口
+// @Param	request	body cygx.AddProductInteriorReq true "type json string"
+// @Success 200 {object} "保存成功"
+// @router /allocation/update [post]
+func (this *ContractAllocationController) CompanyContracUpdate() {
+	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
+	}
+	var req cygx.UpdateAllocationCompanyContractReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	companyContractId := req.CompanyContractId
+	if companyContractId == 0 {
+		br.Msg = "参数错误"
+		br.ErrMsg = "参数错误,id不可为空"
+		return
+	}
+	mapIsGray, err := cygxService.GetMapIsGrayByCompanyContractIds([]int{companyContractId})
+	if err != nil {
+		br.Msg = "获取合同列表失败!"
+		br.ErrMsg = "获取合同列表失败,GetMapIsGrayByCompanyContractIds Err:" + err.Error()
+		return
+	}
+	if mapIsGray[companyContractId] {
+		br.Msg = "超过180天,无法修改!"
+		br.ErrMsg = "超过180天,无法修改,companyContractId :" + strconv.Itoa(companyContractId)
+		return
+	}
+
+	contractItem, err := company.GetCompanyContractById(companyContractId)
+	if err != nil {
+		br.Msg = "获取信息失败"
+		br.ErrMsg = "获取合同信息失败,Err:" + err.Error()
+		return
+	}
+	money := contractItem.Money / 10000 // 合同金额,万为单位
+	var moneyAvg float64                // 行业所占合同的平均金额
+	hasPermissions, e := company.GetCompanyContractPermissionByCompanyContractId(companyContractId)
+	if e != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取合同权限信息失败,Err:" + e.Error()
+		return
+	}
+
+	hasMap := make(map[int]*company.CompanyContractPermission)
+	for _, p := range hasPermissions {
+		hasMap[p.ChartPermissionId] = p
+	}
+
+	raiPermissions, e := company.GetPermissionLookItemsExt("2", utils.COMPANY_PRODUCT_RAI_NAME)
+	if e != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取权益权限列表失败, Err: " + e.Error()
+		return
+	}
+	mapPermissionNameHave := make(map[string]bool) // 判断合同是否存在某一行业权限种类
+	for _, n := range raiPermissions {
+		//只计算,医药、消费、科技、智造、策略、买方研选的
+		if n.PermissionName != utils.YI_YAO_NAME && n.PermissionName != utils.XIAO_FEI_NAME && n.PermissionName != utils.KE_JI_NAME && n.PermissionName != utils.ZHI_ZAO_NAME && n.PermissionName != utils.CE_LUE_NAME && n.PermissionName != utils.CHART_PERMISSION_NAME_MF_YANXUAN {
+			continue
+		}
+		match := hasMap[n.ChartPermissionId]
+		if match == nil {
+			continue
+		}
+
+		// 买方研选(3w/5w)
+		if n.PermissionName == utils.CHART_PERMISSION_NAME_MF_YANXUAN {
+			if match.ExpensiveYx == 1 {
+				money = money - 5
+			} else {
+				money = money - 3
+			}
+		} else {
+			mapPermissionNameHave[n.PermissionName] = true
+		}
+	}
+
+	if len(mapPermissionNameHave) > 0 {
+		moneyAvg = money / float64(len(mapPermissionNameHave))
+	}
+
+	list := req.List
+	var items []*cygx.CygxAllocationCompanyContract
+	var itemsPermission []*cygx.CygxAllocationCompanyContractPermission
+
+	var proportionSum float64 // 校验前端传过来的占比使用
+	for _, v := range list {
+		itemPermission := new(cygx.CygxAllocationCompanyContractPermission)
+		itemPermission.CompanyContractId = companyContractId
+		itemPermission.AdminId = sysUser.AdminId
+		itemPermission.AdminName = sysUser.RealName
+		itemPermission.Proportion = v.Proportion
+		itemPermission.Money = v.Money
+		if v.ChartPermissionName != utils.CHART_PERMISSION_NAME_MF_YANXUAN {
+			itemPermission.MoneyAvg = moneyAvg
+			if v.Money < moneyAvg/2 {
+				br.Msg = "单行业占比值不得低于平均值的一半"
+				br.ErrMsg = "单行业占比值不得低于平均值的一半,Err:" + fmt.Sprint(proportionSum)
+				return
+			}
+		}
+		itemPermission.ChartPermissionName = v.ChartPermissionName
+		itemPermission.CreateTime = time.Now()
+		itemPermission.ModifyTime = time.Now()
+		itemsPermission = append(itemsPermission, itemPermission)
+		var userProportionSum float64 // 校验前端传过来的占比使用
+
+		for _, v2 := range v.List {
+			if v2.Proportion < -20 {
+				br.Msg = "研究员占比值不得小于总额的-20%"
+				br.ErrMsg = "研究员占比值不得小于总额的20%,Err:" + fmt.Sprint(proportionSum)
+				return
+			}
+			item := new(cygx.CygxAllocationCompanyContract)
+			item.CompanyContractId = companyContractId
+			item.AdminId = sysUser.AdminId
+			item.AdminName = sysUser.RealName
+			item.Proportion = v2.Proportion
+			item.Money = v2.Money
+			item.RealName = v2.RealName
+			item.ChartPermissionName = v.ChartPermissionName
+			item.CreateTime = time.Now()
+			item.ModifyTime = time.Now()
+			items = append(items, item)
+			proportionSum += v2.Proportion
+			userProportionSum += v2.Proportion
+		}
+		//先添加0.2%的精度校验
+		if userProportionSum > (v.Proportion+0.2) || userProportionSum < (v.Proportion-0.2) {
+			br.Msg = "单行业下的研究员比值之和不等于行业占比值"
+			br.ErrMsg = "单行业下的研究员比值之和不等于行业占比值"
+			return
+		}
+	}
+
+	//先添加0.5%的精度校验
+	if proportionSum > 100.5 || proportionSum < 99.5 {
+		br.Msg = "行业总比值相加不等于100%"
+		br.ErrMsg = "行业总比值相加不等于100%,Err:"
+		return
+	}
+
+	err = cygx.AddAndUpdateCygxAllocationCompanyContract(items, itemsPermission, companyContractId)
+	if err != nil {
+		br.Msg = "操作失败"
+		br.ErrMsg = "操作失败,AddAndUpdateCygxAllocationCompanyContract Err:" + err.Error()
+		return
+	}
+
+	br.Ret = 200
+	br.Success = true
+	br.IsAddLog = true
+	br.Msg = "操作成功"
+}
+
+// @Title 研究员派点统计
+// @Description 研究员派点统计接口
+// @Param   PageSize   query   int  true       "每页数据条数"
+// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
+// @Param   Keyword   query   string  true       "客户名称"
+// @Param   StartDate   query   string  false       "开始日期"
+// @Param   EndDate   query   string  false       "结束日期"
+// @Param   IsExport   query   bool  false       "是否导出excel,默认是false"
+// @Success 200 {object}  cygx.CompanyContractListResp
+// @router /allocation/statistics [get]
+func (this *ContractAllocationController) CompanyContractStatistics() {
+	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
+	}
+
+	keyword := this.GetString("Keyword")
+	startDate := this.GetString("StartDate")
+	endDate := this.GetString("EndDate")
+	if startDate == "" {
+		startDate = "2015-01-01"
+	}
+
+	//是否导出报表
+	isExport, _ := this.GetBool("IsExport")
+
+	var condition string
+
+	var pars []interface{}
+	if endDate != "" {
+		condition += ` AND a.start_date >= ? AND a.start_date <= ? `
+		pars = append(pars, startDate+" 00:00:01", endDate+" 23:59:59")
+	}
+	//根据当前角色来获取查询条件
+	//condition, pars = getQueryParams(condition, pars, sysUser, "c.")
+
+	companyIds, err := cygxService.GetAdminLookUserCompanyIdsBySelf(sysUser)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,GetAdminLookUserCompanyIds Err:" + err.Error()
+		return
+	}
+	lencompanyIds := len(companyIds)
+	if lencompanyIds > 0 {
+		condition += ` AND c.company_id IN (` + utils.GetOrmInReplace(lencompanyIds) + `)`
+		pars = append(pars, companyIds)
+	}
+
+	//关键字搜索
+	if keyword != "" {
+		condition += ` and b.company_name like "%` + keyword + `%" `
+	}
+
+	//默认只查询权益 2023-06-01 之后的合同
+	condition += ` AND c.product_id = ?  AND a.start_date > ?   `
+	pars = append(pars, 2, "2023-01-01")
+
+	//列表页数据
+	listContract, err := cygx.GetCompanyContractListJoinCompany(condition, pars, 0, 1000)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	//return
+	var companyContractIds []int
+	companyContractIdBool := make(map[int]bool)
+	for _, v := range listContract {
+		companyContractIds = append(companyContractIds, v.CompanyContractId)
+	}
+
+	lenArr := len(companyContractIds)
+	mapUserAllocation := make(map[string]float64) // 关联合同
+	mapUserMoney := make(map[string]float64)      // 派点金额
+	mapPermissionAllocation := make(map[string]float64)
+	mapPermissionMoney := make(map[string]float64)
+	mapPermissionMoneyAvg := make(map[string]float64)
+
+	//totalContract := lenArr //所有的关联合同
+	var totalMoney float64 //所有的关联合同的金额 单位万
+	if lenArr > 0 {
+		var conditionAllocation string
+		var parsAllocation []interface{}
+		conditionAllocation = ` AND company_contract_id IN(` + utils.GetOrmInReplace(lenArr) + ` ) `
+		parsAllocation = append(parsAllocation, companyContractIds)
+		allocationCompanyContractList, err := cygx.GetCygxAllocationCompanyContractList(conditionAllocation, parsAllocation)
+		if err != nil {
+			br.Msg = "获取失败"
+			br.ErrMsg = "获取失败,Err:" + err.Error()
+			return
+		}
+		allocationCompanyContractPermissionList, err := cygx.GetCygxAllocationCompanyContractPermissionList(conditionAllocation, parsAllocation)
+		if err != nil {
+			br.Msg = "获取失败"
+			br.ErrMsg = "获取失败,Err:" + err.Error()
+			return
+		}
+		for _, v := range allocationCompanyContractList {
+
+			if v.Proportion != 0 && v.ChartPermissionName != utils.CHART_PERMISSION_NAME_MF_YANXUAN {
+				mapUserAllocation[v.RealName] += 1
+				mapUserMoney[v.RealName] += v.Money
+				mapPermissionAllocation[v.ChartPermissionName] += 1
+				mapPermissionMoney[v.ChartPermissionName] += v.Money
+				totalMoney += v.Money
+				companyContractIdBool[v.CompanyContractId] = true
+			}
+		}
+		for _, v := range allocationCompanyContractPermissionList {
+			mapPermissionMoneyAvg[v.ChartPermissionName] += v.MoneyAvg
+		}
+	}
+
+	sysUserList, err := cygx.GetAskEmailList()
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,GetAskEmailList Err: " + err.Error()
+		return
+	}
+
+	mapPermissionUser := make(map[string][]*cygx.AllocationRealNameStatisticsListResp) //行业分组 map
+
+	for _, v := range sysUserList {
+		item := new(cygx.AllocationRealNameStatisticsListResp)
+		item.RealName = v.Name
+		item.TotalRelatedContract = mapUserAllocation[v.Name]
+		item.TotalDispatchPoint = utils.SubFloatToString(mapUserMoney[v.Name], 2)
+		if item.TotalDispatchPoint == "" {
+			item.TotalDispatchPoint = "0"
+		}
+		//组内占比
+		if mapUserMoney[v.Name] == 0 {
+			item.GroupProportion = ""
+		} else {
+			item.GroupProportion = utils.SubFloatToString(mapUserMoney[v.Name]/mapPermissionMoney[v.ChartPermissionName]*100, 2)
+		}
+		if item.GroupProportion == "" {
+			item.GroupProportion = "0"
+		}
+		item.GroupProportion += "%"
+
+		//部门占比
+		if totalMoney == 0 {
+			item.DepartmentProportion = ""
+		} else {
+			item.DepartmentProportion = utils.SubFloatToString(mapUserMoney[v.Name]/totalMoney*100, 2)
+		}
+		if item.DepartmentProportion == "" {
+			item.DepartmentProportion = "0"
+		}
+		item.DepartmentProportion += "%"
+		mapPermissionUser[v.ChartPermissionName] = append(mapPermissionUser[v.ChartPermissionName], item)
+	}
+
+	for k, v := range mapPermissionUser {
+		lenUser := len(v)
+		item := new(cygx.AllocationRealNameStatisticsListResp)
+		item.RealName = "合计"
+		item.TotalRelatedContract = mapPermissionAllocation[k]
+		item.TotalDispatchPoint = fmt.Sprint(utils.SubFloatToString(mapPermissionMoney[k], 2), "/", mapPermissionMoneyAvg[k])
+		item.GroupProportion = "100%"
+
+		//部门占比
+		if totalMoney == 0 {
+			item.DepartmentProportion = ""
+		} else {
+			item.DepartmentProportion = utils.SubFloatToString(mapPermissionMoney[k]/totalMoney*100, 2)
+		}
+		if item.DepartmentProportion == "" {
+			item.DepartmentProportion = "0"
+		}
+		item.DepartmentProportion += "%"
+		mapPermissionUser[k] = append(mapPermissionUser[k], item)
+
+		item = new(cygx.AllocationRealNameStatisticsListResp)
+		item.RealName = "平均"
+		item.TotalRelatedContract = utils.SubFloatToFloat(mapPermissionAllocation[k]/float64(lenUser), 2)
+		item.TotalDispatchPoint = utils.SubFloatToString(mapPermissionMoney[k]/float64(lenUser), 2)
+
+		//组内占比
+		if mapPermissionMoney[k] == 0 {
+			item.GroupProportion = ""
+		} else {
+			item.GroupProportion = utils.SubFloatToString(1/(float64(len(mapPermissionUser[k])-1))*100, 2)
+		}
+		if item.GroupProportion == "" {
+			item.GroupProportion = "0"
+		}
+		item.GroupProportion += "%"
+
+		// 部门占比
+		if totalMoney == 0 {
+			item.DepartmentProportion = ""
+		} else {
+			item.DepartmentProportion = utils.SubFloatToString(mapPermissionMoney[k]/totalMoney*100/float64(len(mapPermissionUser[k])-1), 2)
+		}
+
+		if item.DepartmentProportion == "" {
+			item.DepartmentProportion = "0"
+		}
+		item.DepartmentProportion += "%"
+		mapPermissionUser[k] = append(mapPermissionUser[k], item)
+	}
+
+	var list []*cygx.AllocationPermissionStatisticsListResp
+	permissionNameArr := []string{"医药", "消费", "科技", "智造", "策略"}
+	for _, v := range permissionNameArr {
+		item := new(cygx.AllocationPermissionStatisticsListResp)
+		item.ChartPermissionName = v
+		item.List = mapPermissionUser[v]
+		list = append(list, item)
+	}
+
+	resp := cygx.CygxAllocationCompanyContractDetailStatisticsResp{
+		List: list,
+	}
+	resp.TotalContract = len(companyContractIdBool)
+	resp.TotalMoney = utils.SubFloatToFloat(totalMoney, 2)
+	//导出excel
+	if isExport {
+		CompanyContractStatisticsExport(this, resp, br)
+		return
+	}
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = resp
+}
+
+// CompanyContractStatisticsExport 导出Excel
+func CompanyContractStatisticsExport(this *ContractAllocationController, resp cygx.CygxAllocationCompanyContractDetailStatisticsResp, br *models.BaseResponse) {
+	dir, err := os.Executable()
+	exPath := filepath.Dir(dir)
+	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
+	xlsxFile := xlsx.NewFile()
+	if err != nil {
+		br.Msg = "生成文件失败"
+		br.ErrMsg = "生成文件失败"
+		return
+	}
+	style := xlsx.NewStyle()
+	alignment := xlsx.Alignment{
+		Horizontal: "center",
+		Vertical:   "center",
+		WrapText:   true,
+	}
+
+	style.Alignment = alignment
+	style.ApplyAlignment = true
+
+	sheel, err := xlsxFile.AddSheet("研究员派点统计")
+	if err != nil {
+		br.Msg = "新增Sheet失败"
+		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
+		return
+	}
+	sheel.SetColWidth(0, 0, 30)
+	sheel.SetColWidth(1, 1, 15)
+	sheel.SetColWidth(2, 2, 15)
+	sheel.SetColWidth(3, 3, 18)
+
+	titleRow := sheel.AddRow()
+
+	cellA := titleRow.AddCell()
+	cellA.SetStyle(style)
+	cellA.SetValue("组别")
+
+	cellB := titleRow.AddCell()
+	cellB.SetStyle(style)
+	cellB.SetValue("研究员")
+
+	cellC := titleRow.AddCell()
+	cellC.SetStyle(style)
+	cellC.SetValue("关联合同")
+
+	cellD := titleRow.AddCell()
+	cellD.SetStyle(style)
+	cellD.SetValue("总派点")
+
+	cellE := titleRow.AddCell()
+	cellE.SetStyle(style)
+	cellE.SetValue("组内占比")
+
+	cellF := titleRow.AddCell()
+	cellF.SetStyle(style)
+	cellF.SetValue("部门占比")
+
+	for _, v := range resp.List {
+		for k2, v2 := range v.List {
+
+			dataRow := sheel.AddRow()
+			dataRow.SetHeight(20)
+
+			cellA := dataRow.AddCell()
+			cellA.SetStyle(style)
+			cellA.SetValue(v.ChartPermissionName)
+			if k2 < len(v.List)-1 {
+				cellA.VMerge = 1
+			}
+
+			cellB := dataRow.AddCell()
+			cellB.SetStyle(style)
+			cellB.SetValue(v2.RealName)
+
+			cellC := dataRow.AddCell()
+			cellC.SetStyle(style)
+			cellC.SetValue(v2.TotalRelatedContract)
+
+			cellD := dataRow.AddCell()
+			cellD.SetStyle(style)
+			cellD.SetValue(v2.TotalDispatchPoint)
+
+			cellE := dataRow.AddCell()
+			cellE.SetStyle(style)
+			cellE.SetValue(v2.GroupProportion)
+
+			cellF := dataRow.AddCell()
+			cellF.SetStyle(style)
+			cellF.SetValue(v2.DepartmentProportion)
+		}
+	}
+
+	titleRow = sheel.AddRow()
+	cellA = titleRow.AddCell()
+	cellA.HMerge = 1
+	cellA.SetStyle(style)
+	cellA.SetValue("部门合计")
+
+	cellB = titleRow.AddCell()
+	cellB.SetStyle(style)
+	cellB.SetValue("")
+
+	cellC = titleRow.AddCell()
+	cellC.SetStyle(style)
+	cellC.SetValue(resp.TotalContract)
+
+	cellD = titleRow.AddCell()
+	cellD.SetStyle(style)
+	cellD.SetValue(resp.TotalMoney)
+
+	cellE = titleRow.AddCell()
+	cellE.SetStyle(style)
+	cellE.SetValue("-")
+
+	cellF = titleRow.AddCell()
+	cellF.SetStyle(style)
+	cellF.SetValue("100%")
+
+	err = xlsxFile.Save(downLoadnFilePath)
+	if err != nil {
+		br.Msg = "保存文件失败"
+		br.ErrMsg = "保存文件失败"
+		return
+	}
+	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
+	downloadFileName := "研究员派点统计_" + randStr + ".xlsx"
+	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
+	defer func() {
+		os.Remove(downLoadnFilePath)
+	}()
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "导出成功"
+}

+ 16 - 0
models/company/company_apply.go

@@ -79,6 +79,22 @@ func GetCompanyContractHistoryList(companyId int, productId string) (items []*Co
 	return
 }
 
+func GetCompanyContractHistoryListByContractCode(contractCode string) (items []*CompanyContractHistory, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT
+				a.*,
+				b.contract_id
+			FROM
+				company_contract AS a
+			LEFT JOIN contract AS b ON a.contract_code = b.contract_code
+			WHERE
+				a.contract_code = ?  AND a.status = 1
+			ORDER BY
+				a.modify_time DESC`
+	_, err = o.Raw(sql, contractCode).QueryRows(&items)
+	return
+}
+
 type CompanyContractDetail struct {
 	CompanyContractId int
 	CompanyId         int       `description:"客户id"`

+ 47 - 1
models/company/company_contract.go

@@ -194,4 +194,50 @@ func GetCompanyContractUpgradePermissionCheckByContractId(companyId, companyCont
 	sql := `SELECT COUNT(1) AS count FROM company_contract_permission AS a WHERE a.company_id=? AND company_contract_id=? AND a.chart_permission_id=? AND a.is_upgrade=? `
 	err = o.Raw(sql, companyId, companyContractId, permissionId, isUpgrade).QueryRow(&count)
 	return
-}
+}
+
+type CompanyContractResp struct {
+	CompanyContractId int       `orm:"column(company_contract_id);pk" description:"客户合同id"`
+	ContractType      string    `description:"合同类型:枚举值:'新签合同','续约合同','补充协议'"`
+	ProductId         int       `description:"产品id"`
+	ProductName       string    `description:"产品名称"`
+	CompanyId         int       `description:"客户id"`
+	CompanyProductId  int       `description:"客户产品id"`
+	ContractCode      string    `description:"合同编码"`
+	StartDate         time.Time `description:"合同开始时间"`
+	EndDate           time.Time `description:"合同结束时间"`
+	Money             float64   `description:"合同金额"`
+	PayMethod         string    `description:"支付方式"`
+	PayChannel        string    `description:"支付渠道"`
+	ImgUrl            string    `description:"合同图片,多个用#隔开"`
+	CreateTime        time.Time `description:"合同创建时间"`
+	ModifyTime        time.Time `description:"合同修改时间"`
+	Status            int       `description:"状态"`
+	Source            string    `description:"合同来源,枚举值:上传附件、系统合同,默认上传附件"`
+	PackageType       int       `description:"套餐类型,0:无,1:大套餐,2:小套餐"`
+	RaiPackageType    int       `description:"权益套餐类型: 0-无; 1-70w大套餐; 2-45w大套餐"`
+}
+
+// 获取合同列表
+func GetCompanyContractList(condition string, pars []interface{}) (items []*CompanyContractResp, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT * FROM company_contract WHERE 1 = 1  `
+
+	if condition != "" {
+		sql += condition
+	}
+	_, err = o.Raw(sql, pars).QueryRows(&items)
+	return
+}
+
+// 获取合同对应的权限列表
+func GetCompanyContractPermissionList(condition string, pars []interface{}) (items []*CompanyContractPermission, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT * FROM company_contract_permission WHERE 1 = 1  `
+
+	if condition != "" {
+		sql += condition
+	}
+	_, err = o.Raw(sql, pars).QueryRows(&items)
+	return
+}

+ 11 - 3
models/cygx/activity_ask_email.go

@@ -5,9 +5,10 @@ import (
 )
 
 type AskEmailRep struct {
-	Name   string `description:"姓名"`
-	Email  string `description:"邮箱"`
-	Mobile string `description:"手机号"`
+	Name                string `description:"姓名"`
+	Email               string `description:"邮箱"`
+	Mobile              string `description:"手机号"`
+	ChartPermissionName string `description:"权限名称"`
 }
 
 func GetAskEmail() (item []*AskEmailRep, err error) {
@@ -16,3 +17,10 @@ func GetAskEmail() (item []*AskEmailRep, err error) {
 	_, err = o.Raw(sql).QueryRows(&item)
 	return
 }
+
+func GetAskEmailList() (item []*AskEmailRep, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := `SELECT * FROM cygx_activity_ask_email WHERE    chart_permission_name != ''  ORDER BY sort  DESC`
+	_, err = o.Raw(sql).QueryRows(&item)
+	return
+}

+ 250 - 0
models/cygx/allocation_company_contract.go

@@ -0,0 +1,250 @@
+package cygx
+
+import (
+	"github.com/beego/beego/v2/client/orm"
+	"time"
+)
+
+// 研究员派点
+type CygxAllocationCompanyContract struct {
+	AllocationCompanyContractId int       `orm:"column(allocation_company_contract_id);pk"`
+	CompanyContractId           int       `description:"合同id"`
+	CreateTime                  time.Time `description:"创建时间"`
+	ModifyTime                  time.Time `description:"更新时间"`
+	AdminId                     int       `description:"操作人ID"`
+	AdminName                   string    `description:"内容"`
+	Proportion                  float64   `description:"占比"`
+	Money                       float64   `description:"金额"`
+	RealName                    string    `description:"研究员姓名"`
+	ChartPermissionName         string    `description:"行业名称"`
+}
+
+// 研究员派点日志
+type CygxAllocationCompanyContractLog struct {
+	AllocationCompanyContractId int       `orm:"column(allocation_company_contract_id);pk"`
+	CompanyContractId           int       `description:"合同id"`
+	CreateTime                  time.Time `description:"创建时间"`
+	ModifyTime                  time.Time `description:"更新时间"`
+	AdminId                     int       `description:"操作人ID"`
+	AdminName                   string    `description:"内容"`
+	Proportion                  float64   `description:"占比"`
+	Money                       float64   `description:"金额"`
+	RealName                    string    `description:"研究员姓名"`
+	ChartPermissionName         string    `description:"行业名称"`
+}
+
+// 行业派点
+type CygxAllocationCompanyContractPermission struct {
+	AllocationCompanyContractId int       `orm:"column(allocation_company_contract_id);pk"`
+	CompanyContractId           int       `description:"合同id"`
+	CreateTime                  time.Time `description:"创建时间"`
+	ModifyTime                  time.Time `description:"更新时间"`
+	AdminId                     int       `description:"操作人ID"`
+	AdminName                   string    `description:"内容"`
+	Proportion                  float64   `description:"占比"`
+	Money                       float64   `description:"金额"`
+	MoneyAvg                    float64   `description:"行业所占合同的平均金额"`
+	ChartPermissionName         string    `description:"行业名称"`
+}
+
+// 行业派点日志
+type CygxAllocationCompanyContractPermissionLog struct {
+	AllocationCompanyContractId int       `orm:"column(allocation_company_contract_id);pk"`
+	CompanyContractId           int       `description:"合同id"`
+	CreateTime                  time.Time `description:"创建时间"`
+	ModifyTime                  time.Time `description:"更新时间"`
+	AdminId                     int       `description:"操作人ID"`
+	AdminName                   string    `description:"内容"`
+	Proportion                  float64   `description:"占比"`
+	Money                       float64   `description:"金额"`
+	MoneyAvg                    float64   `description:"行业所占合同的平均金额"`
+	ChartPermissionName         string    `description:"行业名称"`
+}
+
+// 更新派点信息
+func AddAndUpdateCygxAllocationCompanyContract(items []*CygxAllocationCompanyContract, itemsPermission []*CygxAllocationCompanyContractPermission, companyContractId int) (err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+
+	//组合研究员派点日志结构体
+	var itemsLog []*CygxAllocationCompanyContractLog
+	for _, v := range items {
+		item := new(CygxAllocationCompanyContractLog)
+		item.CompanyContractId = v.CompanyContractId
+		item.AdminId = v.AdminId
+		item.CompanyContractId = v.CompanyContractId
+		item.AdminName = v.AdminName
+		item.RealName = v.RealName
+		item.ChartPermissionName = v.ChartPermissionName
+		item.Proportion = v.Proportion
+		item.Money = v.Money
+		item.Money = v.Money
+		item.CreateTime = time.Now()
+		item.ModifyTime = time.Now()
+		itemsLog = append(itemsLog, item)
+	}
+
+	//组合行业派点日志结构体
+	var itemsPermissionLog []*CygxAllocationCompanyContractPermissionLog
+	for _, v := range itemsPermission {
+		item := new(CygxAllocationCompanyContractPermissionLog)
+		item.CompanyContractId = v.CompanyContractId
+		item.AdminId = v.AdminId
+		item.CompanyContractId = v.CompanyContractId
+		item.AdminName = v.AdminName
+		item.ChartPermissionName = v.ChartPermissionName
+		item.Proportion = v.Proportion
+		item.Money = v.Money
+		item.MoneyAvg = v.MoneyAvg
+		item.CreateTime = time.Now()
+		item.ModifyTime = time.Now()
+		itemsPermissionLog = append(itemsPermissionLog, item)
+	}
+
+	//删除原有的研究员派点信息
+	sql := `DELETE FROM cygx_allocation_company_contract WHERE company_contract_id = ?`
+	_, err = to.Raw(sql, companyContractId).Exec()
+	if err != nil {
+		return
+	}
+	//删除原有的行业派点信息
+	sql = `	DELETE FROM cygx_allocation_company_contract_permission WHERE company_contract_id = ?`
+	_, err = to.Raw(sql, companyContractId).Exec()
+	if err != nil {
+		return
+	}
+
+	//批量添加研究员派点信息
+	_, err = to.InsertMulti(len(items), items)
+	if err != nil {
+		return
+	}
+
+	_, err = to.InsertMulti(len(itemsLog), itemsLog)
+	if err != nil {
+		return
+	}
+
+	//批量添加行业派点信息
+	_, err = to.InsertMulti(len(itemsPermission), itemsPermission)
+	if err != nil {
+		return
+	}
+
+	_, err = to.InsertMulti(len(itemsPermissionLog), itemsPermissionLog)
+	if err != nil {
+		return
+	}
+
+	ow := orm.NewOrm()
+	sqlW := `UPDATE company_contract SET is_allocation=1   WHERE company_contract_id=? `
+	_, err = ow.Raw(sqlW, companyContractId).Exec()
+
+	return
+}
+
+type UpdateAllocationCompanyContractReq struct {
+	CompanyContractId int `description:"合同ID"`
+	List              []*AllocationPermissionListResp
+}
+
+type CygxAllocationCompanyContractDetailResp struct {
+	CompanyContractId  int     `description:"合同ID"`
+	Money              float64 `description:"金额(单位万)"`
+	TotalPointsContent string  `description:"总点数描述"`
+	IsGray             bool    `description:"是否置灰"`
+	List               []*AllocationPermissionListResp
+}
+
+// 行业
+type AllocationPermissionListResp struct {
+	ChartPermissionName string  `description:"行业名称"`
+	Proportion          float64 `description:"占比"`
+	Money               float64 `description:"金额(单位万)"`
+	MoneyAvg            float64 `description:"行业所占合同的平均金额"`
+	List                []*AllocationRealNameListResp
+}
+
+// 行业
+type AllocationRealNameListResp struct {
+	RealName   string  `description:"研究员姓名"`
+	Proportion float64 `description:"占比"`
+	Money      float64 `description:"金额(单位万)"`
+}
+
+// 获取数量
+func GetCygxAllocationCompanyContractCountByCompanyContractId(companyContractId int) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_allocation_company_contract WHERE company_contract_id = ? `
+	err = o.Raw(sqlCount, companyContractId).QueryRow(&count)
+	return
+}
+
+// 研究员列表
+func GetCygxAllocationCompanyContractListById(companyContractId int) (items []*CygxAllocationCompanyContract, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := `SELECT * FROM cygx_allocation_company_contract WHERE company_contract_id = ? `
+	_, err = o.Raw(sql, companyContractId).QueryRows(&items)
+	return
+}
+
+// 研究员列表
+func GetCygxAllocationCompanyContractList(condition string, pars []interface{}) (items []*CygxAllocationCompanyContract, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := `SELECT * FROM cygx_allocation_company_contract as art WHERE 1= 1 `
+	if condition != "" {
+		sql += condition
+	}
+	_, err = o.Raw(sql, pars).QueryRows(&items)
+	return
+}
+
+// 行业列表
+func GetCygxAllocationCompanyContractPermissionListById(companyContractId int) (items []*AllocationPermissionListResp, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := ` SELECT * FROM cygx_allocation_company_contract_permission WHERE company_contract_id = ? `
+	_, err = o.Raw(sql, companyContractId).QueryRows(&items)
+	return
+}
+
+// 行业列表
+func GetCygxAllocationCompanyContractPermissionList(condition string, pars []interface{}) (items []*AllocationPermissionListResp, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := ` SELECT * FROM cygx_allocation_company_contract_permission  as art WHERE 1= 1 `
+	if condition != "" {
+		sql += condition
+	}
+	_, err = o.Raw(sql, pars).QueryRows(&items)
+	return
+}
+
+type CygxAllocationCompanyContractDetailStatisticsResp struct {
+	List          []*AllocationPermissionStatisticsListResp
+	TotalContract int     `description:"关联合同总计"`
+	TotalMoney    float64 `description:"总派点总计"`
+}
+
+// 行业
+type AllocationPermissionStatisticsListResp struct {
+	ChartPermissionName string `description:"行业名称"`
+	List                []*AllocationRealNameStatisticsListResp
+}
+
+// 行业
+type AllocationRealNameStatisticsListResp struct {
+	RealName             string  `description:"研究员姓名"`
+	TotalRelatedContract float64 `description:"关联合同"`
+	TotalDispatchPoint   string  `description:"总派点"`
+	GroupProportion      string  `description:"组内占比"`
+	DepartmentProportion string  `description:"部门占比"`
+}

+ 92 - 0
models/cygx/company_contract.go

@@ -0,0 +1,92 @@
+package cygx
+
+import (
+	"github.com/beego/beego/v2/client/orm"
+	"github.com/rdlucklib/rdluck_tools/paging"
+)
+
+// 增量客户统计报表列表数据结构
+type CompanyContractResp struct {
+	CompanyContractId int     `description:"合同id"`
+	ContractType      string  `description:"合同类型"`
+	CompanyId         int     `description:"企业客户id"`
+	CompanyName       string  `description:"企业客户名称"`
+	ContractCode      string  `description:"合同编码"`
+	StartDate         string  `description:"合同开始日期"`
+	EndDate           string  `description:"合同结束日期"`
+	Money             float64 `description:"合同金额"`
+	CreateTime        string  `description:"合同创建时间"`
+	ModifyTime        string  `description:"合同修改时间"`
+	SellerId          int     `description:"归属销售id"`
+	SellerName        string  `description:"归属销售名称"`
+	IsAllocation      int     `description:"是否派点: 0-未派点; 1-已派点"`
+	Source            string  `description:"合同来源,枚举值:上传附件、系统合同,默认上传附件"`
+	FormalType        string  `description:"转正类型,枚举值: 标准、非标"`
+	IsGray            bool    `description:"是否置灰"`
+	ContractId        int     `description:"合同唯一id"`
+	MoneyPoint        float64 `description:"派点金额"`
+	PermissionName    string  `description:"权限名"`
+}
+
+// 增量客户统计报表返回类
+type CompanyContractListResp struct {
+	Paging *paging.PagingItem `description:"分页数据"`
+	List   []*CompanyContractResp
+}
+
+// 获取存量客户未续约报表列表统计数据(根据合同来展示)
+func GetCompanyContractCountJoinCompany(condition string, pars []interface{}) (total int, err error) {
+	o := orm.NewOrm()
+	sql := ` SELECT
+	count(*) AS count 
+FROM
+	(
+	SELECT
+		COUNT(*) 
+	FROM
+		company_contract a
+		JOIN company b ON a.company_id = b.company_id
+		JOIN company_product c ON a.company_id = c.company_id 
+		AND a.product_id = c.product_id 
+	WHERE
+		a.STATUS = 1 
+		` + condition + `
+	GROUP BY
+	a.company_contract_id 
+	) b`
+	err = o.Raw(sql, pars).QueryRow(&total)
+	return
+}
+
+// 获取存量客户未续约报表列表数据(根据合同来展示)
+func GetCompanyContractListJoinCompany(condition string, pars []interface{}, startSize, pageSize int) (items []*CompanyContractResp, err error) {
+	o := orm.NewOrm()
+	//
+	//sql := `SELECT a.*,b.region_type,c.seller_id,c.seller_name,b.company_name FROM company_contract a
+	//	 JOIN company b ON a.company_id = b.company_id
+	//	 JOIN company_product c ON a.company_id = c.company_id and a.product_id=c.product_id WHERE a.status = 1 `
+	//
+	//if condition != "" {
+	//	sql += condition
+	//}
+	//sql += " order by a.start_date desc "
+	//sql = `select *,count(*) count from (` + sql + `) b group by company_id  order by end_date asc,company_id desc limit ?,?`
+
+	sql := ` SELECT
+			a.*,
+			b.region_type,
+			c.seller_id,
+			c.seller_name,
+			b.company_name 
+		FROM
+			company_contract a
+			JOIN company b ON a.company_id = b.company_id
+			JOIN company_product c ON a.company_id = c.company_id 
+			AND a.product_id = c.product_id 
+		WHERE
+			a.STATUS = 1`
+	sql += condition
+	sql += `GROUP BY a.company_contract_id ORDER BY a.start_date DESC   , a.company_contract_id DESC  	LIMIT  ?,? `
+	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
+	return
+}

+ 4 - 0
models/db.go

@@ -448,6 +448,10 @@ func initCygx() {
 		new(cygx.CygxResourceDataIndustrialGroupManagement),
 		new(cygx.CygxResourceDataIndustrialGroupSubject),
 		new(cygx.CygxYanxuanSpecialAuthor),
+		new(cygx.CygxAllocationCompanyContract),
+		new(cygx.CygxAllocationCompanyContractLog),
+		new(cygx.CygxAllocationCompanyContractPermission),
+		new(cygx.CygxAllocationCompanyContractPermissionLog),
 	)
 }
 

+ 45 - 0
routers/commentsRouter.go

@@ -1339,6 +1339,42 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:ContractAllocationController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:ContractAllocationController"],
+        beego.ControllerComments{
+            Method: "CompanyContractList",
+            Router: `/allocation/company_contract_list`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:ContractAllocationController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:ContractAllocationController"],
+        beego.ControllerComments{
+            Method: "CompanyContracDetail",
+            Router: `/allocation/detail`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:ContractAllocationController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:ContractAllocationController"],
+        beego.ControllerComments{
+            Method: "CompanyContractStatistics",
+            Router: `/allocation/statistics`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:ContractAllocationController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:ContractAllocationController"],
+        beego.ControllerComments{
+            Method: "CompanyContracUpdate",
+            Router: `/allocation/update`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:IndustrialAnalystController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:IndustrialAnalystController"],
         beego.ControllerComments{
             Method: "IndustrialAnalystAdd",
@@ -8341,6 +8377,15 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:CompanyApplyController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:CompanyApplyController"],
+        beego.ControllerComments{
+            Method: "ApplyContractHistoryDetail",
+            Router: `/apply/contract/history/detail`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:CompanyApplyController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:CompanyApplyController"],
         beego.ControllerComments{
             Method: "ApplyContractHistoryList",

+ 1 - 0
routers/router.go

@@ -152,6 +152,7 @@ func init() {
 				&cygx.BannerCoAntroller{},
 				&cygx.TagManagementController{},
 				&cygx.YanxuanSpecialController{},
+				&cygx.ContractAllocationController{},
 			),
 		),
 		web.NSNamespace("/advisory",

+ 3 - 2
services/company_apply/company_approval.go

@@ -391,7 +391,7 @@ func Approved(approvalRecord *contract.ContractApprovalRecord, opUser *system.Ad
 				// 处理权益客户的身份信息()
 				cygxService.UpdateCygxCompanyUserType(recordInfo.CompanyContractId)
 
-				if recordInfo.ApplyMethod == 1{
+				if recordInfo.ApplyMethod == 1 {
 					//获取合同信息
 					contractInfo, tmpErr := company.GetCompanyContractDetail(recordInfo.CompanyId, recordInfo.ProductId, recordInfo.CompanyContractId)
 					if tmpErr != nil {
@@ -420,7 +420,8 @@ func Approved(approvalRecord *contract.ContractApprovalRecord, opUser *system.Ad
 				//客户研选行业转正时(王芳审批通过),模板消息提醒汪洋
 				services.AddCompanyApprovalMessageWangYang(recordInfo.CompanyId, recordInfo.CompanyContractId, recordInfo.ApplyRealName, companyInfo.CompanyName)
 
-				go cygxService.YanXuanCompanyApproval(recordInfo.CompanyId) //研选审批通过的时候研选扣点更新
+				cygxService.YanXuanCompanyApproval(recordInfo.CompanyId)                           //研选审批通过的时候研选扣点更新
+				cygxService.HandleAllocationCompanyContractByYanXuan(recordInfo.CompanyContractId) //如果合同只有研选的时候,自动处理派点
 
 			}
 		}()

+ 256 - 0
services/cygx/contract_allocation.go

@@ -0,0 +1,256 @@
+package cygx
+
+import (
+	"errors"
+	"fmt"
+	"hongze/hz_crm_api/models"
+	"hongze/hz_crm_api/models/company"
+	"hongze/hz_crm_api/models/cygx"
+	"hongze/hz_crm_api/services/alarm_msg"
+	"hongze/hz_crm_api/utils"
+	"strings"
+	"time"
+)
+
+// GetCompanyContractPermissionNameMapById 获取合并之后的合同所对应的权限种类名称
+func GetCompanyContractPermissionNameMapById(companyContractIds []int) (mapContractResp map[int]string, err error) {
+	//return
+	lenArr := len(companyContractIds)
+	if lenArr == 0 {
+		return
+	}
+	var condition string
+	var pars []interface{}
+
+	condition += " AND  company_contract_id IN (" + utils.GetOrmInReplace(lenArr) + ")"
+	pars = append(pars, companyContractIds)
+
+	companyContractList, e := company.GetCompanyContractList(condition, pars)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetCompanyContractList, Err: " + e.Error())
+		return
+	}
+
+	permissionList, e := models.GetChartPermissionList()
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetChartPermissionList, Err: " + e.Error())
+		return
+	}
+	mappermissionName := make(map[int]string)
+	for _, v := range permissionList {
+		mappermissionName[v.ChartPermissionId] = v.Remark
+	}
+
+	mapContractIdPerssion := make(map[int]string) //单个合同ID所对应的套餐或者权限名称
+	for _, v := range companyContractList {
+		if v.RaiPackageType == 1 {
+			mapContractIdPerssion[v.CompanyContractId] = "70w套餐"
+		}
+		if v.RaiPackageType == 2 {
+			mapContractIdPerssion[v.CompanyContractId] = "45w套餐"
+		}
+	}
+
+	companyContractPermissionList, e := company.GetCompanyContractPermissionList(condition, pars)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetCompanyContractPermissionList, Err: " + e.Error())
+		return
+	}
+
+	mapIsUpgrade := make(map[string]bool) //合同ID对应的行业是否有升级
+	for _, v := range companyContractPermissionList {
+		//如果开通的不是整个套餐,那么就做单独的子权限处理
+		if strings.Count(mapContractIdPerssion[(v.CompanyContractId)], "w套餐") == 0 {
+			if v.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
+				if v.ExpensiveYx == 1 {
+					mapContractIdPerssion[(v.CompanyContractId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(5w),"
+				} else {
+					mapContractIdPerssion[(v.CompanyContractId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(3w),"
+				}
+			} else {
+				mapContractIdPerssion[(v.CompanyContractId)] += mappermissionName[v.ChartPermissionId] + ","
+				if v.IsUpgrade == 1 {
+					//合同ID,权限名称形成唯一的主键索引
+					perssionName := mappermissionName[v.ChartPermissionId]
+					perssionName = strings.Replace(perssionName, "(客观)", "", -1)
+					perssionName = strings.Replace(perssionName, "(主观)", "", -1)
+					mapIsUpgrade[fmt.Sprint(v.CompanyContractId, "perssionName", perssionName)] = true
+				}
+			}
+		} else {
+			if v.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
+				if v.ExpensiveYx == 1 {
+					mapContractIdPerssion[(v.CompanyContractId)] += "," + utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(5w)"
+				} else {
+					mapContractIdPerssion[(v.CompanyContractId)] += "," + utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(3w)"
+				}
+			}
+		}
+	}
+	//合并客观权限
+	for k, v := range mapContractIdPerssion {
+		perssionName := v
+		if strings.Count(v, utils.YI_YAO_NAME) == 2 {
+			perssionName = strings.Replace(perssionName, "医药(主观)", "医药", -1)
+			perssionName = strings.Replace(perssionName, "医药(客观)", "", -1)
+		}
+		if strings.Count(v, utils.XIAO_FEI_NAME) == 2 {
+			perssionName = strings.Replace(perssionName, "消费(主观)", "消费", -1)
+			perssionName = strings.Replace(perssionName, "消费(客观)", "", -1)
+		}
+		if strings.Count(v, utils.KE_JI_NAME) == 2 {
+			perssionName = strings.Replace(perssionName, "科技(主观)", "科技", -1)
+			perssionName = strings.Replace(perssionName, "科技(客观)", "", -1)
+		}
+		if strings.Count(v, utils.ZHI_ZAO_NAME) == 2 {
+			perssionName = strings.Replace(perssionName, "智造(主观)", "智造", -1)
+			perssionName = strings.Replace(perssionName, "智造(客观)", "", -1)
+		}
+
+		perssionName = strings.TrimRight(perssionName, ",")
+		mapContractIdPerssion[k] = perssionName
+	}
+	mapContractResp = make(map[int]string, 0)
+
+	//过滤多余的","
+	for k, v := range mapContractIdPerssion {
+		sliceName := strings.Split(v, ",")
+		var nameArr []string
+		for _, vName := range sliceName {
+			if vName == "" {
+				continue
+			}
+			if mapIsUpgrade[fmt.Sprint(k, "perssionName", vName)] {
+				vName += "(升级)"
+			}
+			nameArr = append(nameArr, vName)
+		}
+		mapContractResp[k] = strings.Join(nameArr, ",")
+	}
+	return
+}
+
+// 判断合同审核通过时间是否超过九十天
+func GetMapIsGrayByCompanyContractIds(companyContractIds []int) (mapResp map[int]bool, err error) {
+	lenArr := len(companyContractIds)
+	if lenArr == 0 {
+		return
+	}
+	var condition string
+	var pars []interface{}
+	pars = make([]interface{}, 0)
+	condition = " AND  company_contract_id IN (" + utils.GetOrmInReplace(lenArr) + ")    GROUP BY company_contract_id ORDER BY create_time DESC  "
+	pars = append(pars, companyContractIds)
+	companyContractPermissionList, e := company.GetCompanyContractPermissionList(condition, pars)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetCompanyContractPermissionList, Err: " + e.Error())
+		return
+	}
+	//超过九十天就置灰
+	timeInit := time.Now().AddDate(0, 0, -180)
+	mapResp = make(map[int]bool, 0)
+	for _, v := range companyContractPermissionList {
+		if v.CreateTime.Before(timeInit) {
+			mapResp[v.CompanyContractId] = true
+		}
+	}
+	return
+}
+
+//func init3() {
+//	var condition string
+//	var pars []interface{}
+//	//默认只查询权益 2023-06-01 之后的合同
+//	condition += ` AND c.product_id = ?  AND a.start_date > ? `
+//	pars = append(pars, 2, "2023-06-01")
+//
+//	//列表页数据
+//	list, err := cygx.GetCompanyContractListJoinCompany(condition, pars, 0, 1000)
+//	if err != nil {
+//		fmt.Println(err)
+//		return
+//	}
+//
+//	for _, v := range list {
+//		fmt.Println(v.CompanyContractId)
+//		HandleAllocationCompanyContractByYanXuan(v.CompanyContractId)
+//	}
+//
+//	fmt.Println(len(list))
+//}
+
+// 如果合同只有研选的时候,自动处理派点
+func HandleAllocationCompanyContractByYanXuan(companyContractId int) (err error) {
+	defer func() {
+		if err != nil {
+			fmt.Println(err)
+			go alarm_msg.SendAlarmMsg(fmt.Sprint("如果合同只有研选的时候,自动处理派点失败,Err:", err.Error(), "companyContractId", companyContractId), 2)
+		}
+	}()
+	var condition string
+	var pars []interface{}
+	pars = make([]interface{}, 0)
+	condition = " AND  company_contract_id = ?  "
+	pars = append(pars, companyContractId)
+	companyContractPermissionList, e := company.GetCompanyContractPermissionList(condition, pars)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetCompanyContractPermissionList, Err: " + e.Error())
+		return
+	}
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetCygxAllocationCompanyContractPermissionListById, Err: " + e.Error())
+		return
+	}
+
+	if len(companyContractPermissionList) > 1 {
+		return
+	}
+	var expensiveYxmoney float64
+	for _, v := range companyContractPermissionList {
+		if v.ChartPermissionId != utils.CHART_PERMISSION_ID_YANXUAN {
+			err = errors.New("没有发现研选权限: ")
+			return
+		}
+		if v.ExpensiveYx == 1 {
+			expensiveYxmoney = 5
+		} else {
+			expensiveYxmoney = 3
+		}
+	}
+
+	var items []*cygx.CygxAllocationCompanyContract
+	var itemsPermission []*cygx.CygxAllocationCompanyContractPermission
+
+	itemPermission := new(cygx.CygxAllocationCompanyContractPermission)
+	itemPermission.CompanyContractId = companyContractId
+	//itemPermission.AdminId = sysUser.AdminId
+	//itemPermission.AdminName = sysUser.RealName
+	itemPermission.Proportion = 0
+	itemPermission.Money = expensiveYxmoney
+	itemPermission.MoneyAvg = 0
+	itemPermission.ChartPermissionName = utils.CHART_PERMISSION_NAME_MF_YANXUAN
+	itemPermission.CreateTime = time.Now()
+	itemPermission.ModifyTime = time.Now()
+	itemsPermission = append(itemsPermission, itemPermission)
+
+	item := new(cygx.CygxAllocationCompanyContract)
+	item.CompanyContractId = companyContractId
+	//item.AdminId = sysUser.AdminId
+	//item.AdminName = sysUser.RealName
+	item.Proportion = 0
+	item.Money = expensiveYxmoney
+	item.RealName = utils.CHART_PERMISSION_NAME_MF_YANXUAN
+	item.ChartPermissionName = utils.CHART_PERMISSION_NAME_MF_YANXUAN
+	item.CreateTime = time.Now()
+	item.ModifyTime = time.Now()
+	items = append(items, item)
+
+	e = cygx.AddAndUpdateCygxAllocationCompanyContract(items, itemsPermission, companyContractId)
+	if e != nil {
+		err = errors.New("AddAndUpdateCygxAllocationCompanyContract, Err: " + e.Error())
+		return
+	}
+
+	return
+
+}