ziwen 2 years ago
parent
commit
5ba20ad99d

+ 338 - 166
controller/contract/pre_register.go

@@ -7,10 +7,14 @@ import (
 	"hongze/fms_api/controller/resp"
 	"hongze/fms_api/global"
 	"hongze/fms_api/models/base"
+	"hongze/fms_api/models/crm"
 	"hongze/fms_api/models/fms"
 	"hongze/fms_api/models/system"
+	crmService "hongze/fms_api/services/crm"
 	fmsService "hongze/fms_api/services/fms"
 	"hongze/fms_api/utils"
+	"strconv"
+	"strings"
 	"time"
 )
 
@@ -26,68 +30,68 @@ type PreRegisterController struct{}
 // @Param   SortType   		query   string  true       "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
 // @Success 200 {object} fms.ContractRegisterItem
 // @router /contract/pre_pay/list [get]
-func (rg *PrePaymentController) List1(c *gin.Context) {
-	var req fms.PrePayListReq
-	if e := c.BindQuery(&req); e != nil {
-		err, ok := e.(validator.ValidationErrors)
-		if !ok {
-			resp.FailData("参数解析失败", "Err:"+e.Error(), c)
-			return
-		}
-		resp.FailData("参数解析失败", err.Translate(global.Trans), c)
-		return
-	}
-
-	cond := `1 = 1`
-	pars := make([]interface{}, 0)
-	// 客户姓名/销售
-	if req.Keyword != "" {
-		kw := "%" + req.Keyword + "%"
-		cond += ` AND (company_name LIKE ? OR seller_name LIKE ? )`
-		pars = append(pars, kw, kw)
-	}
-	if req.StartDate != "" && req.EndDate != "" {
-		st := fmt.Sprint(req.StartDate, " 00:00:00")
-		ed := fmt.Sprint(req.EndDate, " 23:59:59")
-		cond += ` AND (create_time BETWEEN ? AND ?)`
-		pars = append(pars, st, ed)
-	}
-
-	// 货币列表
-	currencyOB := new(fms.CurrencyUnit)
-	currencyCond := `enable = 1`
-	currencyPars := make([]interface{}, 0)
-	currencyList, e := currencyOB.List(currencyCond, currencyPars)
-	if e != nil {
-		resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
-		return
-	}
-	unitMap := make(map[string]string)
-	for i := range currencyList {
-		unitMap[currencyList[i].Code] = currencyList[i].UnitName
-	}
-
-	page := new(base.Page)
-	page.SetPageSize(req.PageSize)
-	page.SetCurrent(req.Current)
-	sortTypeMap := map[int]bool{0: false, 1: true, 2: false}
-	page.AddOrderItem(base.OrderItem{Column: "create_time", Asc: sortTypeMap[req.SortType]})
-
-	total, list, e := fms.GetPrePayItemPageList(page, cond, pars)
-	if e != nil {
-		resp.FailMsg("获取失败", "获取预登记列表失败, Err: "+e.Error(), c)
-		return
-	}
-	for i := range list {
-		list[i].UnitName = unitMap[list[i].CurrencyUnit]
-	}
-
-	page.SetTotal(total)
-	baseData := new(base.BaseData)
-	baseData.SetPage(page)
-	baseData.SetList(list)
-	resp.OkData("获取成功", baseData, c)
-}
+//func (rg *PrePaymentController) List1(c *gin.Context) {
+//	var req fms.PrePayListReq
+//	if e := c.BindQuery(&req); e != nil {
+//		err, ok := e.(validator.ValidationErrors)
+//		if !ok {
+//			resp.FailData("参数解析失败", "Err:"+e.Error(), c)
+//			return
+//		}
+//		resp.FailData("参数解析失败", err.Translate(global.Trans), c)
+//		return
+//	}
+//
+//	cond := `1 = 1`
+//	pars := make([]interface{}, 0)
+//	// 客户姓名/销售
+//	if req.Keyword != "" {
+//		kw := "%" + req.Keyword + "%"
+//		cond += ` AND (company_name LIKE ? OR seller_name LIKE ? )`
+//		pars = append(pars, kw, kw)
+//	}
+//	if req.StartDate != "" && req.EndDate != "" {
+//		st := fmt.Sprint(req.StartDate, " 00:00:00")
+//		ed := fmt.Sprint(req.EndDate, " 23:59:59")
+//		cond += ` AND (create_time BETWEEN ? AND ?)`
+//		pars = append(pars, st, ed)
+//	}
+//
+//	// 货币列表
+//	currencyOB := new(fms.CurrencyUnit)
+//	currencyCond := `enable = 1`
+//	currencyPars := make([]interface{}, 0)
+//	currencyList, e := currencyOB.List(currencyCond, currencyPars)
+//	if e != nil {
+//		resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
+//		return
+//	}
+//	unitMap := make(map[string]string)
+//	for i := range currencyList {
+//		unitMap[currencyList[i].Code] = currencyList[i].UnitName
+//	}
+//
+//	page := new(base.Page)
+//	page.SetPageSize(req.PageSize)
+//	page.SetCurrent(req.Current)
+//	sortTypeMap := map[int]bool{0: false, 1: true, 2: false}
+//	page.AddOrderItem(base.OrderItem{Column: "create_time", Asc: sortTypeMap[req.SortType]})
+//
+//	total, list, e := fms.GetPrePayItemPageList(page, cond, pars)
+//	if e != nil {
+//		resp.FailMsg("获取失败", "获取预登记列表失败, Err: "+e.Error(), c)
+//		return
+//	}
+//	for i := range list {
+//		list[i].UnitName = unitMap[list[i].CurrencyUnit]
+//	}
+//
+//	page.SetTotal(total)
+//	baseData := new(base.BaseData)
+//	baseData.SetPage(page)
+//	baseData.SetList(list)
+//	resp.OkData("获取成功", baseData, c)
+//}
 
 // InvoiceList
 // @Title 开票/到款列表
@@ -141,7 +145,7 @@ func (rg *PreRegisterController) List(c *gin.Context) {
 	sortTypeMap := map[int]bool{0: false, 1: true, 2: false}
 	page.AddOrderItem(base.OrderItem{Column: "create_time", Asc: sortTypeMap[0]})
 
-	total, list, e := fms.GetPrePayItemPageList(page, cond, pars)
+	total, list, e := fms.GetContractInvoiceItemPageList(page, cond, pars)
 	if e != nil {
 		resp.FailMsg("获取失败", "获取预登记列表失败, Err: "+e.Error(), c)
 		return
@@ -162,9 +166,9 @@ func (rg *PreRegisterController) List(c *gin.Context) {
 // @Description 新增到款预登记
 // @Param	request  body  fms.PrepayAddReq  true  "type json string"
 // @Success 200 string "操作成功"
-// @router /contract/pre_pay/add [post]
-func (rg *PrePaymentController) Add(c *gin.Context) {
-	req := new(fms.PrepayAddReq)
+// @router /contract/pre_register/add [post]
+func (rg *PreRegisterController) Add(c *gin.Context) {
+	req := new(fms.PreRegisterAddReq)
 	err := c.ShouldBind(&req)
 	if err != nil {
 		errs, ok := err.(validator.ValidationErrors)
@@ -179,82 +183,164 @@ func (rg *PrePaymentController) Add(c *gin.Context) {
 	adminInfo := claims.(*system.SysAdmin)
 
 	// 日期校验
-	startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
-	if e != nil {
-		resp.FailMsg("约定开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
-		return
-	}
-	endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
-	if e != nil {
-		resp.FailMsg("约定结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
-		return
+	var startDate, endDate time.Time
+	if req.StartDate != "" && req.EndDate != "" {
+		startDate, err = time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
+		if err != nil {
+			resp.FailMsg("约定开始日期格式有误", "合同开始日期格式有误, Err: "+err.Error(), c)
+			return
+		}
+		endDate, err = time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
+		if err != nil {
+			resp.FailMsg("约定结束日期格式有误", "合同结束日期格式有误, Err: "+err.Error(), c)
+			return
+		}
 	}
 
-	// 货币及汇率
-	rateList, e := fmsService.GetTodayCurrencyRateList()
+	// 获取销售分组信息
+	sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
 	if e != nil {
-		resp.FailMsg("操作失败", "获取今日货币汇率失败, Err: "+e.Error(), c)
+		resp.FailData("获取销售失败", "Err:"+e.Error(), c)
 		return
 	}
-	var rate float64
-	for i := range rateList {
-		if req.CurrencyUnit == rateList[i].Code {
-			rate = rateList[i].RMBRate
-			break
-		}
+	sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
+	for i := range sellerList {
+		sellerMap[sellerList[i].SellerId] = sellerList[i]
 	}
-	if rate <= 0 {
-		resp.FailMsg("操作失败", "货币汇率信息有误", c)
+
+	admin := new(crm.Admin)
+	sellerIds := strings.Split(req.SellerIds, ",")
+	if len(sellerIds) > 2 {
+		resp.Fail("最多只能选择两个销售", c)
 		return
 	}
-
-	payDate, err := time.Parse(utils.FormatDate, req.PaymentDate)
+	var pars []interface{}
+	cond := ` admin_id in (?) `
+	pars = append(pars, sellerIds)
+	sellers, e := admin.List(cond, pars)
 	if e != nil {
-		resp.FailMsg("日期转换失败", "日期转换失败, Err: "+e.Error(), c)
+		resp.FailMsg("获取销售信息失败", "获取销售信息失败, Err: "+e.Error(), c)
 		return
 	}
 
-	ob := new(fms.ContractPrePayment)
+	//新增合同
+	ob := new(fms.ContractRegister)
+	//ob.ContractCode = req.ContractCode
 	ob.CompanyName = req.CompanyName
-	ob.CurrencyUnit = req.CurrencyUnit
+	ob.ProductIds = req.ProductIds
 	ob.StartDate = startDate
 	ob.EndDate = endDate
-	ob.AdminId = int(adminInfo.AdminId)
-	ob.AdminName = adminInfo.AdminName
-	ob.Amount = req.Amount / rate
-	ob.OriginAmount = req.Amount
-	ob.CurrencyUnit = req.CurrencyUnit
-	ob.Remark = req.Remark
-	ob.PaymentDate = payDate
 	ob.Set()
+	if req.RegisterType == fms.ContractInvoiceTypePreMake {
+		//sellerItem := sellerMap[r.SellerId]
+		//if sellerItem == nil {
+		//	resp.Fail("销售信息异常", c)
+		//	return
+		//}
+		for _, v := range sellers {
+			if v.DepartmentId == crm.SellerDepartmentId {
+				ob.SellerId = v.AdminId
+				ob.SellerName = v.AdminName
+			} else if v.DepartmentId == crm.RaiSellerDepartmentId {
+				ob.RaiSellerId = v.AdminId
+				ob.RaiSellerName = v.AdminName
+			}
+		}
+	}
 
-	// 新增合同及套餐
-	if e = ob.Create(); e != nil {
+	// 套餐信息
+	serviceAmountMap := make(map[int]float64)
+	serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
+	if e != nil {
+		resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
+		return
+	}
+	if e = fms.CreateContractRegisterAndServicesAndPayMent(ob, serviceList); e != nil {
 		resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
 		return
 	}
-	//// 开票到款汇总
-	//nowTime := time.Now().Local()
-	//v := new(fms.InvoicePaymentSummary)
-	//v.CreateTime = nowTime
-	//v.ModifyTime = nowTime
-	//v.PrePayid = ob.PrePayId
-	//
-	//if e = v.Create(); e != nil {
-	//	err = fmt.Errorf("新增汇总数据失败, Err: %s", e.Error())
-	//}
+
+	for _, r := range req.List {
+		// 货币及汇率
+		rateList, e := fmsService.GetTodayCurrencyRateList()
+		if e != nil {
+			resp.FailMsg("操作失败", "获取今日货币汇率失败, Err: "+e.Error(), c)
+			return
+		}
+		var rate float64
+		for i := range rateList {
+			if r.CurrencyUnit == rateList[i].Code {
+				rate = rateList[i].RMBRate
+				break
+			}
+		}
+		if rate <= 0 {
+			resp.FailMsg("操作失败", "货币汇率信息有误", c)
+			return
+		}
+
+		registerDate, e := time.Parse(utils.FormatDate, r.RegisterDate)
+		if e != nil {
+			resp.FailMsg("日期转换失败", "日期转换失败, Err: "+e.Error(), c)
+			return
+		}
+
+		v := &fms.ContractInvoice{
+			ContractRegisterId: ob.ContractRegisterId,
+			OriginAmount:       r.Amount,
+			CurrencyUnit:       r.CurrencyUnit,
+			InvoiceType:        req.RegisterType,
+			InvoiceDate:        registerDate,
+			AdminId:            int(adminInfo.AdminId),
+			AdminName:          adminInfo.AdminName,
+			Remark:             r.Remark,
+			ServiceProductId:   r.ServiceProductId,
+			IsPrePay:           1,
+			StartDate:          startDate,
+			EndDate:            endDate,
+			TimeBase:           base.TimeBase{},
+		}
+		v.Set()
+
+		a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", v.OriginAmount/rate), 64)
+		v.Amount = a
+
+		if req.RegisterType == fms.ContractInvoiceTypePreMake {
+			sellerItem := sellerMap[r.SellerId]
+			if sellerItem == nil {
+				resp.Fail("销售信息异常", c)
+				return
+			}
+
+			v.SellerId = sellerItem.SellerId
+			v.SellerName = sellerItem.SellerName
+			v.SellerGroupId = sellerItem.GroupId
+			v.SellerGroupName = sellerItem.GroupName
+			v.SellerTeamId = sellerItem.TeamId
+			v.SellerTeamName = sellerItem.TeamName
+		}
+
+		// 新增开票到款记录
+		if e = v.Create(); e != nil {
+			resp.FailMsg("操作失败", "新增预登记失败, Err: "+e.Error(), c)
+			return
+		}
+	}
+
+	// 开票到款汇总
+	go fmsService.SummaryInvoicePaymentByContractRegisterId(ob.ContractRegisterId)
 
 	resp.Ok("操作成功", c)
 }
 
 // Edit
-// @Title 编辑到款预登记
-// @Description 编辑到款预登记
+// @Title 编辑预登记
+// @Description 编辑预登记
 // @Param	request  body  fms.ContractRegisterEditReq  true  "type json string"
 // @Success 200 string "操作成功"
-// @router /contract/pre_pay/edit [post]
-func (rg *PrePaymentController) Edit(c *gin.Context) {
-	req := new(fms.PrepayEditReq)
+// @router /contract/pre_register/edit [post]
+func (rg *PreRegisterController) Edit(c *gin.Context) {
+	req := new(fms.PreRegisterEditReq)
 	err := c.ShouldBind(&req)
 	if err != nil {
 		errs, ok := err.(validator.ValidationErrors)
@@ -269,86 +355,172 @@ func (rg *PrePaymentController) Edit(c *gin.Context) {
 	adminInfo := claims.(*system.SysAdmin)
 
 	// 日期校验
-	startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
-	if e != nil {
-		resp.FailMsg("约定开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
-		return
+	var startDate, endDate time.Time
+	if req.StartDate != "" && req.EndDate != "" {
+		startDate, err = time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
+		if err != nil {
+			resp.FailMsg("约定开始日期格式有误", "合同开始日期格式有误, Err: "+err.Error(), c)
+			return
+		}
+		endDate, err = time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
+		if err != nil {
+			resp.FailMsg("约定结束日期格式有误", "合同结束日期格式有误, Err: "+err.Error(), c)
+			return
+		}
 	}
-	endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
+
+	// 获取销售分组信息
+	sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
 	if e != nil {
-		resp.FailMsg("约定结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
+		resp.FailData("获取销售失败", "Err:"+e.Error(), c)
 		return
 	}
+	sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
+	for i := range sellerList {
+		sellerMap[sellerList[i].SellerId] = sellerList[i]
+	}
 
-	// 货币及汇率
-	rateList, e := fmsService.GetTodayCurrencyRateList()
-	if e != nil {
-		resp.FailMsg("操作失败", "获取今日货币汇率失败, Err: "+e.Error(), c)
+	admin := new(crm.Admin)
+	sellerIds := strings.Split(req.SellerIds, ",")
+	if len(sellerIds) > 2 {
+		resp.Fail("最多只能选择两个销售", c)
 		return
 	}
-	var rate float64
-	for i := range rateList {
-		if req.CurrencyUnit == rateList[i].Code {
-			rate = rateList[i].RMBRate
-			break
-		}
-	}
-	if rate <= 0 {
-		resp.FailMsg("操作失败", "货币汇率信息有误", c)
+	var pars []interface{}
+	cond := ` admin_id in (?) `
+	pars = append(pars, sellerIds)
+	sellers, e := admin.List(cond, pars)
+	if e != nil {
+		resp.FailMsg("获取销售信息失败", "获取销售信息失败, Err: "+e.Error(), c)
 		return
 	}
 
-	ob := new(fms.ContractPrePayment)
-
-	item, e := ob.Fetch(req.PrePayId)
-	if e != nil {
-		if e == utils.ErrNoRow {
-			resp.Fail("预到款登记记录不存在或已被删除", c)
-			return
+	//修改合同
+	ob := new(fms.ContractRegister)
+	//ob.ContractCode = req.ContractCode
+	ob.ContractRegisterId = req.ContractRegisterId
+	ob.CompanyName = req.CompanyName
+	ob.ProductIds = req.ProductIds
+	ob.StartDate = startDate
+	ob.EndDate = endDate
+	ob.ModifyTime = time.Now().Local()
+	if req.RegisterType == fms.ContractInvoiceTypePreMake {
+		//sellerItem := sellerMap[r.SellerId]
+		//if sellerItem == nil {
+		//	resp.Fail("销售信息异常", c)
+		//	return
+		//}
+		for _, v := range sellers {
+			if v.DepartmentId == crm.SellerDepartmentId {
+				ob.SellerId = v.AdminId
+				ob.SellerName = v.AdminName
+			} else if v.DepartmentId == crm.RaiSellerDepartmentId {
+				ob.RaiSellerId = v.AdminId
+				ob.RaiSellerName = v.AdminName
+			}
 		}
-		resp.FailMsg("操作失败", "获取预到款登记信息失败, Err:"+e.Error(), c)
-		return
 	}
 
-	payDate, err := time.Parse(utils.FormatDate, req.PaymentDate)
+	// 套餐信息
+	serviceAmountMap := make(map[int]float64)
+	serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
 	if e != nil {
-		resp.FailMsg("日期转换失败", "日期转换失败, Err: "+e.Error(), c)
+		resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
 		return
 	}
+	updateCols := []string{
+		"ProductIds", "CompanyName", "SellerId", "SellerName", "StartDate", "EndDate",
+		"RaiSellerId", "RaiSellerName", "ModifyTime",
+	}
 
-	item.CompanyName = req.CompanyName
-	item.CurrencyUnit = req.CurrencyUnit
-	item.StartDate = startDate
-	item.EndDate = endDate
-	item.AdminId = int(adminInfo.AdminId)
-	item.AdminName = adminInfo.AdminName
-	item.Amount = req.Amount / rate
-	item.OriginAmount = req.Amount
-	item.CurrencyUnit = req.CurrencyUnit
-	item.Remark = req.Remark
-	item.PaymentDate = payDate
-	item.ModifyTime = time.Now().Local()
+	invoiceList := make([]*fms.ContractInvoice, 0)
+	for _, r := range req.List {
+		// 货币及汇率
+		rateList, e := fmsService.GetTodayCurrencyRateList()
+		if e != nil {
+			resp.FailMsg("操作失败", "获取今日货币汇率失败, Err: "+e.Error(), c)
+			return
+		}
+		var rate float64
+		for i := range rateList {
+			if r.CurrencyUnit == rateList[i].Code {
+				rate = rateList[i].RMBRate
+				break
+			}
+		}
+		if rate <= 0 {
+			resp.FailMsg("操作失败", "货币汇率信息有误", c)
+			return
+		}
 
-	updateCols := []string{
-		"ContractCode", "CompanyName", "SellerId", "SellerName", "Amount", "StartDate", "EndDate",
-		"Remark", "ModifyTime", "NewCompany", "OriginAmount", "CurrencyUnit", "PaymentDate",
+		registerDate, e := time.Parse(utils.FormatDate, r.RegisterDate)
+		if e != nil {
+			resp.FailMsg("日期转换失败", "日期转换失败, Err: "+e.Error(), c)
+			return
+		}
+
+		v := &fms.ContractInvoice{
+			ContractInvoiceId:  r.InvoiceId,
+			ContractRegisterId: ob.ContractRegisterId,
+			OriginAmount:       r.Amount,
+			CurrencyUnit:       r.CurrencyUnit,
+			InvoiceType:        req.RegisterType,
+			InvoiceDate:        registerDate,
+			AdminId:            int(adminInfo.AdminId),
+			AdminName:          adminInfo.AdminName,
+			Remark:             r.Remark,
+			ServiceProductId:   r.ServiceProductId,
+			IsPrePay:           1,
+			StartDate:          startDate,
+			EndDate:            endDate,
+		}
+		v.TimeBase.ModifyTime = time.Now().Local()
+
+		a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", v.OriginAmount/rate), 64)
+		v.Amount = a
+
+		if req.RegisterType == fms.ContractInvoiceTypePreMake {
+			sellerItem := sellerMap[r.SellerId]
+			if sellerItem == nil {
+				resp.Fail("销售信息异常", c)
+				return
+			}
+
+			v.SellerId = sellerItem.SellerId
+			v.SellerName = sellerItem.SellerName
+			v.SellerGroupId = sellerItem.GroupId
+			v.SellerGroupName = sellerItem.GroupName
+			v.SellerTeamId = sellerItem.TeamId
+			v.SellerTeamName = sellerItem.TeamName
+		}
+
+		invoiceList = append(invoiceList, v)
 	}
-	if e = item.Update(updateCols); e != nil {
-		resp.FailMsg("操作失败", "更新到预款登记失败, Err:"+e.Error(), c)
+	invoiceUpdateCols := []string{
+		"CurrencyUnit", "Amount", "InvoiceDate", "AdminId", "AdminName", "Remark",
+		"ServiceProductId", "StartDate", "EndDate", "ModifyTime",
+	}
+	// 更新合同登记、套餐、开票到款
+	if e = fms.UpdateContractPreRegister(ob, updateCols, serviceList, invoiceList, invoiceUpdateCols); e != nil {
+		resp.FailMsg("操作失败", "更新合同及套餐失败, Err: "+e.Error(), c)
 		return
 	}
 
+	// 开票到款汇总
+	go fmsService.SummaryInvoicePaymentByContractRegisterId(ob.ContractRegisterId)
+
 	resp.Ok("操作成功", c)
 }
 
+
 // Del
 // @Title 删除到款预登记
 // @Description 删除到款预登记
 // @Param	request  body  fms.ContractRegisterDelReq  true  "type json string"
 // @Success 200 string "操作成功"
 // @router /contract/pre_pay/del [post]
-func (rg *PrePaymentController) Del(c *gin.Context) {
-	req := new(fms.PrepayDelReq)
+func (rg *PreRegisterController) Del(c *gin.Context) {
+	req := new(fms.PreRegisterDelReq)
 	err := c.ShouldBind(&req)
 	if err != nil {
 		errs, ok := err.(validator.ValidationErrors)
@@ -360,8 +532,8 @@ func (rg *PrePaymentController) Del(c *gin.Context) {
 		return
 	}
 
-	ob := new(fms.ContractPrePayment)
-	item, e := ob.Fetch(req.PrePayId)
+	ob := new(fms.ContractInvoice)
+	item, e := ob.Fetch(req.InvoiceId)
 	if e != nil {
 		if e == utils.ErrNoRow {
 			resp.Fail("合同登记不存在或已被删除", c)

+ 2 - 2
controller/contract/register.go

@@ -341,7 +341,7 @@ func (rg *RegisterController) Add(c *gin.Context) {
 		}
 
 		//新增合同信息
-		if e = fms.CreateContractRegisterAndServicesAndPayMent(ob, serviceList, req.PrePayId); e != nil {
+		if e = fms.CreateContractRegisterAndServicesAndPayMent(ob, serviceList); e != nil {
 			resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
 			return
 		}
@@ -395,7 +395,7 @@ func (rg *RegisterController) Add(c *gin.Context) {
 			return
 		}
 		opData = string(opDataByte)
-		opType := fms.ContractInvoiceTypePrePay
+		opType := fms.ContractRegisterOpTypePreInvoice
 		newAmount := decimal.NewFromFloat(0).Round(2)
 		a := decimal.NewFromFloat(v.Amount).Round(2)
 		newAmount = newAmount.Add(a)

+ 12 - 10
models/fms/constants.go

@@ -19,18 +19,20 @@ const (
 	ContractRegisterStatusComplete = 2 // 已完成
 
 	// 合同登记操作类型
-	ContractRegisterOpTypeSave    = 1 // 合规登记
-	ContractRegisterOpTypeInvoice = 2 // 开票登记
-	ContractRegisterOpTypePayment = 3 // 到款登记
-	ContractRegisterOpTypeStatus  = 4 // 修改合同状态
-	ContractRegisterOpTypeDel     = 5 // 删除合同登记
-	ContractRegisterOpTypeEdit    = 6 // 合规编辑
-	ContractPrePayOpTypeEdit      = 7 // 到款预登记
+	ContractRegisterOpTypeSave       = 1 // 合规登记
+	ContractRegisterOpTypeInvoice    = 2 // 开票登记
+	ContractRegisterOpTypePayment    = 3 // 到款登记
+	ContractRegisterOpTypeStatus     = 4 // 修改合同状态
+	ContractRegisterOpTypeDel        = 5 // 删除合同登记
+	ContractRegisterOpTypeEdit       = 6 // 合规编辑
+	ContractRegisterOpTypePreInvoice = 7 // 开票预登记
+	ContractRegisterOpTypePrePay     = 8 // 到款预登记
 
 	// 合同登记开票类型
-	ContractInvoiceTypeMake = 1 // 开票登记
-	ContractInvoiceTypePay  = 2 // 到款登记
-	ContractInvoiceTypePrePay  = 3 // 到款预登记
+	ContractInvoiceTypeMake    = 1 // 开票登记
+	ContractInvoiceTypePay     = 2 // 到款登记
+	ContractInvoiceTypePreMake  = 3 // 开票预登记
+	ContractInvoiceTypePrePay = 4 // 到款预登记
 
 	// 到款登记付款方式
 	ContractPaymentPayTypeYear     = 1 // 年付

+ 24 - 4
models/fms/contract_invoice.go

@@ -16,7 +16,7 @@ type ContractInvoice struct {
 	Amount             float64   `gorm:"column:amount" json:"amount" description:"换算后的金额(人民币)"`
 	OriginAmount       float64   `gorm:"column:origin_amount" json:"origin_amount" description:"开票/到款金额"`
 	CurrencyUnit       string    `gorm:"column:currency_unit" json:"currency_unit" description:"货币国际代码"`
-	InvoiceType        int       `gorm:"column:invoice_type" json:"invoice_type" description:"类型: 1-开票登记; 2-到款登记"`
+	InvoiceType        int       `gorm:"column:invoice_type" json:"invoice_type" description:"类型: 1-开票登记; 2-到款登记;3-开票预登记;4-到款预登记"`
 	InvoiceDate        time.Time `gorm:"column:invoice_time" json:"invoice_time" description:"开票日期/到款月"`
 	SellerId           int       `gorm:"column:seller_id" json:"seller_id" description:"销售ID"`
 	SellerName         string    `gorm:"column:seller_name" json:"seller_name" description:"销售名称"`
@@ -31,6 +31,9 @@ type ContractInvoice struct {
 	IsDeleted          int       `gorm:"column:is_deleted" json:"is_deleted" description:"是否已删除: 0-正常; 1-已删除"`
 	ServiceProductId   int       `gorm:"column:service_product_id" json:"service_product_id" description:"套餐类型:1ficc套餐,2权益套餐"`
 	IsPrePay           int       `gorm:"column:is_pre_pay" json:"is_pre_pay" description:"是否预付款: 0-不是; 1-是"`
+	StartDate          time.Time `gorm:"column:start_date" json:"start_date" description:"约定开始时间"`
+	EndDate            time.Time `gorm:"column:end_date" json:"end_date" description:"约定结束时间"`
+	Pid                int       `gorm:"column:pid" json:"pid" description:"关联主id"`
 	base.TimeBase
 }
 
@@ -48,7 +51,7 @@ type ContractInvoiceItem struct {
 	OriginAmount       float64 `gorm:"column:origin_amount" json:"origin_amount" description:"开票/到款金额"`
 	CurrencyUnit       string  `gorm:"column:currency_unit" json:"currency_unit" description:"货币国际代码"`
 	UnitName           string  `json:"unit_name" description:"货币单位名称"`
-	InvoiceType        int     `gorm:"column:invoice_type" json:"invoice_type" description:"类型: 1-开票登记; 2-到款登记"`
+	InvoiceType        int     `gorm:"column:invoice_type" json:"invoice_type" description:"类型: 1-开票登记; 2-到款登记;3-开票预登记;4-到款预登记"`
 	InvoiceDate        string  `gorm:"column:invoice_time" json:"invoice_time" description:"开票日期/到款月"`
 	SellerId           int     `gorm:"column:seller_id" json:"seller_id" description:"销售ID"`
 	SellerName         string  `gorm:"column:seller_name" json:"seller_name" description:"销售名称"`
@@ -56,6 +59,8 @@ type ContractInvoiceItem struct {
 	Remark             string  `gorm:"column:remark" json:"remark" description:"备注信息"`
 	ServiceProductId   int     `gorm:"column:service_product_id" json:"service_product_id" description:"套餐类型:1ficc套餐,2权益套餐"`
 	IsPrePay           int     `gorm:"column:is_pre_pay" json:"is_pre_pay" description:"是否预付款: 0-不是; 1-是"`
+	StartDate          string  `gorm:"column:start_date" json:"start_date" description:"约定开始时间"`
+	EndDate            string  `gorm:"column:end_date" json:"end_date" description:"约定结束时间"`
 	CreateTime         string  `gorm:"column:create_time" json:"create_time" description:"创建时间"`
 }
 
@@ -79,6 +84,13 @@ func (c *ContractInvoice) Fetch(id int) (item *ContractInvoice, err error) {
 	return
 }
 
+// 删除
+func (c *ContractInvoice) Delete() (err error) {
+	err = global.DEFAULT_MYSQL.Delete(c).Error
+	return
+}
+
+
 func (c *ContractInvoice) Sum(field, condition string, pars []interface{}) (total float64, err error) {
 	totalList := make([]float64, 0)
 	err = global.DEFAULT_MYSQL.Model(c).
@@ -196,9 +208,11 @@ func formatContractInvoice2ItemList(list []*ContractInvoice) (itemList []*Contra
 			SellerName:         list[i].SellerName,
 			PayType:            list[i].PayType,
 			Remark:             list[i].Remark,
+			ServiceProductId:   list[i].ServiceProductId,
 			IsPrePay:           list[i].IsPrePay,
+			StartDate:          list[i].StartDate.Format(utils.FormatDate),
+			EndDate:            list[i].StartDate.Format(utils.FormatDate),
 			CreateTime:         utils.TimeTransferString(utils.FormatDateTime, list[i].CreateTime),
-			ServiceProductId:   list[i].ServiceProductId,
 		})
 	}
 	return
@@ -278,7 +292,7 @@ type InvoicePaymentCensusListReq struct {
 	IsExport     int    `json:"is_export" form:"is_export" description:"是否导出: 0-否; 1-是"`
 	SortParam    string `json:"sort_param" form:"sort_param" description:"排序字段参数,用来排序的字段, 枚举值:'invoice_time':开票日 、 'payment_date':到款日"`
 	SortType     string `json:"sort_type" form:"sort_type" description:"如何排序,是正序还是倒序,枚举值:asc 正序,desc 倒叙"`
-	TimeType    int    `json:"time_type" form:"time_type" description:"时间类型: 1-开票时间; 2-到款时间;3-开票时间&到款时间"`
+	TimeType     int    `json:"time_type" form:"time_type" description:"时间类型: 1-开票时间; 2-到款时间;3-开票时间&到款时间"`
 	base.PageReq
 }
 
@@ -495,3 +509,9 @@ func GetInvoiceListCurrencySum(condition string, pars []interface{}, groupRule s
 	err = query.Find(&results).Error
 	return
 }
+
+// PreRegisterListReq 预登记列表请求体
+type PreRegisterListReq struct {
+	Keyword string `json:"keyword" form:"keyword" binding:"omitempty" description:"关键词"`
+	base.PageReq
+}

+ 43 - 14
models/fms/contract_pre_payment.go

@@ -107,14 +107,25 @@ func formatPrePay2Item(item *ContractPrePayment) (formatItem *ContractPrePayment
 }
 
 // PrepayAddReq 新增到款预登记请求体
-type PrepayAddReq struct {
-	CompanyName  string  `json:"company_name" binding:"required" description:"客户名称"`
-	Amount       float64 `json:"amount" binding:"required" description:"到款金额"`
-	CurrencyUnit string  `json:"currency_unit" binding:"required" description:"货币单位"`
-	StartDate    string  `json:"start_date" binding:"required" description:"约定开始日期"`
-	EndDate      string  `json:"end_date" binding:"required" description:"约定结束日期"`
-	Remark       string  `json:"remark" description:"备注信息"`
-	PaymentDate  string  `json:"payment_date" description:"到款日"`
+type PreRegisterAddReq struct {
+	CompanyName  string                   `json:"company_name" binding:"required" description:"客户名称"`
+	StartDate    string                   `json:"start_date" binding:"required" description:"约定开始日期"`
+	EndDate      string                   `json:"end_date" binding:"required" description:"约定结束日期"`
+	RegisterType int                      `json:"register_type" description:"预登记类型 3-开票预登记 4-到款预登记"`
+	ProductIds   string                   `gorm:"column:product_ids" json:"product_ids" description:"产品ID:1-FICC; 2-权益, 如果两者都有,则用英文逗号拼接"`
+	SellerIds    string                   `json:"seller_ids" binding:"required" description:"CRM系统-销售ID"`
+	List         []*PreRegisterAddReqItem `json:"lists" binding:"required" description:"CRM系统-销售ID"`
+	Services     []ContractServiceAddReq  `json:"services" description:"服务套餐内容"`
+}
+
+type PreRegisterAddReqItem struct {
+	Amount           float64 `json:"amount" binding:"required" description:"到款金额"`
+	CurrencyUnit     string  `json:"currency_unit" binding:"required" description:"货币单位"`
+	Remark           string  `json:"remark" description:"备注信息"`
+	RegisterDate     string  `json:"register_date" description:"到款或开票日期"`
+	SellerId         int     `gorm:"column:seller_id" json:"seller_id" description:"销售ID"`
+	SellerName       string  `gorm:"column:seller_name" json:"seller_name" description:"销售名称"`
+	ServiceProductId int     `gorm:"column:service_product_id" json:"service_product_id" description:"套餐类型:1ficc套餐,2权益套餐"`
 }
 
 func (c *ContractPrePayment) Create() (err error) {
@@ -139,12 +150,30 @@ func (c *ContractPrePayment) Delete() (err error) {
 }
 
 // PrepayEditReq 编辑到款预登记请求体
-type PrepayEditReq struct {
-	PrePayId int `json:"pre_pay_id" binding:"required,gte=1" description:"预付款ID"`
-	PrepayAddReq
+type PreRegisterEditReq struct {
+	ContractRegisterId int    `json:"contract_register_id" binding:"required,gte=1" description:"登记ID"`
+	CompanyName        string `json:"company_name" binding:"required" description:"客户名称"`
+	StartDate          string `json:"start_date" binding:"required" description:"约定开始日期"`
+	EndDate            string `json:"end_date" binding:"required" description:"约定结束日期"`
+	RegisterType       int    `json:"register_type" description:"预登记类型 3-开票预登记 4-到款预登记"`
+	ProductIds         string `gorm:"column:product_ids" json:"product_ids" description:"产品ID:1-FICC; 2-权益, 如果两者都有,则用英文逗号拼接"`
+	SellerIds          string `json:"seller_ids" binding:"required" description:"CRM系统-销售ID"`
+	List               []*PreRegisterEditReqItem
+	Services           []ContractServiceAddReq `json:"services" description:"服务套餐内容"`
+}
+
+type PreRegisterEditReqItem struct {
+	InvoiceId        int     `json:"invoice_id" description:"开票ID"`
+	Amount           float64 `json:"amount" binding:"required" description:"到款金额"`
+	CurrencyUnit     string  `json:"currency_unit" binding:"required" description:"货币单位"`
+	Remark           string  `json:"remark" description:"备注信息"`
+	RegisterDate     string  `json:"register_date" description:"到款或开票日期"`
+	SellerId         int     `gorm:"column:seller_id" json:"seller_id" description:"销售ID"`
+	SellerName       string  `gorm:"column:seller_name" json:"seller_name" description:"销售名称"`
+	ServiceProductId int     `gorm:"column:service_product_id" json:"service_product_id" description:"套餐类型:1ficc套餐,2权益套餐"`
 }
 
-// PrepayDelReq 删除到款预登记
-type PrepayDelReq struct {
-	PrePayId int `json:"pre_pay_id" binding:"required,gte=1" description:"预付款ID"`
+// PreRegisterDelReq 预登记删除请求体
+type PreRegisterDelReq struct {
+	InvoiceId int `json:"invoice_id" description:"开票ID"`
 }

+ 73 - 13
models/fms/contract_register.go

@@ -277,7 +277,6 @@ func UpdateContractRegister(item *ContractRegister, updateCols []string, service
 	sql = `DELETE FROM contract_service_amount WHERE contract_register_id = ?`
 	tx.Exec(sql, item.ContractRegisterId)
 
-
 	// 新增合同服务
 	//nowTime := time.Now().Local()
 	for i := 0; i < len(serviceDetail); i++ {
@@ -348,11 +347,11 @@ type ContractRegisterDetailReq struct {
 // ContractRegisterDetail-合同登记详情
 type ContractRegisterDetail struct {
 	*ContractRegisterItem
-	ServiceList       []*ContractServiceAndDetail `json:"service_list" description:"合同服务及详情"`
-	InvoiceList       []*ContractInvoiceItem      `json:"invoice_list" description:"开票信息"`
-	PaymentList       []*ContractInvoiceItem      `json:"payment_list" description:"到款信息"`
-	Logs              []*ContractRegisterLogItem  `json:"logs" description:"登记日志"`
-	ServiceAmountList []*ContractServiceAmountItem    `json:"service_amount_list" description:"合同套餐金额"`
+	ServiceList       []*ContractServiceAndDetail  `json:"service_list" description:"合同服务及详情"`
+	InvoiceList       []*ContractInvoiceItem       `json:"invoice_list" description:"开票信息"`
+	PaymentList       []*ContractInvoiceItem       `json:"payment_list" description:"到款信息"`
+	Logs              []*ContractRegisterLogItem   `json:"logs" description:"登记日志"`
+	ServiceAmountList []*ContractServiceAmountItem `json:"service_amount_list" description:"合同套餐金额"`
 }
 
 // GetContractRegisterItemById 获取合同登记信息
@@ -484,8 +483,7 @@ func CreateImportContractRegister(item *ContractRegister, serviceList []*Contrac
 	return
 }
 
-
-func GetContractInfoByRegisterIds(registerIds []int) (list []ContractRegister,err error) {
+func GetContractInfoByRegisterIds(registerIds []int) (list []ContractRegister, err error) {
 	err = global.DEFAULT_MYSQL.Model(ContractRegister{}).
 		Where("is_deleted = 0 AND contract_register_id in ?", registerIds).
 		Find(&list).Error
@@ -493,7 +491,7 @@ func GetContractInfoByRegisterIds(registerIds []int) (list []ContractRegister,er
 }
 
 // CreateContractRegisterAndServices 新增合同登记及套餐
-func CreateContractRegisterAndServicesAndPayMent(item *ContractRegister, serviceDetail []*ContractServiceAndDetail, prePayId int) (err error) {
+func CreateContractRegisterAndServicesAndPayMent(item *ContractRegister, serviceDetail []*ContractServiceAndDetail) (err error) {
 	tx := global.DEFAULT_MYSQL.Begin()
 	defer func() {
 		if err != nil {
@@ -539,13 +537,75 @@ func CreateContractRegisterAndServicesAndPayMent(item *ContractRegister, service
 	return
 }
 
-type  CheckContractNameReq struct {
+type CheckContractNameReq struct {
 	CompanyName string `json:"company_name" form:"company_name" description:"客户名称"`
 	StartDate   string `json:"start_date" form:"start_date" description:"合同开始日期"`
 	EndDate     string `json:"end_date" form:"end_date" description:"合同结束日期"`
 }
 
+type CheckContractNameResp struct {
+	Exist int `json:"exist" description:"是否存在相似的合同:0不存在,1存在"`
+}
+
+// UpdateContractPreRegister 更新合同预登记
+func UpdateContractPreRegister(item *ContractRegister, updateCols []string, serviceDetail []*ContractServiceAndDetail,
+	invoiceList []*ContractInvoice, invoiceUpdateCols []string) (err error) {
+	tx := global.DEFAULT_MYSQL.Begin()
+	defer func() {
+		if err != nil {
+			tx.Rollback()
+		} else {
+			tx.Commit()
+		}
+	}()
+
+	// 更新合同登记
+	if e := tx.Model(item).Select(updateCols).Updates(item).Error; e != nil {
+		err = e
+		return
+	}
+
+	// 删除原服务及详情信息
+	sql := `DELETE FROM contract_service WHERE contract_register_id = ?`
+	tx.Exec(sql, item.ContractRegisterId)
+
+	// 新增合同服务
+	//nowTime := time.Now().Local()
+	for i := 0; i < len(serviceDetail); i++ {
+		// 合同服务
+		t := serviceDetail[i]
+		contractService := &ContractService{
+			ContractRegisterId: item.ContractRegisterId,
+			ProductId:          t.ProductId,
+			ServiceTemplateId:  t.ServiceTemplateId,
+			Title:              t.Title,
+			Value:              t.Value,
+			TableValue:         t.TableValue,
+			HasDetail:          t.HasDetail,
+			ChartPermissionId:  t.ChartPermissionId,
+			ChartPermissionIds: t.ChartPermissionIds,
+		}
+		contractService.Set()
+		tx.Create(contractService)
+
+		//// 合同服务详情
+		//for j := 0; j < len(t.Detail); j++ {
+		//	contractServiceDetail := t.Detail[j]
+		//	contractServiceDetail.ContractServiceId = contractService.ContractServiceId
+		//	contractServiceDetail.ContractRegisterId = item.ContractRegisterId
+		//	contractServiceDetail.ServiceTemplateId = contractService.ServiceTemplateId
+		//	contractServiceDetail.CreateTime = nowTime
+		//	tx.Create(contractServiceDetail)
+		//	t.Detail[j] = contractServiceDetail
+		//}
+	}
+
+	for i := range invoiceList {
+		if e := tx.Model(invoiceList[i]).Select(invoiceUpdateCols).Updates(invoiceList[i]).Error; e != nil {
+			err = e
+			return
+		}
+	}
 
-type  CheckContractNameResp struct {
-	Exist int 	`json:"exist" description:"是否存在相似的合同:0不存在,1存在"`
-}
+	return
+}

+ 7 - 7
routers/contract.go

@@ -36,11 +36,11 @@ func InitContract(rg *gin.RouterGroup) {
 	payGroup.POST("update_pay_type", pay.UpdatePaymentPayType)
 	payGroup.POST("distribute_service_amount", pay.DistributePaymentServiceAmount)
 
-	//到款预登记
-	prepay := new(contract.PrePaymentController)
-	prepayGroup := rg.Group("pre_pay/").Use(middleware.Token())
-	prepayGroup.GET("list", prepay.List)
-	prepayGroup.POST("add", prepay.Add)
-	prepayGroup.POST("edit", prepay.Edit)
-	prepayGroup.POST("del", prepay.Del)
+	//预登记
+	preRegister := new(contract.PreRegisterController)
+	preRegisterGroup := rg.Group("pre_register/").Use(middleware.Token())
+	preRegisterGroup.GET("list", preRegister.List)
+	preRegisterGroup.POST("add", preRegister.Add)
+	preRegisterGroup.POST("edit", preRegister.Edit)
+	preRegisterGroup.POST("del", preRegister.Del)
 }

+ 162 - 24
services/fms/invoice_payment.go

@@ -186,7 +186,7 @@ func SummaryInvoicePaymentByContractRegisterId(registerId int) {
 		if list[i].InvoiceType == fms.ContractInvoiceTypeMake {
 			if list[i].ServiceProductId == crm.CompanyProductFicc {
 				ficcInvoiceIds = append(ficcInvoiceIds, list[i].ContractInvoiceId)
-			}else if list[i].ServiceProductId == crm.CompanyProductRai {
+			} else if list[i].ServiceProductId == crm.CompanyProductRai {
 				raiInvoiceIds = append(raiInvoiceIds, list[i].ContractInvoiceId)
 			}
 			continue
@@ -194,9 +194,26 @@ func SummaryInvoicePaymentByContractRegisterId(registerId int) {
 		if list[i].InvoiceType == fms.ContractInvoiceTypePay {
 			if list[i].ServiceProductId == crm.CompanyProductFicc {
 				ficcPaymentIds = append(ficcPaymentIds, list[i].ContractInvoiceId)
-			}else if list[i].ServiceProductId == crm.CompanyProductRai {
+			} else if list[i].ServiceProductId == crm.CompanyProductRai {
 				raiPaymentIds = append(raiPaymentIds, list[i].ContractInvoiceId)
 			}
+			continue
+		}
+		if list[i].InvoiceType == fms.ContractInvoiceTypePreMake {
+			if list[i].ServiceProductId == crm.CompanyProductFicc {
+				ficcInvoiceIds = append(ficcInvoiceIds, list[i].ContractInvoiceId)
+			} else if list[i].ServiceProductId == crm.CompanyProductRai {
+				raiInvoiceIds = append(raiInvoiceIds, list[i].ContractInvoiceId)
+			}
+			continue
+		}
+		if list[i].InvoiceType == fms.ContractInvoiceTypePrePay {
+			if list[i].ServiceProductId == crm.CompanyProductFicc {
+				ficcPaymentIds = append(ficcPaymentIds, list[i].ContractInvoiceId)
+			} else if list[i].ServiceProductId == crm.CompanyProductRai {
+				raiPaymentIds = append(raiPaymentIds, list[i].ContractInvoiceId)
+			}
+			continue
 		}
 	}
 	ficcInvoiceLen := len(ficcInvoiceIds)
@@ -271,7 +288,6 @@ func SummaryInvoicePaymentByContractRegisterId(registerId int) {
 		}
 	}
 
-
 	// 删除并新增汇总数据
 	summaryOB := new(fms.InvoicePaymentSummary)
 	if e = summaryOB.DeleteAndCreate(registerId, summaryList); e != nil {
@@ -281,7 +297,7 @@ func SummaryInvoicePaymentByContractRegisterId(registerId int) {
 }
 
 // CalculatePaymentServiceAmount
-func CalculatePaymentServiceAmount(registerId int) (err error)  {
+func CalculatePaymentServiceAmount(registerId int) (err error) {
 	// todo 判断是否符合均分金额的条件,如果符合,需要生成金额分配记录表
 	// 查询所有的到款记录,如果没有到款记录则无需分配到款金额
 	cond := `contract_register_id = ? and invoice_type=2 and service_product_id=2`
@@ -296,13 +312,13 @@ func CalculatePaymentServiceAmount(registerId int) (err error)  {
 		return
 	}
 	var contractPaymentIds []int
-	for _, v:= range paymentList{
+	for _, v := range paymentList {
 		contractPaymentIds = append(contractPaymentIds, v.ContractInvoiceId)
 	}
 	// 获取服务套餐
 	servicesList, err := fms.GetContractServiceAndDetailList(registerId)
 	if err != nil {
-		err = fmt.Errorf("获取服务套餐失败, Err: "+err.Error())
+		err = fmt.Errorf("获取服务套餐失败, Err: " + err.Error())
 		return
 	}
 	industrySlice := []string{
@@ -319,19 +335,19 @@ func CalculatePaymentServiceAmount(registerId int) (err error)  {
 	industryFlag := false
 	servicesListMap := make(map[int]*fms.ContractServiceAndDetail)
 	// 判断当前套餐是否符合分配规则
-	for _, v :=range servicesList {
+	for _, v := range servicesList {
 		if v.ProductId == crm.CompanyProductRai {
 			industryFlag = true
 		}
 		servicesListMap[v.ServiceTemplateId] = v
-		if v.ProductId==crm.CompanyProductRai && !utils.InArray(v.Title, industrySlice){
+		if v.ProductId == crm.CompanyProductRai && !utils.InArray(v.Title, industrySlice) {
 			unNeedAsign = true
 		}
 	}
-	if unNeedAsign || !industryFlag{
+	if unNeedAsign || !industryFlag {
 		//不符合自动分配规则,则直接删除之前的自动分配记录
-		err =fms.DeletePaymentServiceAmountByRegisterId(registerId)
-		if err !=nil {
+		err = fms.DeletePaymentServiceAmountByRegisterId(registerId)
+		if err != nil {
 			return
 		}
 		return
@@ -349,19 +365,19 @@ func CalculatePaymentServiceAmount(registerId int) (err error)  {
 		}
 
 		servicesFormatStr := ""
-		length :=0
-		for _, v :=range servicesFormatList {
-			if  servicesListMap[v.ServiceTemplateId].ProductId==crm.CompanyProductRai{
-				length ++
+		length := 0
+		for _, v := range servicesFormatList {
+			if servicesListMap[v.ServiceTemplateId].ProductId == crm.CompanyProductRai {
+				length++
 				servicesFormatStr += fmt.Sprintf("%d_", v.ServiceTemplateId)
 			}
 		}
-		if length ==0 {
+		if length == 0 {
 			return
 		}
 		payAverageAmountMap := make(map[int]float64)
-		for _, v := range paymentList{
-			payAverageAmountMap[v.ContractInvoiceId] = v.Amount/float64(length)
+		for _, v := range paymentList {
+			payAverageAmountMap[v.ContractInvoiceId] = v.Amount / float64(length)
 			payAverageAmountMap[v.ContractInvoiceId], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", payAverageAmountMap[v.ContractInvoiceId]), 64)
 		}
 
@@ -378,14 +394,14 @@ func CalculatePaymentServiceAmount(registerId int) (err error)  {
 
 		oldPaymentServiceMap := make(map[int]string)
 		oldPaymentAmountMap := make(map[int]float64)
-		for _, v := range serviceAmountList{
+		for _, v := range serviceAmountList {
 			oldPaymentServiceMap[v.ContractPaymentId] += fmt.Sprintf("%d_", v.ServiceTemplateId)
 			oldPaymentAmountMap[v.ContractPaymentId] = v.Amount
 		}
 
 		var newPaymentIds []int
-		for _, v := range paymentList{
-			if _, ok1 := oldPaymentServiceMap[v.ContractInvoiceId]; !ok1{
+		for _, v := range paymentList {
+			if _, ok1 := oldPaymentServiceMap[v.ContractInvoiceId]; !ok1 {
 				newPaymentIds = append(newPaymentIds, v.ContractInvoiceId)
 				continue
 			}
@@ -400,13 +416,13 @@ func CalculatePaymentServiceAmount(registerId int) (err error)  {
 		}
 
 		// 删除旧的金额分配记录并生成新的自动分配记录
-		if len(newPaymentIds) == 0{
+		if len(newPaymentIds) == 0 {
 			return
 		}
 		for _, v := range newPaymentIds {
 			addList := make([]*fms.ContractPaymentServiceAmount, 0)
 			for _, f := range servicesFormatList {
-				if  servicesListMap[f.ServiceTemplateId].ProductId==crm.CompanyProductRai {
+				if servicesListMap[f.ServiceTemplateId].ProductId == crm.CompanyProductRai {
 					t := &fms.ContractPaymentServiceAmount{
 						ContractRegisterId: registerId,
 						ContractPaymentId:  v,
@@ -420,7 +436,7 @@ func CalculatePaymentServiceAmount(registerId int) (err error)  {
 				}
 			}
 			if e := fms.CreatePaymentServiceAmount(registerId, v, addList); e != nil {
-				err = fmt.Errorf( "新增到款套餐金额失败, Err: "+e.Error())
+				err = fmt.Errorf("新增到款套餐金额失败, Err: " + e.Error())
 				return
 			}
 		}
@@ -428,3 +444,125 @@ func CalculatePaymentServiceAmount(registerId int) (err error)  {
 	return
 }
 
+// SummaryInvoicePaymentByPreRegister 预登记时汇总
+func SummaryInvoicePaymentByPreRegister(invoiceId, registerId int) {
+	var err error
+	defer func() {
+		if err != nil {
+			alarm_msg.SendAlarmMsg(fmt.Sprintf("汇总开票到款失败, ErrMsg: \n%s", err.Error()), 3)
+		}
+	}()
+	// 获取开票到款信息
+	cond := `contract_register_id = ?`
+	pars := make([]interface{}, 0)
+	pars = append(pars, registerId)
+	list, e := fms.GetContractInvoiceItemList(cond, pars)
+	if e != nil {
+		err = fmt.Errorf("获取开票到款列表失败, Err: %s", e.Error())
+		return
+	}
+
+	// 获取开票到款信息
+	ficcInvoiceIds := make([]int, 0)
+	ficcPaymentIds := make([]int, 0)
+	raiInvoiceIds := make([]int, 0)
+	raiPaymentIds := make([]int, 0)
+
+	for i := range list {
+		if list[i].InvoiceType == fms.ContractInvoiceTypePreMake {
+			if list[i].ServiceProductId == crm.CompanyProductFicc {
+				ficcInvoiceIds = append(ficcInvoiceIds, list[i].ContractInvoiceId)
+			} else if list[i].ServiceProductId == crm.CompanyProductRai {
+				raiInvoiceIds = append(raiInvoiceIds, list[i].ContractInvoiceId)
+			}
+			continue
+		}
+		if list[i].InvoiceType == fms.ContractInvoiceTypePay {
+			if list[i].ServiceProductId == crm.CompanyProductFicc {
+				ficcPaymentIds = append(ficcPaymentIds, list[i].ContractInvoiceId)
+			} else if list[i].ServiceProductId == crm.CompanyProductRai {
+				raiPaymentIds = append(raiPaymentIds, list[i].ContractInvoiceId)
+			}
+		}
+	}
+
+
+	ficcInvoiceLen := len(ficcInvoiceIds)
+	raiInvoiceLen := len(raiInvoiceIds)
+	ficcPaymentLen := len(ficcPaymentIds)
+	raiPaymentLen := len(raiPaymentIds)
+
+	// 汇总数据
+	nowTime := time.Now().Local()
+	summaryList := make([]*fms.InvoicePaymentSummary, 0)
+	// ficc
+	if ficcInvoiceLen >= ficcPaymentLen {
+		for i := range ficcInvoiceIds {
+			v := new(fms.InvoicePaymentSummary)
+			v.RegisterId = registerId
+			v.InvoiceId = ficcInvoiceIds[i]
+			v.ServiceProductId = crm.CompanyProductFicc
+			v.CreateTime = nowTime
+			v.ModifyTime = nowTime
+			// 取对应key的到款ID
+			if i+1 <= ficcPaymentLen {
+				v.PaymentId = ficcPaymentIds[i]
+			}
+			summaryList = append(summaryList, v)
+		}
+	}
+	if ficcPaymentLen > ficcInvoiceLen {
+		for i := range ficcPaymentIds {
+			v := new(fms.InvoicePaymentSummary)
+			v.RegisterId = registerId
+			v.PaymentId = ficcPaymentIds[i]
+			v.ServiceProductId = crm.CompanyProductFicc
+			v.CreateTime = nowTime
+			v.ModifyTime = nowTime
+			// 取对应key的开票ID
+			if i+1 <= ficcInvoiceLen {
+				v.InvoiceId = ficcInvoiceIds[i]
+			}
+			summaryList = append(summaryList, v)
+		}
+	}
+
+	// rai
+	if raiInvoiceLen >= raiPaymentLen {
+		for i := range raiInvoiceIds {
+			v := new(fms.InvoicePaymentSummary)
+			v.RegisterId = registerId
+			v.InvoiceId = raiInvoiceIds[i]
+			v.ServiceProductId = crm.CompanyProductRai
+			v.CreateTime = nowTime
+			v.ModifyTime = nowTime
+			// 取对应key的到款ID
+			if i+1 <= raiPaymentLen {
+				v.PaymentId = raiPaymentIds[i]
+			}
+			summaryList = append(summaryList, v)
+		}
+	}
+	if raiPaymentLen > raiInvoiceLen {
+		for i := range raiPaymentIds {
+			v := new(fms.InvoicePaymentSummary)
+			v.RegisterId = registerId
+			v.PaymentId = raiPaymentIds[i]
+			v.ServiceProductId = crm.CompanyProductRai
+			v.CreateTime = nowTime
+			v.ModifyTime = nowTime
+			// 取对应key的开票ID
+			if i+1 <= raiInvoiceLen {
+				v.InvoiceId = raiInvoiceIds[i]
+			}
+			summaryList = append(summaryList, v)
+		}
+	}
+
+	// 删除并新增汇总数据
+	summaryOB := new(fms.InvoicePaymentSummary)
+	if e = summaryOB.DeleteAndCreate(registerId, summaryList); e != nil {
+		err = fmt.Errorf("新增汇总数据失败, Err: %s", e.Error())
+	}
+	return
+}