浏览代码

Merge branch 'fms_2.5'

ziwen 2 年之前
父节点
当前提交
cdbfd42c75

+ 8 - 0
controller/census/invoice_payment.go

@@ -508,6 +508,7 @@ func ExportInvoicePaymentCensusList(c *gin.Context, results *fms.InvoicePaymentC
 // @Param   HasInvoice		query	string		false	"是否已开票: 0-否; 1-是; 空-全部"
 // @Param   HasPayment		query	string		false	"是否已到款: 0-否; 1-是; 空-全部"
 // @Param   IsExport		query	int		false	"是否导出: 0-否; 1-是"
+// @Param   ListParam		query	int		false	"套餐类型: 0-全部; 1-ficc; 2-权益"
 // @Param   SortParam       query   string  false      "排序字段参数,用来排序的字段, 枚举值:'invoice_time':开票日 、 'payment_date':到款日"
 // @Param   SortType        query   string  true       "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
 // @Success 200 {object} fms.ContractRegisterItem
@@ -552,6 +553,13 @@ func (ct *InvoicePaymentController) List(c *gin.Context) {
 			cond += ` AND 1 = 2`
 		}
 	}
+
+	if req.ListParam == 1{
+		cond += ` AND a.service_product_id = 1 `
+	}else if req.ListParam == 2 {
+		cond += ` AND a.service_product_id = 2 `
+	}
+
 	// 开票到款日期
 	if req.TimeType != 0 {
 		if req.TimeType == 1 &&  req.StartDate != "" && req.EndDate != "" {

+ 0 - 334
controller/contract/pre_payment.go

@@ -1,334 +0,0 @@
-package contract
-
-import (
-	"fmt"
-	"github.com/gin-gonic/gin"
-	"github.com/go-playground/validator/v10"
-	"hongze/fms_api/controller/resp"
-	"hongze/fms_api/global"
-	"hongze/fms_api/models/base"
-	"hongze/fms_api/models/fms"
-	"hongze/fms_api/models/system"
-	fmsService "hongze/fms_api/services/fms"
-	"hongze/fms_api/utils"
-	"time"
-)
-
-// // RegisterController 合同登记
-type PrePaymentController struct{}
-
-// List
-// @Title 到款预登记列表
-// @Description 到款预登记列表
-// @Param   Keyword			query	string	false	"关键词"
-// @Param   StartDate		query	string	false	"约定开始时间"
-// @Param   EndDate			query	string	false	"约定结束时间"
-// @Param   SortType   		query   string  true       "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
-// @Success 200 {object} fms.ContractRegisterItem
-// @router /contract/pre_pay/list [get]
-func (rg *PrePaymentController) List(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)
-}
-
-// Add
-// @Title 新增到款预登记
-// @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)
-	err := c.ShouldBind(&req)
-	if err != nil {
-		errs, ok := err.(validator.ValidationErrors)
-		if !ok {
-			resp.FailData("参数解析失败", "Err:"+err.Error(), c)
-			return
-		}
-		resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
-		return
-	}
-	claims, _ := c.Get("adminInfo")
-	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
-	}
-
-	// 货币及汇率
-	rateList, e := fmsService.GetTodayCurrencyRateList()
-	if e != nil {
-		resp.FailMsg("操作失败", "获取今日货币汇率失败, Err: "+e.Error(), 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)
-		return
-	}
-
-	payDate,err := time.Parse(utils.FormatDate,req.PaymentDate)
-	if e != nil {
-		resp.FailMsg("日期转换失败", "日期转换失败, Err: "+e.Error(), c)
-		return
-	}
-
-	ob := new(fms.ContractPrePayment)
-	ob.CompanyName = req.CompanyName
-	ob.CurrencyUnit = req.CurrencyUnit
-	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 e = ob.Create(); 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())
-	//}
-
-	resp.Ok("操作成功", c)
-}
-
-// Edit
-// @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)
-	err := c.ShouldBind(&req)
-	if err != nil {
-		errs, ok := err.(validator.ValidationErrors)
-		if !ok {
-			resp.FailData("参数解析失败", "Err:"+err.Error(), c)
-			return
-		}
-		resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
-		return
-	}
-	claims, _ := c.Get("adminInfo")
-	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
-	}
-
-	// 货币及汇率
-	rateList, e := fmsService.GetTodayCurrencyRateList()
-	if e != nil {
-		resp.FailMsg("操作失败", "获取今日货币汇率失败, Err: "+e.Error(), 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)
-		return
-	}
-
-	ob := new(fms.ContractPrePayment)
-
-	item, e := ob.Fetch(req.PrePayId)
-	if e != nil {
-		if e == utils.ErrNoRow {
-			resp.Fail("预到款登记记录不存在或已被删除", c)
-			return
-		}
-		resp.FailMsg("操作失败", "获取预到款登记信息失败, Err:"+e.Error(), c)
-		return
-	}
-
-	payDate,err := time.Parse(utils.FormatDate,req.PaymentDate)
-	if e != nil {
-		resp.FailMsg("日期转换失败", "日期转换失败, Err: "+e.Error(), c)
-		return
-	}
-
-	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()
-
-	updateCols := []string{
-		"ContractCode", "CompanyName", "SellerId", "SellerName", "Amount", "StartDate", "EndDate",
-		"Remark", "ModifyTime","NewCompany", "OriginAmount", "CurrencyUnit", "PaymentDate",
-	}
-	if e = item.Update(updateCols); e != nil {
-		resp.FailMsg("操作失败", "更新到预款登记失败, Err:"+e.Error(), c)
-		return
-	}
-
-	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)
-	err := c.ShouldBind(&req)
-	if err != nil {
-		errs, ok := err.(validator.ValidationErrors)
-		if !ok {
-			resp.FailData("参数解析失败", "Err:"+err.Error(), c)
-			return
-		}
-		resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
-		return
-	}
-
-	ob := new(fms.ContractPrePayment)
-	item, e := ob.Fetch(req.PrePayId)
-	if e != nil {
-		if e == utils.ErrNoRow {
-			resp.Fail("合同登记不存在或已被删除", c)
-			return
-		}
-		resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
-		return
-	}
-	e = item.Delete()
-	if e != nil {
-		resp.FailMsg("删除记录失败", "Err:"+e.Error(), c)
-		return
-	}
-
-	// 操作日志
-	//go func() {
-	//	opData := ""
-	//	opDataByte, e := json.Marshal(req)
-	//	if e != nil {
-	//		return
-	//	}
-	//	opData = string(opDataByte)
-	//
-	//	logItem := new(fms.ContractRegisterLog)
-	//	logItem.ContractRegisterId = req.ContractRegisterId
-	//	logItem.AdminId = int(adminInfo.AdminId)
-	//	logItem.AdminName = adminInfo.RealName
-	//	logItem.OpData = opData
-	//	logItem.OpType = fms.ContractRegisterOpTypeDel
-	//	logItem.CreateTime = nowTime
-	//	if e = logItem.Create(); e != nil {
-	//		return
-	//	}
-	//}()
-
-	resp.Ok("操作成功", c)
-}

+ 1108 - 0
controller/contract/pre_register.go

@@ -0,0 +1,1108 @@
+package contract
+
+import (
+	"fmt"
+	"github.com/gin-gonic/gin"
+	"github.com/go-playground/validator/v10"
+	"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"
+)
+
+// // RegisterController 合同登记
+type PreRegisterController struct{}
+
+// InvoiceList
+// @Title 开票/到款列表
+// @Description 开票/到款列表
+// @Param   Keyword			query	string	false	"关键词"
+// @Success 200 {object} fms.ContractInvoiceItem
+// @router /contract/pre_register/list [get]
+func (rg *PreRegisterController) List(c *gin.Context) {
+	var req fms.PreRegisterListReq
+	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
+	}
+	pageSize := req.PageSize
+	pageIndex := req.Current
+	if pageSize <= 0 {
+		pageSize = utils.PageSize20
+	}
+	if pageIndex <= 0 {
+		pageIndex = 1
+	}
+	cond := ` invoice_type IN (3, 4) `
+	pars := make([]interface{}, 0)
+	if req.Keyword != "" {
+		kw := "%" + req.Keyword + "%"
+		cond += ` AND company_name LIKE ? `
+		pars = append(pars, kw)
+	}
+	// 货币列表
+	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[0]})
+
+	total, list, e := fms.GetContractPreRegisterItemPageList(page, cond, pars)
+	if e != nil {
+		resp.FailMsg("获取失败", "获取预登记列表失败, Err: "+e.Error(), c)
+		return
+	}
+	serviceMap := make(map[int]string, 0)
+	registerIds := make([]int, 0)
+	for i := range list {
+		list[i].UnitName = unitMap[list[i].CurrencyUnit]
+		registerIds = append(registerIds, list[i].ContractRegisterId)
+	}
+
+	if len(registerIds) > 0 {
+		serviceMap, _, e = fmsService.GetContractServiceNameFormat(registerIds)
+		if e != nil {
+			resp.FailMsg("获取失败", e.Error(), c)
+			return
+		}
+	}
+
+	respList := make([]*fms.ContractPreRegisterList, 0)
+
+	for _, v := range list {
+		item := new(fms.ContractPreRegisterList)
+		item.ContractPreRegisterItem = v
+		item.ServicesName = serviceMap[v.ContractRegisterId]
+		respList = append(respList, item)
+	}
+
+	page.SetTotal(total)
+	baseData := new(base.BaseData)
+	baseData.SetPage(page)
+	baseData.SetList(respList)
+	resp.OkData("获取成功", baseData, c)
+}
+
+// Add
+// @Title 新增预登记
+// @Description 新增预登记
+// @Param	request  body  fms.PrepayAddReq  true  "type json string"
+// @Success 200 string "操作成功"
+// @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)
+		if !ok {
+			resp.FailData("参数解析失败", "Err:"+err.Error(), c)
+			return
+		}
+		resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
+		return
+	}
+	claims, _ := c.Get("adminInfo")
+	adminInfo := claims.(*system.SysAdmin)
+
+	// 日期校验
+	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
+		}
+	}
+
+	var currencyUnit string
+	if len(req.List) > 0 {
+		currencyUnit = req.List[0].CurrencyUnit
+	}
+	// 获取销售分组信息
+	sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
+	if e != nil {
+		resp.FailData("获取销售失败", "Err:"+e.Error(), c)
+		return
+	}
+	sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
+	for i := range sellerList {
+		sellerMap[sellerList[i].SellerId] = sellerList[i]
+	}
+
+	admin := new(crm.Admin)
+	sellerIds := strings.Split(req.SellerIds, ",")
+	if len(sellerIds) > 2 {
+		resp.Fail("最多只能选择两个销售", c)
+		return
+	}
+
+	var sellers []*crm.Admin
+	var pars []interface{}
+	cond := ``
+	if len(sellerIds) > 0 {
+		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.ContractRegister)
+	//ob.ContractCode = req.ContractCode
+	ob.CompanyName = req.CompanyName
+	ob.ProductIds = req.ProductIds
+	ob.StartDate = startDate
+	ob.EndDate = endDate
+	ob.Set()
+	ob.CurrencyUnit = currencyUnit
+	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
+			}
+		}
+	}
+
+	// 套餐信息
+	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
+	}
+
+	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
+		}
+
+		//预登记列表
+		pp := &fms.ContractPreRegister{
+			ContractRegisterId: ob.ContractRegisterId,
+			CompanyName:        req.CompanyName,
+			InvoiceType:        req.RegisterType,
+			AdminId:            int(adminInfo.AdminId),
+			AdminName:          adminInfo.AdminName,
+			ServiceProductId:   r.ServiceProductId,
+			IsPrePay:           1,
+			StartDate:          startDate,
+			EndDate:            endDate,
+			TimeBase:           base.TimeBase{},
+		}
+		pp.Set()
+		pp.CurrencyUnit = r.CurrencyUnit
+		if pp.InvoiceType == fms.ContractInvoiceTypePreMake {
+			//开票走开票字段
+			pp.InvoiceId = v.ContractInvoiceId
+			pp.InvoiceDate = registerDate
+			pp.OriginAmount = r.Amount
+			a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", pp.OriginAmount/rate), 64)
+			pp.Amount = a
+			pp.Remark = r.Remark
+			sellerItem := sellerMap[r.SellerId]
+			if sellerItem == nil {
+				resp.Fail("销售信息异常", c)
+				return
+			}
+
+			pp.SellerId = sellerItem.SellerId
+			pp.SellerName = sellerItem.SellerName
+			pp.SellerGroupId = sellerItem.GroupId
+			pp.SellerGroupName = sellerItem.GroupName
+			pp.SellerTeamId = sellerItem.TeamId
+			pp.SellerTeamName = sellerItem.TeamName
+		} else {
+			//到款
+			pp.ArriveId = v.ContractInvoiceId
+			pp.ArriveDate = registerDate
+			pp.ArriveOriginAmount = r.Amount
+			a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", pp.ArriveOriginAmount/rate), 64)
+			pp.ArriveAmount = a
+			pp.ArriveRemark = r.Remark
+		}
+
+		// 新增开票到款记录
+		if e = pp.Create(); e != nil {
+			resp.FailMsg("操作失败", "新增预登记失败, Err: "+e.Error(), c)
+			return
+		}
+
+		v.PreRegisterId = pp.PreRegisterId
+		if e = v.Update([]string{"PreRegisterId"}); e != nil {
+			fmt.Println("更新开票登记失败, Err: " + e.Error())
+			return
+		}
+	}
+
+	// 开票到款汇总
+	go fmsService.SummaryInvoicePaymentByContractRegisterId(ob.ContractRegisterId)
+
+	resp.Ok("操作成功", c)
+}
+
+// Edit
+// @Title 编辑预登记
+// @Description 编辑预登记
+// @Param	request  body  fms.ContractRegisterEditReq  true  "type json string"
+// @Success 200 string "操作成功"
+// @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)
+		if !ok {
+			resp.FailData("参数解析失败", "Err:"+err.Error(), c)
+			return
+		}
+		resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
+		return
+	}
+	claims, _ := c.Get("adminInfo")
+	adminInfo := claims.(*system.SysAdmin)
+
+	// 日期校验
+	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
+		}
+	}
+
+	var currencyUnit string
+	if len(req.List) > 0 {
+		currencyUnit = req.List[0].CurrencyUnit
+	}
+
+	// 获取销售分组信息
+	sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
+	if e != nil {
+		resp.FailData("获取销售失败", "Err:"+e.Error(), c)
+		return
+	}
+	sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
+	for i := range sellerList {
+		sellerMap[sellerList[i].SellerId] = sellerList[i]
+	}
+
+	admin := new(crm.Admin)
+	sellerIds := strings.Split(req.SellerIds, ",")
+	if len(sellerIds) > 2 {
+		resp.Fail("最多只能选择两个销售", c)
+		return
+	}
+	var sellers []*crm.Admin
+	var pars []interface{}
+	cond := ``
+	if len(sellerIds) > 0 {
+		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.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()
+	ob.CurrencyUnit = currencyUnit
+	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
+			}
+		}
+	}
+
+	// 套餐信息
+	serviceAmountMap := make(map[int]float64)
+	serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
+	if e != nil {
+		resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
+		return
+	}
+	updateCols := []string{
+		"ProductIds", "CompanyName", "SellerId", "SellerName", "StartDate", "EndDate",
+		"RaiSellerId", "RaiSellerName", "ModifyTime", "CurrencyUnit",
+	}
+
+	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
+		}
+
+		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
+		}
+
+		//预登记列表
+		pp := &fms.ContractPreRegister{
+			PreRegisterId:      r.PreRegisterId,
+			ContractRegisterId: ob.ContractRegisterId,
+			CompanyName:        req.CompanyName,
+			InvoiceType:        req.RegisterType,
+			AdminId:            int(adminInfo.AdminId),
+			AdminName:          adminInfo.AdminName,
+			ServiceProductId:   r.ServiceProductId,
+			IsPrePay:           1,
+			StartDate:          startDate,
+			EndDate:            endDate,
+			TimeBase:           base.TimeBase{},
+		}
+		pp.Set()
+		pp.CurrencyUnit = r.CurrencyUnit
+		ppUpdateCols := make([]string, 0)
+		if pp.InvoiceType == fms.ContractInvoiceTypePreMake {
+			//开票走开票字段
+			pp.Remark = r.Remark
+			pp.InvoiceDate = registerDate
+			pp.OriginAmount = r.Amount
+			a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", pp.OriginAmount/rate), 64)
+			pp.Amount = a
+
+			sellerItem := sellerMap[r.SellerId]
+			if sellerItem == nil {
+				resp.Fail("销售信息异常", c)
+				return
+			}
+
+			pp.InvoiceId = v.ContractInvoiceId
+			pp.SellerId = sellerItem.SellerId
+			pp.SellerName = sellerItem.SellerName
+			pp.SellerGroupId = sellerItem.GroupId
+			pp.SellerGroupName = sellerItem.GroupName
+			pp.SellerTeamId = sellerItem.TeamId
+			pp.SellerTeamName = sellerItem.TeamName
+			ppUpdateCols = append(ppUpdateCols, "InvoiceDate", "Amount", "OriginAmount", "SellerId",
+				"SellerName", "SellerGroupId", "SellerGroupName", "SellerTeamId", "SellerTeamName", "InvoiceId")
+		} else {
+			//到款
+			pp.ArriveRemark = r.Remark
+			pp.ArriveDate = registerDate
+			pp.ArriveId = v.ContractRegisterId
+			pp.ArriveOriginAmount = r.Amount
+			a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", pp.ArriveOriginAmount/rate), 64)
+			pp.ArriveAmount = a
+			ppUpdateCols = append(ppUpdateCols, "CurrencyUnit", "ArriveDate", "ArriveAmount", "ArriveOriginAmount", "ArriveId")
+		}
+
+		if pp.PreRegisterId == 0 {
+			if e = pp.Create(); e != nil {
+				resp.FailMsg("操作失败", "新增预登记失败, Err: "+e.Error(), c)
+				return
+			}
+			v.PreRegisterId = pp.PreRegisterId
+		} else {
+			ppUpdateCols = append(ppUpdateCols,
+				"CurrencyUnit", "CompanyName", "Remark", "ArriveRemark", "InvoiceTime", "ArriveTime",
+				"ServiceProductId", "CurrencyUnit", "StartDate", "EndDate", "ModifyTime")
+			if e = pp.Update(ppUpdateCols); e != nil {
+				resp.FailMsg("操作失败", "更新预登记记录失败, Err: "+e.Error(), c)
+				return
+			}
+		}
+
+		invoiceList = append(invoiceList, v)
+	}
+	invoiceUpdateCols := []string{
+		"CurrencyUnit", "OriginAmount", "Amount", "InvoiceDate", "AdminId", "AdminName", "Remark",
+		"ServiceProductId", "StartDate", "EndDate", "ModifyTime",
+	}
+	// 更新合同登记、套餐、开票到款
+	if e = fms.UpdateContractPreRegister(ob, updateCols, serviceList, invoiceList, invoiceUpdateCols, req.DelInvoiceIds, req.DelPreRegisterIds); 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_register/del [post]
+func (rg *PreRegisterController) Del(c *gin.Context) {
+	req := new(fms.PreRegisterDelReq)
+	err := c.ShouldBind(&req)
+	if err != nil {
+		errs, ok := err.(validator.ValidationErrors)
+		if !ok {
+			resp.FailData("参数解析失败", "Err:"+err.Error(), c)
+			return
+		}
+		resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
+		return
+	}
+
+	if req.InvoiceId != 0 {
+		ob := new(fms.ContractInvoice)
+		item, e := ob.Fetch(req.InvoiceId)
+		if e != nil {
+			if e == utils.ErrNoRow {
+				resp.Fail("合同登记不存在或已被删除", c)
+				return
+			}
+			resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
+			return
+		}
+		e = item.Delete()
+		if e != nil {
+			resp.FailMsg("删除记录失败", "Err:"+e.Error(), c)
+			return
+		}
+	}
+
+	if req.ArriveId != 0 {
+		ob := new(fms.ContractInvoice)
+		item, e := ob.Fetch(req.ArriveId)
+		if e != nil {
+			if e == utils.ErrNoRow {
+				resp.Fail("合同登记不存在或已被删除", c)
+				return
+			}
+			resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
+			return
+		}
+		e = item.Delete()
+		if e != nil {
+			resp.FailMsg("删除记录失败", "Err:"+e.Error(), c)
+			return
+		}
+	}
+
+	ob := new(fms.ContractPreRegister)
+	item, e := ob.Fetch(req.PreRegisterId)
+	if e != nil {
+		if e == utils.ErrNoRow {
+			resp.Fail("预登记记录不存在或已被删除", c)
+			return
+		}
+		resp.FailMsg("获取预登记失败", "Err:"+e.Error(), c)
+		return
+	}
+	e = item.Delete()
+	if e != nil {
+		resp.FailMsg("删除预登记记录失败", "Err:"+e.Error(), c)
+		return
+	}
+
+	//todo 合同看情况要不要删
+
+	resp.Ok("操作成功", c)
+}
+
+// Detail
+// @Title 预登记记录详情
+// @Description 预登记记录详情
+// @Param	request  body  fms.PreRegisterDetailReq  true  "type json string"
+// @Success 200 string "操作成功"
+// @router /contract/pre_register/detail [post]
+func (rg *PreRegisterController) Detail(c *gin.Context) {
+	req := new(fms.PreRegisterDetailReq)
+	err := c.ShouldBind(&req)
+	if err != nil {
+		errs, ok := err.(validator.ValidationErrors)
+		if !ok {
+			resp.FailData("参数解析失败", "Err:"+err.Error(), c)
+			return
+		}
+		resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
+		return
+	}
+
+	ob := new(fms.ContractRegister)
+	item, e := ob.Fetch(req.ContractRegisterId)
+	if e != nil {
+		if e == utils.ErrNoRow {
+			resp.Fail("合同登记不存在或已被删除", c)
+			return
+		}
+		resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
+		return
+	}
+
+	nItme := fms.ContractRegisterItem{
+		ContractRegisterId: item.ContractRegisterId,
+		ContractCode:       item.ContractCode,
+		RelateContractCode: item.RelateContractCode,
+		CrmContractId:      item.CrmContractId,
+		ContractSource:     item.ContractSource,
+		CompanyName:        item.CompanyName,
+		ActualCompanyName:  item.ActualCompanyName,
+		ProductIds:         item.ProductIds,
+		SellerId:           item.SellerId,
+		SellerName:         item.SellerName,
+		RaiSellerId:        item.RaiSellerId,
+		RaiSellerName:      item.RaiSellerName,
+		ContractType:       item.ContractType,
+		ContractAmount:     item.ContractAmount,
+		InvoicedAmount:     item.InvoicedAmount,
+		PaymentAmount:      item.PaymentAmount,
+		CurrencyUnit:       item.CurrencyUnit,
+		RMBRate:            item.RMBRate,
+		StartDate:          item.StartDate.Format(utils.FormatDate),
+		EndDate:            item.EndDate.Format(utils.FormatDate),
+		SignDate:           item.SignDate.Format(utils.FormatDate),
+		AgreedPayTime:      item.AgreedPayTime,
+		ContractStatus:     item.ContractStatus,
+		RegisterStatus:     item.RegisterStatus,
+		Remark:             item.Remark,
+		ServiceRemark:      item.ServiceRemark,
+		HasPayment:         item.HasPayment,
+		NewCompany:         item.NewCompany,
+		CreateTime:         item.CreateTime.Format(utils.FormatDateTime),
+	}
+
+	if nItme.StartDate == "0001-01-01" {
+		nItme.StartDate = ""
+	}
+	if nItme.EndDate == "0001-01-01" {
+		nItme.EndDate = ""
+	}
+
+	cond := ``
+	pars := make([]interface{}, 0)
+
+	if req.InvoiceId == 0 && req.ArriveId == 0 {
+		cond = `contract_register_id = ? AND invoice_type = ? `
+		pars = append(pars, req.ContractRegisterId, req.InvoiceType)
+	} else {
+		cond = `contract_register_id = ? AND invoice_type = ?  AND contract_invoice_id =? `
+		pars = append(pars, req.ContractRegisterId, req.InvoiceType)
+	}
+
+	if req.InvoiceType == 4 {
+		pars = append(pars, req.ArriveId)
+	} else {
+		pars = append(pars, req.InvoiceId)
+	}
+	list, e := fms.GetContractInvoiceDetailItemList(cond, pars)
+	if e != nil {
+		err = fmt.Errorf("获取开票到款列表失败, Err: %s", e.Error())
+		return
+	}
+
+	//获取ficc小套餐品种
+	sysConf := new(system.SysConfig)
+	confCond := `config_code = ?`
+	confPars := make([]interface{}, 0)
+	confPars = append(confPars, system.ConfigKeyCrmPermissionFiccClassify)
+	confItem, e := sysConf.FetchByCondition(confCond, confPars)
+	if e != nil {
+		resp.FailData("获取失败", "Err:"+e.Error(), c)
+		return
+	}
+	if confItem.ConfigValue == "" {
+		resp.FailData("获取失败", "FICC品种分类配置为空", c)
+		return
+	}
+	classifyArr := strings.Split(confItem.ConfigValue, ",")
+	if len(classifyArr) == 0 {
+		resp.FailData("获取失败", "FICC品种分类配置为空", c)
+		return
+	}
+	// 获取FICC权限
+	ficcCond := `enabled = 1 AND permission_type = 0 AND product_id = ? AND classify_name IN ?`
+	ficcPars := make([]interface{}, 0)
+	ficcPars = append(ficcPars, 1, classifyArr)
+	items, e := crm.GetPermissionSetItemsByCondition(ficcCond, ficcPars)
+	if e != nil {
+		resp.FailData("获取失败", "获取FICC权限信息失败, Err: "+e.Error(), c)
+		return
+	}
+	ficcItemMap := make(map[string][]*crm.PermissionSetItem, 0)
+	for i := range items {
+		if ficcItemMap[items[i].ClassifyName] == nil {
+			ficcItemMap[items[i].ClassifyName] = make([]*crm.PermissionSetItem, 0)
+		}
+		ficcItemMap[items[i].ClassifyName] = append(ficcItemMap[items[i].ClassifyName], items[i])
+	}
+
+	sTempIdMap := make(map[string]int, 0)
+
+	for i := range classifyArr {
+		if classifyArr[i] == "市场策略" {
+			continue
+		}
+		checkList := make([]int, 0)
+		if classifyArr[i] == "宏观经济" {
+			checkList = append(checkList, 1)
+		}
+
+		pItem := fms.ContractServiceTemplateItem{
+			ServiceTemplateId: 90000 + i*100,
+		}
+
+		ficcItems := ficcItemMap[classifyArr[i]]
+		for _, ficcItem := range ficcItems {
+			sTempIdMap[strconv.Itoa(ficcItem.ChartPermissionId)] = pItem.ServiceTemplateId + ficcItem.ChartPermissionId
+		}
+	}
+
+	services, e := fms.GetContractServiceAndDetailList(req.ContractRegisterId)
+	if e != nil {
+		err = fmt.Errorf(fmt.Sprint("查找合同服务异常", e))
+		return
+	}
+
+	serviceTemplateIdSlice := make([]string, 0)
+	for _, service := range services {
+		if service.Title == "FICC小套餐" {
+			serviceTemplateIdSlice = strings.Split(service.ChartPermissionIds, ",")
+		}
+	}
+
+	serviceTemplateIds := make([]int, 0)
+	for _, v := range serviceTemplateIdSlice {
+		serviceTemplateIds = append(serviceTemplateIds, sTempIdMap[v])
+	}
+	respItem := fms.ContractPreRegisterDetail{
+		ContractRegisterItem: &nItme,
+		List:                 list,
+		Services:             services,
+		ServiceTemplateIds:   serviceTemplateIds,
+	}
+
+	resp.OkData("获取成功", respItem, c)
+}
+
+// Save
+// @Title 预登记保存
+// @Description 预登记保存
+// @Param	request  body  fms.PrepayAddReq  true  "type json string"
+// @Success 200 string "操作成功"
+// @router /contract/pre_register/save [post]
+func (rg *PreRegisterController) Save(c *gin.Context) {
+	req := new(fms.PreRegisterSaveReq)
+	err := c.ShouldBind(&req)
+	if err != nil {
+		errs, ok := err.(validator.ValidationErrors)
+		if !ok {
+			resp.FailData("参数解析失败", "Err:"+err.Error(), c)
+			return
+		}
+		resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
+		return
+	}
+	claims, _ := c.Get("adminInfo")
+	adminInfo := claims.(*system.SysAdmin)
+
+	// 日期校验
+	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
+		}
+	}
+
+	// 获取销售分组信息
+	sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
+	if e != nil {
+		resp.FailData("获取销售失败", "Err:"+e.Error(), c)
+		return
+	}
+	sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
+	for i := range sellerList {
+		sellerMap[sellerList[i].SellerId] = sellerList[i]
+	}
+
+	admin := new(crm.Admin)
+	sellerIds := strings.Split(req.SellerIds, ",")
+	if len(sellerIds) > 2 {
+		resp.Fail("最多只能选择两个销售", c)
+		return
+	}
+
+	var sellers []*crm.Admin
+	var pars []interface{}
+	cond := ``
+	if len(sellerIds) > 0 {
+		cond = ` admin_id in (?) `
+		pars = append(pars, sellerIds)
+		sellers, e = admin.List(cond, pars)
+		if e != nil {
+			resp.FailMsg("获取销售信息失败", "获取销售信息失败, Err: "+e.Error(), c)
+			return
+		}
+	}
+	updateCols := []string{"CompanyName", "ProductIds", "StartDate", "EndDate", "ModifyTime"}
+
+	//更新合同
+	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()
+	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
+				updateCols = append(updateCols, "SellerId", "SellerName")
+			} else if v.DepartmentId == crm.RaiSellerDepartmentId {
+				ob.RaiSellerId = v.AdminId
+				ob.RaiSellerName = v.AdminName
+				updateCols = append(updateCols, "RaiSellerId", "RaiSellerName")
+			}
+		}
+	}
+
+	// 套餐信息
+	serviceAmountMap := make(map[int]float64)
+	serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
+	if e != nil {
+		resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
+		return
+	}
+	invoiceUpdateCols := make([]string, 0)
+	invoiceHandleType := 0
+	invoiceList := make([]*fms.ContractInvoice, 0)
+	ppList := make([]*fms.ContractPreRegister, 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
+		}
+
+		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,
+			TimeBase:           base.TimeBase{},
+		}
+		v.TimeBase.ModifyTime = time.Now()
+
+		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
+			invoiceUpdateCols = append(invoiceUpdateCols, "SellerId", "SellerName", "SellerGroupId",
+				"SellerGroupName", "SellerTeamId", "SellerTeamName")
+		}
+
+		// 新增开票到款记录
+		if v.ContractInvoiceId != 0 {
+			//更新
+			invoiceHandleType = 1
+			invoiceUpdateCols = append(invoiceUpdateCols, "OriginAmount", "CurrencyUnit",
+				"InvoiceDate", "Remark", "ServiceProductId", "StartDate", "EndDate", "ModifyTime")
+		} else {
+			//新增
+			invoiceHandleType = 2
+		}
+		invoiceList = append(invoiceList, v)
+
+		//预登记列表
+		ppUpdateCols := make([]string, 0)
+		pp := &fms.ContractPreRegister{
+			PreRegisterId:      r.PreRegisterId,
+			ContractRegisterId: ob.ContractRegisterId,
+			CompanyName:        req.CompanyName,
+			InvoiceType:        req.RegisterType,
+			InvoiceDate:        registerDate,
+			AdminId:            int(adminInfo.AdminId),
+			AdminName:          adminInfo.AdminName,
+			ServiceProductId:   r.ServiceProductId,
+			IsPrePay:           1,
+			StartDate:          startDate,
+			EndDate:            endDate,
+			TimeBase:           base.TimeBase{},
+		}
+		pp.Set()
+		pp.CurrencyUnit = r.CurrencyUnit
+		if pp.InvoiceType == fms.ContractInvoiceTypePreMake {
+			//开票走开票字段
+			pp.Remark = r.Remark
+			pp.InvoiceDate = registerDate
+			pp.OriginAmount = r.Amount
+			a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", pp.OriginAmount/rate), 64)
+			pp.Amount = a
+
+			sellerItem := sellerMap[r.SellerId]
+			if sellerItem == nil {
+				resp.Fail("销售信息异常", c)
+				return
+			}
+
+			pp.SellerId = sellerItem.SellerId
+			pp.SellerName = sellerItem.SellerName
+			pp.SellerGroupId = sellerItem.GroupId
+			pp.SellerGroupName = sellerItem.GroupName
+			pp.SellerTeamId = sellerItem.TeamId
+			pp.SellerTeamName = sellerItem.TeamName
+			ppUpdateCols = append(ppUpdateCols, "InvoiceDate", "Amount", "OriginAmount", "SellerId",
+				"SellerName", "SellerGroupId", "SellerGroupName", "SellerTeamId", "SellerTeamName", "Remark")
+		} else {
+			//到款
+			pp.ArriveRemark = r.Remark
+			pp.ArriveDate = registerDate
+			pp.ArriveOriginAmount = r.Amount
+			a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", pp.ArriveOriginAmount/rate), 64)
+			pp.ArriveAmount = a
+			ppUpdateCols = append(ppUpdateCols, "ArriveRemark", "CurrencyUnit", "ArriveDate", "ArriveAmount", "ArriveOriginAmount")
+		}
+
+		ppUpdateCols = append(ppUpdateCols,
+			"CompanyName", "AdminId", "AdminName", "ServiceProductId",
+			"CurrencyUnit", "StartDate", "EndDate", "ModifyTime")
+
+		if e = pp.Update(ppUpdateCols); e != nil {
+			resp.FailMsg("操作失败", "更新预登记记录失败, Err: "+e.Error(), c)
+			return
+		}
+		ppList = append(ppList, pp)
+	}
+	if e = fms.UpdateContractRegisterPre(ob, updateCols, serviceList, invoiceList, invoiceUpdateCols, invoiceHandleType, ppList); e != nil {
+		resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
+		return
+	}
+	// 开票到款汇总
+	go fmsService.SummaryInvoicePaymentByContractRegisterId(ob.ContractRegisterId)
+
+	resp.Ok("操作成功", c)
+}

文件差异内容过多而无法显示
+ 440 - 232
controller/contract/register.go


+ 91 - 7
controller/contract/service.go

@@ -5,8 +5,11 @@ import (
 	"github.com/go-playground/validator/v10"
 	"hongze/fms_api/controller/resp"
 	"hongze/fms_api/global"
+	"hongze/fms_api/models/crm"
 	"hongze/fms_api/models/fms"
+	"hongze/fms_api/models/system"
 	"strconv"
+	"strings"
 )
 
 // ServiceController 合同套餐
@@ -36,7 +39,7 @@ func (sr *ServiceController) List(c *gin.Context) {
 	var err error
 	if productIdStr == "" {
 		list, err = fms.GetContractServiceTemplateSecond()
-	}else{
+	} else {
 		productId, _ = strconv.Atoi(productIdStr)
 		list, err = fms.GetContractServiceTemplateMapByProductId(productId)
 	}
@@ -92,11 +95,92 @@ func (sr *ServiceController) List(c *gin.Context) {
 		}
 		v.Detail = detail
 		v.Children = secFormatList
+
+		if v.Title == "FICC小套餐" {
+			//获取ficc小套餐品种
+			sysConf := new(system.SysConfig)
+			confCond := `config_code = ?`
+			confPars := make([]interface{}, 0)
+			confPars = append(confPars, system.ConfigKeyCrmPermissionFiccClassify)
+			confItem, e := sysConf.FetchByCondition(confCond, confPars)
+			if e != nil {
+				resp.FailData("获取失败", "Err:"+e.Error(), c)
+				return
+			}
+			if confItem.ConfigValue == "" {
+				resp.FailData("获取失败", "FICC品种分类配置为空", c)
+				return
+			}
+			classifyArr := strings.Split(confItem.ConfigValue, ",")
+			if len(classifyArr) == 0 {
+				resp.FailData("获取失败", "FICC品种分类配置为空", c)
+				return
+			}
+
+			// 获取FICC权限
+			ficcCond := `enabled = 1 AND permission_type = 0 AND product_id = ? AND classify_name IN ?`
+			ficcPars := make([]interface{}, 0)
+			ficcPars = append(ficcPars, 1, classifyArr)
+			items, e := crm.GetPermissionSetItemsByCondition(ficcCond, ficcPars)
+			if e != nil {
+				resp.FailData("获取失败", "获取FICC权限信息失败, Err: "+e.Error(), c)
+				return
+			}
+			ficcItemMap := make(map[string][]*crm.PermissionSetItem, 0)
+			for i := range items {
+				if ficcItemMap[items[i].ClassifyName] == nil {
+					ficcItemMap[items[i].ClassifyName] = make([]*crm.PermissionSetItem, 0)
+				}
+				ficcItemMap[items[i].ClassifyName] = append(ficcItemMap[items[i].ClassifyName], items[i])
+			}
+
+			for i := range classifyArr {
+				if classifyArr[i] == "市场策略" {
+					continue
+				}
+				checkList := make([]int, 0)
+				if classifyArr[i] == "宏观经济" {
+					checkList = append(checkList, 1)
+				}
+
+				pItem := fms.ContractServiceTemplateItem{
+					ServiceTemplateId: 90000 + i*100,
+					ProductId:         1,
+					Pid:               v.ServiceTemplateId,
+					ParentTitle:       v.Title,
+					Title:             classifyArr[i],
+				}
+
+				childs := make([]*fms.ContractServiceTemplateMapItems, 0)
+				ficcItems := ficcItemMap[classifyArr[i]]
+				for _, ficcItem := range ficcItems {
+					tempItem := fms.ContractServiceTemplateItem{
+						ServiceTemplateId: pItem.ServiceTemplateId + ficcItem.ChartPermissionId,
+						ProductId:         1,
+						Pid:               pItem.ServiceTemplateId,
+						ParentTitle:       pItem.Title,
+						Title:             ficcItem.PermissionName,
+						ChartPermissionId: ficcItem.ChartPermissionId,
+					}
+					newpItem := fms.ContractServiceTemplateMapItems{
+						ContractServiceTemplateItem: tempItem,
+					}
+					childs = append(childs, &newpItem)
+				}
+				tempItem := fms.ContractServiceTemplateMapItems{
+					ContractServiceTemplateItem: pItem,
+					Children:                    childs,
+				}
+
+				v.Children = append(v.Children, &tempItem)
+			}
+		}
+
 		allMap[item.ProductId] = append(allMap[item.ProductId], v)
 	}
 	allTitleMap := map[int]string{
-		1:"FICC套餐",
-		2:"权益套餐",
+		1: "FICC套餐",
+		2: "权益套餐",
 	}
 	if productId == 0 {
 		tmp1 := &fms.ContractServiceTemplateList{
@@ -109,7 +193,7 @@ func (sr *ServiceController) List(c *gin.Context) {
 		}
 		respList = append(respList, tmp1)
 		respList = append(respList, tmp2)
-	}else{
+	} else {
 		tmp := &fms.ContractServiceTemplateList{
 			Title:    allTitleMap[productId],
 			Children: allMap[productId],
@@ -144,7 +228,7 @@ func (sr *ServiceController) SimpleList(c *gin.Context) {
 			for _, sv := range industryList {
 				allList = append(allList, sv)
 			}
-		}else{
+		} else {
 			allList = append(allList, list[i])
 		}
 	}
@@ -156,8 +240,8 @@ func (sr *ServiceController) SimpleList(c *gin.Context) {
 		allMap[item.ProductId] = append(allMap[item.ProductId], v)
 	}
 	allTitleMap := map[int]string{
-		1:"FICC套餐",
-		2:"权益套餐",
+		1: "FICC套餐",
+		2: "权益套餐",
 	}
 	tmp1 := &fms.ContractServiceTemplateList{
 		Title:    allTitleMap[1],

+ 18 - 0
controller/crm/company_seller.go

@@ -66,3 +66,21 @@ func (rg *CompanySellerController) GroupList(c *gin.Context) {
 	}
 	resp.OkData("获取成功", list, c)
 }
+
+// List
+// @Title 销售列表
+// @Description 销售列表
+// @Success 200 {object} crm.SellerAdminWithGroupList
+// @router /crm/company_seller/all_list [get]
+func (rg *CompanySellerController) AllList(c *gin.Context) {
+	ficcList, raiLits, e := crmService.GetSellerDepartmentListWithGroupAndTeamByDepartment()
+	if e != nil {
+		resp.FailData("获取销售失败", "Err:"+e.Error(), c)
+		return
+	}
+	respItem := crm.AllSellerResp{
+		FiccSeller: ficcList,
+		RaiSeller:  raiLits,
+	}
+	resp.OkData("获取成功", respItem, c)
+}

+ 54 - 20
controller/crm/contract.go

@@ -60,21 +60,24 @@ func (rg *ContractController) SearchList(c *gin.Context) {
 	}
 
 	// 获取代付合同实际使用方
-	peyContractIds := make([]int, 0)
+	businessContractIds := make([]int, 0)
+	payContractIds := make([]int, 0)
 	for i := range list {
 		if list[i].ContractBusinessType == crm.ContractTypePayment {
-			peyContractIds = append(peyContractIds, list[i].ContractId)
+			payContractIds = append(payContractIds, list[i].ContractId)
+		} else {
+			businessContractIds = append(businessContractIds, list[i].ContractId)
 		}
 	}
 	payCompanyMap := make(map[int]string, 0)      // 代付合同实际使用方
 	payContractCodeMap := make(map[int]string, 0) // 代付合同实际使用方合同编号
-	if len(peyContractIds) > 0 {
+	if len(payContractIds) > 0 {
 		payCond := `a.status IN ('已签回', '已审批') AND b.payment_on_behalf_contract_id IN ?`
 		payPars := make([]interface{}, 0)
-		payPars = append(payPars, peyContractIds)
+		payPars = append(payPars, payContractIds)
 		payList, e := crm.GetPayCompanyByContractIds(payCond, payPars)
 		if e != nil {
-			resp.FailMsg("获取失败", "获取代付合同信息失败, Err: "+e.Error(), c)
+			resp.FailMsg("获取失败", "获取代付合同实际使用方信息失败, Err: "+e.Error(), c)
 			return
 		}
 		for i := range payList {
@@ -82,6 +85,21 @@ func (rg *ContractController) SearchList(c *gin.Context) {
 			payContractCodeMap[payList[i].PaymentOnBehalfContractId] = payList[i].ContractCode
 		}
 	}
+	// 获取业务合同的所有代付方信息
+	businessPayMap := make(map[int]string, 0)
+	if len(businessContractIds) > 0 {
+		businessCond := `b.status IN ('已签回', '已审批') AND a.contract_id IN ?`
+		businessPars := make([]interface{}, 0)
+		businessPars = append(businessPars, businessContractIds)
+		businessPayCompanies, e := crm.GetContractActualPayCompaniesByContractIds(businessCond, businessPars)
+		if e != nil {
+			resp.FailMsg("获取失败", "获取业务合同代付方信息失败, Err: "+e.Error(), c)
+			return
+		}
+		for i := range businessPayCompanies {
+			businessPayMap[businessPayCompanies[i].ContractId] = businessPayCompanies[i].ActualPayCompanies
+		}
+	}
 
 	respList := make([]*crm.ContractSearchListResp, 0)
 	for i := range list {
@@ -92,21 +110,37 @@ func (rg *ContractController) SearchList(c *gin.Context) {
 			contractTypeKey = fms.ContractTypeAgentPay
 		}
 
-		respList = append(respList, &crm.ContractSearchListResp{
-			ContractId:         list[i].ContractId,
-			ContractCode:       list[i].ContractCode,
-			ProductId:          list[i].ProductId,
-			CompanyName:        list[i].CompanyName,
-			RelateContractCode: payContractCodeMap[list[i].ContractId],
-			ActualCompanyName:  payCompanyMap[list[i].ContractId],
-			SellerId:           list[i].SellerId,
-			SellerName:         list[i].SellerName,
-			ContractTypeKey:    contractTypeKey,
-			ContractType:       contractType,
-			Price:              list[i].Price,
-			StartDate:          utils.TimeTransferString(utils.FormatDate, list[i].StartDate),
-			EndDate:            utils.TimeTransferString(utils.FormatDate, list[i].EndDate),
-		})
+		respItem := &crm.ContractSearchListResp{
+			ContractId:              list[i].ContractId,
+			ContractCode:            list[i].ContractCode,
+			ProductId:               list[i].ProductId,
+			CompanyName:             list[i].CompanyName,
+			RelateContractCode:      payContractCodeMap[list[i].ContractId],
+			ActualCompanyName:       payCompanyMap[list[i].ContractId],
+			SellerId:                list[i].SellerId,
+			SellerName:              list[i].SellerName,
+			ContractTypeKey:         contractTypeKey,
+			ContractType:            contractType,
+			ContractBusinessTypeInt: 0,
+			Price:                   list[i].Price,
+			StartDate:               utils.TimeTransferString(utils.FormatDate, list[i].StartDate),
+			EndDate:                 utils.TimeTransferString(utils.FormatDate, list[i].EndDate),
+			ActualPayCompanies: businessPayMap[list[i].ContractId],
+		}
+		if list[i].ContractBusinessType == crm.ContractTypePayment {
+			respItem.ContractBusinessTypeInt = 2
+		}else {
+			respItem.ContractBusinessTypeInt = 1
+		}
+		if list[i].ContractType == "新签合同"{
+			respItem.ContractTypeInt = 1
+		} else if list[i].ContractType == "续约合同"{
+			respItem.ContractTypeInt = 2
+		} else if list[i].ContractType == "补充协议"{
+			respItem.ContractTypeInt = 3
+		}
+		respList = append(respList, respItem)
+
 	}
 
 	page.SetTotal(total)

+ 1 - 1
controller/resp/base.go

@@ -22,7 +22,7 @@ type ResultData struct {
 	Code   int         `json:"code" description:"状态码"`
 	Msg    string      `json:"msg" description:"提示信息"`
 	Data   interface{} `json:"data" description:"返回数据"`
-	ErrMsg string      `json:"-" description:"错误信息,不用返回给前端,只是做日志记录"`
+	ErrMsg string      `json:"errMsg" description:"错误信息,不用返回给前端,只是做日志记录"`
 }
 
 func result(code int, resultData ResultData, c *gin.Context) {

+ 24 - 1
models/crm/contract.go

@@ -88,9 +88,12 @@ type ContractSearchListResp struct {
 	SellerName      string  `json:"seller_name" description:"销售名称"`
 	ContractTypeKey int     `json:"contract_type_key" description:"FMS合同类型: 1-新签; 2-续约; 3-代付; 4-补充协议;"`
 	ContractType    string  `json:"contract_type" description:"CRM合同类型: 新签合同; 续约合同; 补充协议;"`
+	ContractTypeInt    int  `json:"contract_type_int" description:"CRM合同类型: 1新签合同; 2续约合同; 3补充协议;"`
+	ContractBusinessTypeInt    int  `json:"contract_business_type_int" description:"合同业务类型,1'业务合同', 2'代付合同;"`
 	Price           float64 `json:"price" description:"合同金额"`
 	StartDate       string  `json:"start_date" description:"合同开始日期"`
 	EndDate         string  `json:"end_date" description:"合同结束日期"`
+	ActualPayCompanies string  `json:"actual_pay_companies" description:"该合同关联的所有代付方, 英文逗号拼接"`
 }
 
 // PayCompanyRelation 代付合同
@@ -101,7 +104,7 @@ type PayCompanyRelation struct {
 	PaymentOnBehalfContractId int    `description:"实际使用方合同ID"`
 }
 
-// GetPayCompanyByContractIds 通过合同IDs获取代付客户信息
+// GetPayCompanyByContractIds 通过代付合同IDs获取关联客户信息
 func GetPayCompanyByContractIds(condition string, pars []interface{}) (results []*PayCompanyRelation, err error) {
 	results = make([]*PayCompanyRelation, 0)
 	query := global.MYSQL["report"].
@@ -114,6 +117,26 @@ func GetPayCompanyByContractIds(condition string, pars []interface{}) (results [
 	return
 }
 
+// ContractActualPayCompanies 代付合同信息
+type ContractActualPayCompanies struct {
+	ContractId         int    `json:"contract_id" description:"业务合同ID"`
+	ActualPayCompanies string `json:"actual_pay_companies" description:"关联的代付方名称, 英文逗号拼接"`
+}
+
+// GetContractActualPayCompaniesByContractIds 通过合同IDs获取代付客户信息
+func GetContractActualPayCompaniesByContractIds(condition string, pars []interface{}) (results []*ContractActualPayCompanies, err error) {
+	results = make([]*ContractActualPayCompanies, 0)
+	query := global.MYSQL["report"].
+		Table("contract_relation AS a").
+		Select("a.contract_id, GROUP_CONCAT(DISTINCT b.company_name) AS actual_pay_companies").
+		Joins("JOIN contract AS b ON a.payment_on_behalf_contract_id = b.contract_id").
+		Where("b.is_delete = 0").
+		Where(condition, pars...).
+		Group("a.contract_id")
+	err = query.Find(&results).Error
+	return
+}
+
 // ContractDetail 合同详情信息(包含服务信息等)
 type ContractDetail struct {
 	Contract

+ 5 - 0
models/crm/sys_group.go

@@ -36,3 +36,8 @@ func (m *SysGroup) Count(condition string, pars []interface{}) (total int64, err
 		Count(&total).Error
 	return
 }
+
+type AllSellerResp struct {
+	FiccSeller []*SellerAdminWithGroupTeam
+	RaiSeller []*SellerAdminWithGroupTeam
+}

+ 21 - 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 // 年付
@@ -39,6 +41,15 @@ const (
 	ContractPaymentPayTypeOther    = 4 // 次付
 	ContractPaymentPayTypeAbnormal = 5 // 异常
 
+	// 2.5 新合同类型
+	ContractTypeSelf   = 0 // 自付
+	ContractTypebehalf = 1 // 代付
+
+	// 2.5 子合同类型
+	NewContractTypeNew      = 1 // 新签
+	NewContractTypeRenew    = 2 // 续约
+	NewContractTypePlus     = 4 // 补充协议
+
 	// 基础货币代码(人民币)
 	BaseCurrencyCode = "CNY"
 )

+ 105 - 11
models/fms/contract_invoice.go

@@ -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:"约定结束时间"`
+	PreRegisterId      int       `gorm:"column:pre_register_id" json:"pre_register_id" 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,7 +59,10 @@ 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:"创建时间"`
+	CompanyName        string  `gorm:"column:company_name" json:"company_name" description:"客户名称"`
 }
 
 func (c *ContractInvoice) Create() (err error) {
@@ -79,6 +85,12 @@ 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
@@ -208,7 +222,7 @@ func formatContractInvoice2ItemList(list []*ContractInvoice) (itemList []*Contra
 type ContractInvoiceListReq struct {
 	InvoiceType      int     `json:"invoice_type" form:"invoice_type" binding:"oneof=1 2" description:"类型: 1-开票登记; 2-到款登记"`
 	SellerIds        string  `json:"seller_ids" form:"seller_ids" description:"销售ID, 多个id用逗号拼接"`
-	ContractCode     string  `json:"contract_code" form:"contract_code" binding:"omitempty" description:"合同编号"`
+	Keyword          string  `json:"keyword" form:"keyword" binding:"omitempty" description:"搜索关键字"`
 	StartDate        string  `json:"start_date" form:"start_date" binding:"omitempty,datetime=2006-01-02" description:"开始日期"`
 	EndDate          string  `json:"end_date" form:"end_date" binding:"omitempty,datetime=2006-01-02" description:"结束日期"`
 	MinAmount        float64 `json:"min_amount" form:"min_amount" description:"开票金额区间-最小值"`
@@ -220,9 +234,11 @@ type ContractInvoiceListReq struct {
 
 // GetContractInvoiceItemPageList 获取合同开票/到款列表-分页
 func GetContractInvoiceItemPageList(page base.IPage, condition string, pars []interface{}) (count int64, results []*ContractInvoiceItem, err error) {
-	list := make([]*ContractInvoice, 0)
-	query := global.DEFAULT_MYSQL.Table("contract_invoice").
-		Where("is_deleted = 0").
+	list := make([]*ContractInvoiceRespItem, 0)
+	query := global.DEFAULT_MYSQL.Table("contract_invoice AS a").
+		Select("a.*, b.company_name").
+		Joins("JOIN contract_register b ON a.contract_register_id = b.contract_register_id").
+		Where("a.is_deleted = 0").
 		Where(condition, pars...)
 	query.Count(&count)
 	if len(page.GetOrderItemsString()) > 0 {
@@ -239,7 +255,7 @@ func GetContractInvoiceItemPageList(page base.IPage, condition string, pars []in
 }
 
 // formatContractInvoice2Item 格式化ContractInvoiceItem
-func formatContractInvoice2Item(item *ContractInvoice) (formatItem *ContractInvoiceItem) {
+func formatContractInvoice2Item(item *ContractInvoiceRespItem) (formatItem *ContractInvoiceItem) {
 	formatItem = new(ContractInvoiceItem)
 	formatItem.ContractInvoiceId = item.ContractInvoiceId
 	formatItem.ContractRegisterId = item.ContractRegisterId
@@ -256,6 +272,7 @@ func formatContractInvoice2Item(item *ContractInvoice) (formatItem *ContractInvo
 	formatItem.IsPrePay = item.IsPrePay
 	formatItem.ServiceProductId = item.ServiceProductId
 	formatItem.CreateTime = utils.TimeTransferString(utils.FormatDateTime, item.CreateTime)
+	formatItem.CompanyName = item.CompanyName
 	return
 }
 
@@ -276,9 +293,10 @@ type InvoicePaymentCensusListReq struct {
 	HasInvoice   string `json:"has_invoice" form:"has_invoice" description:"是否已开票: 0-否; 1-是; 空-全部"`
 	HasPayment   string `json:"has_payment" form:"has_payment" description:"是否已到款: 0-否; 1-是; 空-全部"`
 	IsExport     int    `json:"is_export" form:"is_export" description:"是否导出: 0-否; 1-是"`
+	ListParam    int    `json:"list_param" form:"list_param" description:"套餐类型: 0-全部; 1-ficc; 2-权益"`
 	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
 }
 
@@ -487,11 +505,87 @@ type InvoiceListCurrencySum struct {
 
 // GetInvoiceListCurrencySum 获取开票/到款分货币合计
 func GetInvoiceListCurrencySum(condition string, pars []interface{}, groupRule string) (results []*InvoiceListCurrencySum, err error) {
-	query := global.DEFAULT_MYSQL.Table("contract_invoice").
-		Select("currency_unit, invoice_type, SUM(amount) AS amount_total, SUM(origin_amount) AS origin_amount_total").
-		Where("is_deleted = 0").
+	query := global.DEFAULT_MYSQL.Table("contract_invoice AS a").
+		Select("a.currency_unit, a.invoice_type, SUM(a.amount) AS amount_total, SUM(a.origin_amount) AS origin_amount_total, b.company_name").
+		Joins("JOIN contract_register b ON a.contract_register_id = b.contract_register_id").
 		Where(condition, pars...).
 		Group(groupRule)
 	err = query.Find(&results).Error
 	return
 }
+
+// PreRegisterListReq 预登记列表请求体
+type PreRegisterListReq struct {
+	Keyword string `json:"keyword" form:"keyword" binding:"omitempty" description:"关键词"`
+	base.PageReq
+}
+
+// ContractInvoiceDetailItem 预登记列表详情用-invoice_time换register_time
+type ContractInvoiceDetailItem struct {
+	ContractInvoiceId  int     `gorm:"column:contract_invoice_id" json:"contract_invoice_id" description:"开票ID"`
+	ContractRegisterId int     `gorm:"column:contract_register_id" json:"contract_register_id" description:"登记ID"`
+	ContractCode       string  `gorm:"column:contract_code" json:"contract_code" description:"合同编号"`
+	ContractStatus     int     `json:"contract_status" description:"合同状态: 1-已审批; 2-单章寄出; 3-已签回"`
+	OriginAmount       float64 `gorm:"column:amount" json:"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-到款登记;3-开票预登记;4-到款预登记"`
+	InvoiceDate        string  `gorm:"column:register_date" 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:"销售名称"`
+	PayType            int     `gorm:"column:pay_type" json:"pay_type" description:"付款方式:0-无;1-年付;2-半年付;3-季付;4-次付;5-异常"`
+	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:"创建时间"`
+	PreRegisterId      int     `gorm:"column:pre_register_id" json:"pre_register_id" description:"预登记ID"`
+}
+
+// GetContractInvoiceDetailItemList 预登记列表详情用-获取开票到款列表
+func GetContractInvoiceDetailItemList(condition string, pars []interface{}) (itemList []*ContractInvoiceDetailItem, err error) {
+	list := make([]*ContractInvoice, 0)
+	err = global.DEFAULT_MYSQL.Model(ContractInvoice{}).
+		Where("is_deleted = 0").
+		Where(condition, pars...).
+		Order("contract_invoice_id ASC").
+		Find(&list).Error
+	if err != nil {
+		return
+	}
+	itemList = formatContractInvoice2DetailItemList(list)
+	return
+}
+
+// formatContractInvoice2ItemList 预登记列表详情用-格式化ContractInvoice
+func formatContractInvoice2DetailItemList(list []*ContractInvoice) (itemList []*ContractInvoiceDetailItem) {
+	itemList = make([]*ContractInvoiceDetailItem, 0)
+	for i := range list {
+		itemList = append(itemList, &ContractInvoiceDetailItem{
+			ContractInvoiceId:  list[i].ContractInvoiceId,
+			ContractRegisterId: list[i].ContractRegisterId,
+			ContractCode:       list[i].ContractCode,
+			OriginAmount:       list[i].OriginAmount,
+			CurrencyUnit:       list[i].CurrencyUnit,
+			InvoiceType:        list[i].InvoiceType,
+			InvoiceDate:        utils.TimeTransferString(utils.FormatDate, list[i].InvoiceDate),
+			SellerId:           list[i].SellerId,
+			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),
+			PreRegisterId:      list[i].PreRegisterId,
+		})
+	}
+	return
+}
+
+type ContractInvoiceRespItem struct {
+	ContractInvoice
+	CompanyName string `gorm:"column:company_name" json:"company_name" description:"客户名称"`
+}

+ 77 - 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" description:"约定开始日期"`
+	EndDate      string                  `json:"end_date" 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" description:"CRM系统-销售ID"`
+	List         []PreRegisterAddReqItem `json:"list" binding:"required" description:"预登记列表"`
+	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,64 @@ 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 {
+	PreRegisterId      int    `json:"pre_register_id" description:"预登记ID"`
+	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" description:"约定开始日期"`
+	EndDate            string `json:"end_date" 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" description:"CRM系统-销售ID"`
+	DelInvoiceIds      []int  `json:"del_invoice_ids" description:"删除的开票到款记录ids"`
+	DelPreRegisterIds  []int  `json:"del_pre_register_ids" description:"删除的预登记记录ids"`
+	List               []*PreRegisterEditReqItem
+	Services           []ContractServiceAddReq `json:"services" description:"服务套餐内容"`
+}
+
+type PreRegisterEditReqItem struct {
+	PreRegisterId    int     `json:"pre_register_id" description:"预登记ID"`
+	InvoiceId        int     `json:"contract_invoice_id" description:"开票ID"`
+	ArriveId         int     `json:"arrive_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权益套餐"`
+}
+
+// PreRegisterDelReq 预登记删除请求体
+type PreRegisterDelReq struct {
+	ContractRegisterId int `json:"contract_register_id" binding:"required,gte=1" description:"登记ID"`
+	InvoiceId          int `json:"invoice_id" description:"开票ID"`
+	ArriveId           int `json:"arrive_id" description:"到款ID"`
+	PreRegisterId      int `json:"pre_register_id" description:"预登记ID"`
+}
+
+type PreRegisterSaveReqItem struct {
+	PreRegisterId    int     `json:"pre_register_id" description:"预登记ID"`
+	InvoiceId        int     `json:"contract_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"`
+// PreRegisterSaveReq 预登记保存请求体
+type PreRegisterSaveReq struct {
+	PreRegisterId      int                      `json:"pre_register_id" description:"预登记ID"`
+	ContractRegisterId int                      `json:"contract_register_id" binding:"required,gte=1" description:"登记ID"`
+	CompanyName        string                   `json:"company_name" 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" description:"CRM系统-销售ID"`
+	List               []PreRegisterSaveReqItem `json:"list" binding:"required" description:"预登记列表"`
+	Services           []ContractServiceAddReq  `json:"services" description:"服务套餐内容"`
 }

+ 212 - 0
models/fms/contract_pre_register.go

@@ -0,0 +1,212 @@
+package fms
+
+import (
+	"hongze/fms_api/global"
+	"hongze/fms_api/models/base"
+	"hongze/fms_api/utils"
+	"time"
+)
+
+// PreRegister 合同开票表
+type ContractPreRegister struct {
+	PreRegisterId      int       `gorm:"primaryKey;column:pre_register_id" json:"pre_register_id" description:"预登记ID"`
+	ContractRegisterId int       `gorm:"column:contract_register_id" json:"contract_register_id" description:"登记ID"`
+	InvoiceId          int       `gorm:"column:invoice_id" json:"invoice_id" description:"开票ID"`
+	ArriveId           int       `gorm:"column:arrive_id" json:"arrive_id" description:"到款ID"`
+	CompanyName        string    `json:"company_name" description:"客户名称"`
+	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:"开票货币国际代码"`
+	ArriveAmount       float64   `gorm:"column:arrive_amount" json:"arrive_amount" description:"到款换算后的金额(人民币)"`
+	ArriveOriginAmount float64   `gorm:"column:arrive_origin_amount" json:"arrive_origin_amount" description:"到款金额"`
+	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:"开票日"`
+	ArriveDate         time.Time `gorm:"column:arrive_time" json:"arrive_time" description:"到款日"`
+	SellerId           int       `gorm:"column:seller_id" json:"seller_id" description:"销售ID"`
+	SellerName         string    `gorm:"column:seller_name" json:"seller_name" description:"销售名称"`
+	SellerGroupId      int       `gorm:"column:seller_group_id" json:"seller_group_id" description:"销售分组ID"`
+	SellerGroupName    string    `gorm:"column:seller_group_name" json:"seller_group_name" description:"销售分组名称"`
+	SellerTeamId       int       `gorm:"column:seller_team_id" json:"seller_team_id" description:"销售小组ID"`
+	SellerTeamName     string    `gorm:"column:seller_team_name" json:"seller_team_name" description:"销售小组名称"`
+	AdminId            int       `gorm:"column:admin_id" json:"admin_id" description:"操作人ID"`
+	AdminName          string    `gorm:"column:admin_name" json:"admin_name" description:"操作人姓名"`
+	Remark             string    `gorm:"column:remark" json:"remark" description:"备注信息"`
+	ArriveRemark       string    `gorm:"column:arrive_remark" json:"arrive_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          time.Time `gorm:"column:start_date" json:"start_date" description:"约定开始时间"`
+	EndDate            time.Time `gorm:"column:end_date" json:"end_date" description:"约定结束时间"`
+	base.TimeBase
+}
+
+func (c *ContractPreRegister) TableName() string {
+	return "contract_pre_register"
+}
+
+// ContractPreRegisterItem 合同开票/到款
+type ContractPreRegisterItem struct {
+	PreRegisterId      int     `gorm:"primaryKey;column:pre_register_id" json:"pre_register_id" description:"预登记ID"`
+	ContractRegisterId int     `gorm:"column:contract_register_id" json:"contract_register_id" description:"登记ID"`
+	InvoiceId          int     `gorm:"column:invoice_id" json:"invoice_id" description:"开票ID"`
+	ArriveId           int     `gorm:"column:arrive_id" json:"arrive_id" description:"到款ID"`
+	CompanyName        string  `json:"company_name" description:"客户名称"`
+	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:"开票货币国际代码"`
+	ArriveAmount       float64 `gorm:"column:arrive_amount" json:"arrive_amount" description:"到款换算后的金额(人民币)"`
+	ArriveOriginAmount float64 `gorm:"column:arrive_origin_amount" json:"arrive_origin_amount" description:"到款金额"`
+	UnitName           string  `json:"unit_name" description:"货币单位名称"`
+	InvoiceType        int     `gorm:"column:invoice_type" json:"invoice_type" description:"类型: 1-开票登记; 2-到款登记;3-开票预登记;4-到款预登记"`
+	InvoiceDate        string  `gorm:"column:invoice_time" json:"invoice_time" description:"开票日"`
+	ArriveDate         string  `gorm:"column:arrive_time" json:"arrive_time" description:"到款日"`
+	SellerId           int     `gorm:"column:seller_id" json:"seller_id" description:"销售ID"`
+	SellerName         string  `gorm:"column:seller_name" json:"seller_name" description:"销售名称"`
+	PayType            int     `gorm:"column:pay_type" json:"pay_type" description:"付款方式:0-无;1-年付;2-半年付;3-季付;4-次付;5-异常"`
+	Remark             string  `gorm:"column:remark" json:"remark" description:"开票备注信息"`
+	ArriveRemark       string  `gorm:"column:arrive_remark" json:"arrive_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:"约定结束时间"`
+	AdminId            int     `gorm:"column:admin_id" json:"admin_id" description:"操作人ID"`
+	CreateTime         string  `gorm:"column:create_time" json:"create_time" description:"创建时间"`
+}
+
+// formatContractInvoice2Item 格式化ContractInvoiceItem
+func formatContractPreRegister2Item(item *ContractPreRegister) (formatItem *ContractPreRegisterItem) {
+	formatItem = new(ContractPreRegisterItem)
+	formatItem.PreRegisterId = item.PreRegisterId
+	formatItem.ContractRegisterId = item.ContractRegisterId
+	formatItem.InvoiceId = item.InvoiceId
+	formatItem.ArriveId = item.ArriveId
+	formatItem.CompanyName = item.CompanyName
+	formatItem.Amount = item.Amount
+	formatItem.OriginAmount = item.OriginAmount
+	formatItem.CurrencyUnit = item.CurrencyUnit
+	formatItem.ArriveAmount = item.ArriveAmount
+	formatItem.ArriveOriginAmount = item.ArriveOriginAmount
+	formatItem.InvoiceType = item.InvoiceType
+	formatItem.InvoiceDate = utils.TimeTransferString(utils.FormatDate, item.InvoiceDate)
+	formatItem.ArriveDate = utils.TimeTransferString(utils.FormatDate, item.ArriveDate)
+	formatItem.SellerId = item.SellerId
+	formatItem.SellerName = item.SellerName
+	formatItem.Remark = item.Remark
+	formatItem.ArriveRemark = item.ArriveRemark
+	formatItem.IsPrePay = item.IsPrePay
+	formatItem.ServiceProductId = item.ServiceProductId
+	formatItem.AdminId = item.AdminId
+	formatItem.CreateTime = utils.TimeTransferString(utils.FormatDateTime, item.CreateTime)
+	formatItem.StartDate = item.StartDate.Format(utils.FormatDate)
+	formatItem.EndDate = item.EndDate.Format(utils.FormatDate)
+	return
+}
+
+// GetContractInvoiceItemPageList 获取合同开票/到款列表-分页
+func GetContractPreRegisterItemPageList(page base.IPage, condition string, pars []interface{}) (count int64, results []*ContractPreRegisterItem, err error) {
+	list := make([]*ContractPreRegister, 0)
+	query := global.DEFAULT_MYSQL.Table("contract_pre_register").
+		Where(condition, pars...)
+	query.Count(&count)
+	if len(page.GetOrderItemsString()) > 0 {
+		query = query.Order(page.GetOrderItemsString())
+	}
+	err = query.Limit(int(page.GetPageSize())).Offset(int(page.Offset())).Find(&list).Error
+	if err != nil {
+		return
+	}
+	for i := range list {
+		results = append(results, formatContractPreRegister2Item(list[i]))
+	}
+	return
+}
+
+func (c *ContractPreRegister) Create() (err error) {
+	err = global.DEFAULT_MYSQL.Create(c).Error
+	return
+}
+
+func (c *ContractPreRegister) Fetch(id int) (item *ContractPreRegister, err error) {
+	err = global.DEFAULT_MYSQL.Model(c).Where(" pre_register_id = ?", id).First(&item).Error
+	return
+}
+
+func (c *ContractPreRegister) FetchByRegisterId(id int) (items []*ContractPreRegister, err error) {
+	err = global.DEFAULT_MYSQL.Model(c).Where(" contract_register_id = ?", id).Find(&items).Error
+	return
+}
+
+// 删除
+func (c *ContractPreRegister) Delete() (err error) {
+	err = global.DEFAULT_MYSQL.Delete(c).Error
+	return
+}
+
+func (c *ContractPreRegister) Update(updateCols []string) (err error) {
+	err = global.DEFAULT_MYSQL.Model(c).Select(updateCols).Updates(c).Error
+	return
+}
+
+// GetContractInvoiceItemList 获取开票到款列表
+func GetContractPreRegisterItemList(condition string, pars []interface{}) (itemList []*ContractPreRegisterItem, err error) {
+	list := make([]*ContractPreRegister, 0)
+	err = global.DEFAULT_MYSQL.Model(ContractPreRegister{}).
+		Where("is_deleted = 0").
+		Where(condition, pars...).
+		Order("contract_invoice_id ASC").
+		Find(&list).Error
+	if err != nil {
+		return
+	}
+	itemList = formatContractPreRegister2ItemList(list)
+	return
+}
+
+// formatContractPreRegister2ItemList 格式化ContractInvoice
+func formatContractPreRegister2ItemList(list []*ContractPreRegister) (itemList []*ContractPreRegisterItem) {
+	itemList = make([]*ContractPreRegisterItem, 0)
+	for i := range list {
+		itemList = append(itemList, &ContractPreRegisterItem{
+			PreRegisterId:      list[i].PreRegisterId,
+			ContractRegisterId: list[i].ContractRegisterId,
+			Amount:             list[i].Amount,
+			OriginAmount:       list[i].OriginAmount,
+			CurrencyUnit:       list[i].CurrencyUnit,
+			ArriveAmount:       list[i].ArriveAmount,
+			ArriveOriginAmount: list[i].ArriveOriginAmount,
+			InvoiceType:        list[i].InvoiceType,
+			InvoiceDate:        utils.TimeTransferString(utils.FormatDate, list[i].InvoiceDate),
+			SellerId:           list[i].SellerId,
+			SellerName:         list[i].SellerName,
+			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),
+		})
+	}
+	return
+}
+
+// ContractPreRegisterList 预登记列表
+type ContractPreRegisterList struct {
+	*ContractPreRegisterItem
+	ServicesName string `json:"services" description:"套餐名称"`
+}
+
+// PreRegisterDetailReq 预登记详情请求体
+type PreRegisterDetailReq struct {
+	ContractRegisterId int `json:"contract_register_id" form:"contract_register_id" binding:"required,gte=1"`
+	InvoiceType        int `gorm:"column:invoice_type" json:"invoice_type" description:"类型: 1-开票登记; 2-到款登记;3-开票预登记;4-到款预登记"`
+	PreRegisterId      int `gorm:"column:pre_register_id" json:"pre_register_id" description:"预登记ID"`
+	InvoiceId          int `gorm:"column:invoice_id" json:"invoice_id" description:"开票ID"`
+	ArriveId           int `gorm:"column:arrive_id" json:"arrive_id" description:"到款ID"`
+}
+
+// ContractPreRegisterDetail 预登记详情
+type ContractPreRegisterDetail struct {
+	*ContractRegisterItem
+	List               []*ContractInvoiceDetailItem `json:"list" description:"开票到款列表"`
+	Services           []*ContractServiceAndDetail  `json:"services" description:"套餐列表"`
+	ServiceTemplateIds []int                        `json:"serviceTemplateIds" description:"小套餐列表"`
+}

+ 342 - 71
models/fms/contract_register.go

@@ -9,35 +9,38 @@ import (
 
 // ContractRegister 合同登记表
 type ContractRegister struct {
-	ContractRegisterId int       `gorm:"primaryKey;column:contract_register_id" json:"contract_register_id" description:"登记ID"`
-	ContractCode       string    `gorm:"column:contract_code" json:"contract_code" description:"合同编号"`
-	RelateContractCode string    `gorm:"column:relate_contract_code" json:"relate_contract_code" description:"关联合同编号"`
-	CrmContractId      int       `gorm:"column:crm_contract_id" json:"crm_contract_id" description:"CRM系统-合同ID"`
-	ContractSource     int       `gorm:"column:contract_source" json:"contract_source" description:"合同来源: 0-非系统合同导入; 1-CRM合同导入"`
-	CompanyName        string    `gorm:"column:company_name" json:"company_name" description:"客户名称"`
-	ActualCompanyName  string    `gorm:"column:actual_company_name" json:"actual_company_name" description:"实际使用方"`
-	ProductIds         string    `gorm:"column:product_ids" json:"product_ids" description:"产品ID:1-FICC; 2-权益, 如果两者都有,则用英文逗号拼接"`
-	SellerId           int       `gorm:"column:seller_id" json:"seller_id" description:"CRM系统-销售ID"`
-	SellerName         string    `gorm:"column:seller_name" json:"seller_name" description:"CRM系统-销售名称"`
-	RaiSellerId        int       `gorm:"column:rai_seller_id" json:"rai_seller_id"  description:"CRM系统-权益销售ID"`
-	RaiSellerName      string    `gorm:"column:rai_seller_name" json:"rai_seller_name" description:"CRM系统-权益销售名称"`
-	ContractType       int       `gorm:"column:contract_type" json:"contract_type" description:"合同类型: 1-新签; 2-续约; 3-代付; 4-补充协议"`
-	ContractAmount     float64   `gorm:"column:contract_amount" json:"contract_amount" description:"合同金额"`
-	InvoicedAmount     float64   `gorm:"column:invoiced_amount" json:"invoiced_amount" description:"开票金额"`
-	PaymentAmount      float64   `gorm:"column:payment_amount" json:"payment_amount" description:"到款金额"`
-	CurrencyUnit       string    `gorm:"column:currency_unit" json:"currency_unit" description:"货币国际代码"`
-	RMBRate            float64   `gorm:"column:rmb_rate" json:"rmb_rate" description:"人民币汇率(create_time当日)"`
-	StartDate          time.Time `gorm:"column:start_date" json:"start_date" description:"合同开始日期"`
-	EndDate            time.Time `gorm:"column:end_date" json:"end_date" description:"合同结束日期"`
-	SignDate           time.Time `gorm:"column:sign_date" json:"sign_date" description:"合同签订日期"`
-	AgreedPayTime      string    `gorm:"column:agreed_pay_time" json:"agreed_pay_time" description:"约定付款时间(如:生效日起10日内)"`
-	ContractStatus     int       `gorm:"column:contract_status" json:"contract_status" description:"合同状态: 1-已审批; 2-单章寄出; 3-已签回"`
-	RegisterStatus     int       `gorm:"column:register_status" json:"register_status" description:"登记状态: 1-进行中; 2-已完成;"`
-	Remark             string    `gorm:"column:remark" json:"remark" description:"备注信息"`
-	ServiceRemark      string    `gorm:"column:service_remark" json:"service_remark" description:"套餐备注信息"`
-	HasPayment         int       `gorm:"column:has_payment" json:"has_payment" description:"是否有代付: 0-无; 1-有"`
-	NewCompany         int       `gorm:"column:new_company" json:"new_company" description:"是否为新客户: 0-否; 1-是"`
-	IsDeleted          int       `gorm:"column:is_deleted" json:"is_deleted" description:"是否已删除: 0-正常; 1-已删除"`
+	ContractRegisterId     int       `gorm:"primaryKey;column:contract_register_id" json:"contract_register_id" description:"登记ID"`
+	ContractCode           string    `gorm:"column:contract_code" json:"contract_code" description:"合同编号"`
+	RelateContractCode     string    `gorm:"column:relate_contract_code" json:"relate_contract_code" description:"关联合同编号"`
+	RelateContractMainCode string    `gorm:"column:relate_contract_main_code" json:"relate_contract_main_code" description:"关联主合同编号"`
+	CrmContractId          int       `gorm:"column:crm_contract_id" json:"crm_contract_id" description:"CRM系统-合同ID"`
+	ContractSource         int       `gorm:"column:contract_source" json:"contract_source" description:"合同来源: 0-非系统合同导入; 1-CRM合同导入"`
+	CompanyName            string    `gorm:"column:company_name" json:"company_name" description:"客户名称"`
+	ActualCompanyName      string    `gorm:"column:actual_company_name" json:"actual_company_name" description:"实际使用方"`
+	ProductIds             string    `gorm:"column:product_ids" json:"product_ids" description:"产品ID:1-FICC; 2-权益, 如果两者都有,则用英文逗号拼接"`
+	SellerId               int       `gorm:"column:seller_id" json:"seller_id" description:"CRM系统-销售ID"`
+	SellerName             string    `gorm:"column:seller_name" json:"seller_name" description:"CRM系统-销售名称"`
+	RaiSellerId            int       `gorm:"column:rai_seller_id" json:"rai_seller_id"  description:"CRM系统-权益销售ID"`
+	RaiSellerName          string    `gorm:"column:rai_seller_name" json:"rai_seller_name" description:"CRM系统-权益销售名称"`
+	ContractType           int       `gorm:"column:contract_type" json:"contract_type" description:"合同类型: 1-新签; 2-续约; 3-代付; 4-补充协议"`
+	ContractAmount         float64   `gorm:"column:contract_amount" json:"contract_amount" description:"合同金额"`
+	InvoicedAmount         float64   `gorm:"column:invoiced_amount" json:"invoiced_amount" description:"开票金额"`
+	PaymentAmount          float64   `gorm:"column:payment_amount" json:"payment_amount" description:"到款金额"`
+	CurrencyUnit           string    `gorm:"column:currency_unit" json:"currency_unit" description:"货币国际代码"`
+	RMBRate                float64   `gorm:"column:rmb_rate" json:"rmb_rate" description:"人民币汇率(create_time当日)"`
+	StartDate              time.Time `gorm:"column:start_date" json:"start_date" description:"合同开始日期"`
+	EndDate                time.Time `gorm:"column:end_date" json:"end_date" description:"合同结束日期"`
+	SignDate               time.Time `gorm:"column:sign_date" json:"sign_date" description:"合同签订日期"`
+	AgreedPayTime          string    `gorm:"column:agreed_pay_time" json:"agreed_pay_time" description:"约定付款时间(如:生效日起10日内)"`
+	ContractStatus         int       `gorm:"column:contract_status" json:"contract_status" description:"合同状态: 1-已审批; 2-单章寄出; 3-已签回"`
+	RegisterStatus         int       `gorm:"column:register_status" json:"register_status" description:"登记状态: 1-进行中; 2-已完成;"`
+	Remark                 string    `gorm:"column:remark" json:"remark" description:"备注信息"`
+	ServiceRemark          string    `gorm:"column:service_remark" json:"service_remark" description:"套餐备注信息"`
+	HasPayment             int       `gorm:"column:has_payment" json:"has_payment" description:"是否有代付: 0-无; 1-有"`
+	HasInvoice             int       `gorm:"column:has_invoice" json:"has_invoice" description:"是否需要开票到款: 0-无; 1-有"`
+	NewCompany             int       `gorm:"column:new_company" json:"new_company" description:"是否为新客户: 0-否; 1-是"`
+	IsDeleted              int       `gorm:"column:is_deleted" json:"is_deleted" description:"是否已删除: 0-正常; 1-已删除"`
+	ActualPayCompanies     string    `gorm:"column:actual_pay_companies" json:"actual_pay_companies" description:"合同关联的所有代付方名称, 英文逗号拼接"`
 	base.TimeBase
 }
 
@@ -77,6 +80,7 @@ func (c *ContractRegister) List(condition string, pars []interface{}) (list []*C
 	list = make([]*ContractRegister, 0)
 	err = global.DEFAULT_MYSQL.Model(c).
 		Where("is_deleted = 0").
+		Where("register_status <> 0").
 		Where(condition, pars...).
 		Find(&list).Error
 	return
@@ -101,8 +105,9 @@ type ContractRegisterListReq struct {
 	StartDate      string `json:"start_date" form:"start_date" binding:"omitempty,datetime=2006-01-02" description:"合同开始日期"`
 	EndDate        string `json:"end_date" form:"end_date" binding:"omitempty,datetime=2006-01-02" description:"合同结束日期"`
 	ServiceTypes   string `json:"service_types" form:"service_types" description:"套餐类型"`
-	ContractType   int    `json:"contract_type" form:"contract_type" description:"合同类型"`
+	ContractType   string `json:"contract_type" form:"contract_type" description:"合同类型"`
 	RegisterStatus int    `json:"register_status" form:"register_status" description:"登记状态"`
+	ListParam      int    `json:"list_param" form:"list_param" description:"套餐类型: 0-全部; 1-ficc; 2-权益"`
 	base.PageReq
 }
 
@@ -135,7 +140,9 @@ type ContractRegisterItem struct {
 	Remark             string  `json:"remark" description:"备注信息"`
 	ServiceRemark      string  `json:"service_remark" description:"套餐备注信息"`
 	HasPayment         int     `json:"has_payment" description:"是否有代付: 0-无; 1-有"`
+	HasInvoice         int     `json:"has_invoice" description:"是否需要开票到款: 0-无; 1-有"`
 	NewCompany         int     `json:"new_company" description:"是否为新客户: 0-否; 1-是"`
+	ActualPayCompanies string  `json:"actual_pay_companies" description:"合同关联的所有代付方名称, 英文逗号拼接"`
 	CreateTime         string  `json:"create_time" description:"登记时间"`
 	SellerIds          string  `json:"seller_ids"`
 }
@@ -143,9 +150,10 @@ type ContractRegisterItem struct {
 // ContractRegisterList 合同登记列表
 type ContractRegisterList struct {
 	*ContractRegisterItem
-	ServicesName string                 `json:"services" description:"套餐名称"`
-	InvoiceList  []*ContractInvoiceItem `json:"invoice_list" description:"开票信息"`
-	PaymentList  []*ContractInvoiceItem `json:"payment_list" description:"到款信息"`
+	ContractTypeString string                 `json:"contract_type_string" description:"合同类型"`
+	ServicesName       string                 `json:"services" description:"套餐名称"`
+	InvoiceList        []*ContractInvoiceItem `json:"invoice_list" description:"开票信息"`
+	PaymentList        []*ContractInvoiceItem `json:"payment_list" description:"到款信息"`
 }
 
 // ContractRegisterDelReq 合同登记-删除请求体
@@ -161,30 +169,31 @@ type ContractRegisterUpdateStatusReq struct {
 
 // ContractRegisterAddReq 新增合同登记请求体
 type ContractRegisterAddReq struct {
-	ContractCode       string                        `json:"contract_code" binding:"required" description:"合同编号"`
-	RelateContractCode string                        `json:"relate_contract_code" description:"关联合同编号"`
-	CrmContractId      int                           `json:"crm_contract_id" description:"CRM系统-合同ID"`
-	ContractSource     int                           `json:"contract_source" binding:"oneof=0 1" description:"合同来源: 0-非系统合同导入; 1-CRM合同导入"`
-	CompanyName        string                        `json:"company_name" binding:"required" description:"客户名称"`
-	ActualCompanyName  string                        `json:"actual_company_name" description:"实际使用方"`
-	SellerIds          string                        `json:"seller_ids" binding:"required" description:"CRM系统-销售ID"`
-	ContractType       int                           `json:"contract_type" binding:"oneof=1 2 3 4" description:"合同类型: 1-新签; 2-续约; 3-代付; 4-补充协议"`
-	ContractAmount     float64                       `json:"contract_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:"合同结束日期"`
-	SignDate           string                        `json:"sign_date" description:"合同签订日期"`
-	AgreedPayTime      string                        `json:"agreed_pay_time" description:"约定付款时间(如:生效日起10日内)"`
-	ContractStatus     int                           `json:"contract_status" binding:"oneof=1 2 3 4 5" description:"合同状态: 1-已审批; 2-单章寄出; 3-已签回; 4-已终止; 5-邮件备案"`
-	Remark             string                        `json:"remark" description:"备注信息"`
-	ProductIds         string                        `json:"product_ids" description:"产品ID:1-FICC; 2-权益, 如果两者都有,则用英文逗号拼接"`
-	ServiceRemark      string                        `json:"service_remark" description:"套餐备注"`
-	HasPayment         int                           `json:"has_payment" description:"是否有代付: 0-无; 1-有"`
-	NewCompany         int                           `json:"new_company" description:"是否为新客户: 0-否; 1-是"`
-	Supplement         int                           `json:"supplement" description:"是否为补录合同: 0-否; 1-是"`
-	PrePayId           int                           `json:"pre_pay_id" description:"预到款信息ID"`
-	Services           []ContractServiceAddReq       `json:"services" description:"服务套餐内容"`
-	ServiceAmount      []ContractServiceAmountAddReq `json:"service_amount" description:"服务套餐金额"`
+	ContractCode           string                        `json:"contract_code" binding:"required" description:"合同编号"`
+	RelateContractCode     string                        `json:"relate_contract_code" description:"关联合同编号"`
+	RelateContractMainCode string                        `json:"relate_contract_main_code" description:"关联主合同编号"`
+	CrmContractId          int                           `json:"crm_contract_id" description:"CRM系统-合同ID"`
+	ContractSource         int                           `json:"contract_source" binding:"oneof=0 1" description:"合同来源: 0-非系统合同导入; 1-CRM合同导入"`
+	CompanyName            string                        `json:"company_name" binding:"required" description:"客户名称"`
+	SellerIds              string                        `json:"seller_ids" binding:"required" description:"CRM系统-销售ID"`
+	ContractType           int                           `json:"contract_type" binding:"oneof=1 2 3 4" description:"合同类型: 1-新签; 2-续约; 3-代付; 4-补充协议"`
+	ContractAmount         float64                       `json:"contract_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:"合同结束日期"`
+	SignDate               string                        `json:"sign_date" description:"合同签订日期"`
+	AgreedPayTime          string                        `json:"agreed_pay_time" description:"约定付款时间(如:生效日起10日内)"`
+	ContractStatus         int                           `json:"contract_status" binding:"oneof=1 2 3 4 5" description:"合同状态: 1-已审批; 2-单章寄出; 3-已签回; 4-已终止; 5-邮件备案"`
+	Remark                 string                        `json:"remark" description:"备注信息"`
+	ProductIds             string                        `json:"product_ids" description:"产品ID:1-FICC; 2-权益, 如果两者都有,则用英文逗号拼接"`
+	ServiceRemark          string                        `json:"service_remark" description:"套餐备注"`
+	HasPayment             int                           `json:"has_payment" description:"是否有代付: 0-无; 1-有"`
+	HasInvoice             int                           `json:"has_invoice" description:"是否需要开票到款流程: 0-无; 1-有"`
+	Supplement             int                           `json:"supplement" description:"是否为补录合同: 0-否; 1-是"`
+	ContractRegisterId     int                           `json:"contract_register_id" description:"登记ID"`
+	Services               []ContractServiceAddReq       `json:"services" description:"服务套餐内容"`
+	ServiceAmount          []ContractServiceAmountAddReq `json:"service_amount" description:"服务套餐金额"`
+	ActualPayCompanies     string                        `json:"actual_pay_companies" description:"合同关联的所有代付方名称, 英文逗号拼接"`
 }
 
 // ContractRegisterEditReq 编辑合同登记请求体
@@ -277,7 +286,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++ {
@@ -345,14 +353,14 @@ type ContractRegisterDetailReq struct {
 	ContractRegisterId int `json:"contract_register_id" form:"contract_register_id" binding:"required,gte=1"`
 }
 
-// ContractRegisterDetail-合同登记详情
+// 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 获取合同登记信息
@@ -373,6 +381,7 @@ func GetContractRegisterItemPageList(page base.IPage, condition string, pars []i
 	list := make([]*ContractRegister, 0)
 	query := global.DEFAULT_MYSQL.Table("contract_register").
 		Where("is_deleted = 0").
+		Where("register_status <> 0").
 		Where(condition, pars...)
 	query.Count(&count)
 	if len(page.GetOrderItemsString()) > 0 {
@@ -418,7 +427,9 @@ func formatContractRegister2Item(item *ContractRegister) (formatItem *ContractRe
 	formatItem.Remark = item.Remark
 	formatItem.ServiceRemark = item.ServiceRemark
 	formatItem.HasPayment = item.HasPayment
+	formatItem.HasInvoice = item.HasInvoice
 	formatItem.NewCompany = item.NewCompany
+	formatItem.ActualPayCompanies = item.ActualPayCompanies
 	formatItem.CreateTime = utils.TimeTransferString(utils.FormatDateTime, item.CreateTime)
 	return
 }
@@ -484,8 +495,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 +503,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 +549,274 @@ 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:"合同结束日期"`
+	SellerIds   string `json:"seller_ids" form:"seller_ids" binding:"required" description:"CRM系统-销售ID"`
+}
+
+type CheckContractNameResp struct {
+	Exist int `json:"exist" description:"是否存在相似的合同:0不存在,1存在"`
+}
+
+// UpdateContractPreRegister 更新合同预登记
+func UpdateContractPreRegister(item *ContractRegister, updateCols []string, serviceDetail []*ContractServiceAndDetail,
+	invoiceList []*ContractInvoice, invoiceUpdateCols []string, delInvoiceIds, delPreRegisterIds []int) (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 invoiceList[i].ContractInvoiceId == 0 {
+			if e := invoiceList[i].Create(); e != nil {
+				err = e
+				return
+			}
+		} else {
+			if e := tx.Model(invoiceList[i]).Select(invoiceUpdateCols).Updates(invoiceList[i]).Error; e != nil {
+				err = e
+				return
+			}
+		}
+	}
+
+	//更新另一类型的invoice表数据
+	invoiceItem := ContractInvoice{
+		ContractRegisterId: item.ContractRegisterId,
+		StartDate:          item.StartDate,
+		EndDate:            item.EndDate,
+		CurrencyUnit:       item.CurrencyUnit,
+	}
+	tx.Model(&invoiceItem).Select([]string{"StartDate", "EndDate", "CurrencyUnit"}).Where("ContractRegisterId", item.ContractRegisterId).Updates(invoiceItem)
+
+	//删除
+	if len(delInvoiceIds) > 0 {
+		for _, id := range delInvoiceIds {
+			ob := ContractInvoice{ContractInvoiceId: id}
+			tx.Model(&ob).Delete(ob)
+		}
+	}
+	if len(delPreRegisterIds) > 0 {
+		for _, id := range delPreRegisterIds {
+			ob := ContractPreRegister{PreRegisterId: id}
+			tx.Model(&ob).Delete(ob)
+		}
+	}
+
+	return
 }
 
+// UpdateContractRegister 预登记保存和更新
+func UpdateContractRegisterPre(item *ContractRegister, updateCols []string, serviceDetail []*ContractServiceAndDetail,
+	invoiceList []*ContractInvoice, invoiceUpdateCols []string, invoiceHandleType int, ppList []*ContractPreRegister) (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)
+	sql = `DELETE FROM contract_service_detail WHERE contract_register_id = ?`
+	tx.Exec(sql, item.ContractRegisterId)
+	sql = `DELETE FROM contract_service_amount WHERE contract_register_id = ?`
+	tx.Exec(sql, item.ContractRegisterId)
 
-type  CheckContractNameResp struct {
-	Exist int 	`json:"exist" description:"是否存在相似的合同:0不存在,1存在"`
-}
+	// 新增合同服务
+	//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
+		//}
+	}
+
+	//更新另一类型的invoice表数据
+	invoiceItem := ContractInvoice{
+		ContractRegisterId: item.ContractRegisterId,
+		StartDate:          item.StartDate,
+		EndDate:            item.EndDate,
+		CurrencyUnit:       item.CurrencyUnit,
+	}
+	tx.Model(&invoiceItem).Select([]string{"StartDate", "EndDate", "CurrencyUnit"}).Where("ContractRegisterId", item.ContractRegisterId).Updates(invoiceItem)
+
+	// 开票到款操作类型: 0-无; 1-更新; 2-新增;
+	if invoiceHandleType == 2 {
+		for _, v := range invoiceList {
+			if e := v.Create(); e != nil {
+				err = e
+				return
+			}
+			if len(ppList) > 0 {
+				pp := &ContractPreRegister{
+					PreRegisterId: ppList[0].PreRegisterId,
+				}
+				ppUpdateCols := make([]string, 0)
+				if v.InvoiceType == 3 {
+					pp.InvoiceId = v.ContractInvoiceId
+					ppUpdateCols = append(ppUpdateCols, "InvoiceId")
+				} else {
+					pp.ArriveId = v.ContractInvoiceId
+					ppUpdateCols = append(ppUpdateCols, "ArriveId")
+				}
+				if e := pp.Update(ppUpdateCols); e != nil {
+					err = e
+					return
+				}
+			}
+		}
+	}
+	if invoiceHandleType == 1 {
+		for i := range invoiceList {
+			if e := tx.Model(invoiceList[i]).Select(invoiceUpdateCols).Updates(invoiceList[i]).Error; e != nil {
+				err = e
+				return
+			}
+		}
+	}
+	return
+}
+
+// UpdateSupplementContractPreRegister 更新补录合同预登记
+func UpdateSupplementContractPreRegister(item *ContractRegister, serviceAmountList []*ContractServiceAmount, serviceDetail []*ContractServiceAndDetail) (err error) {
+	tx := global.DEFAULT_MYSQL.Begin()
+	defer func() {
+		if err != nil {
+			tx.Rollback()
+		} else {
+			tx.Commit()
+		}
+	}()
+
+	for i := 0; i < len(serviceAmountList); i++ {
+		// 合同服务
+		t := serviceAmountList[i]
+		tmp := &ContractServiceAmount{
+			ContractRegisterId: item.ContractRegisterId,
+			ProductId:          t.ProductId,
+			ServiceAmount:      t.ServiceAmount,
+			CurrencyUnit:       t.CurrencyUnit,
+		}
+
+		if e := tmp.Create(); 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
+		//}
+	}
+
+	return
+}

+ 2 - 3
models/fms/contract_service_template.go

@@ -48,7 +48,7 @@ type ContractServiceTemplateItem struct {
 }
 
 type ContractServiceTemplateList struct {
-	Title string `json:"title"`
+	Title    string                             `json:"title"`
 	Children []*ContractServiceTemplateMapItems `json:"children"`
 }
 
@@ -124,7 +124,6 @@ type ContractServiceTemplateFullName struct {
 	ParentTitle string
 }
 
-
 type ContractServiceTemplateFormat struct {
 	FormatTitle        string
 	ServiceTemplateId  int
@@ -161,4 +160,4 @@ func GetContractServiceTemplateByTitle(titles string) (items []*ContractServiceT
 		Where("title IN (?)", titles).
 		Scan(&items).Error
 	return
-}
+}

+ 9 - 7
routers/contract.go

@@ -36,11 +36,13 @@ 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)
+	preRegisterGroup.POST("detail", preRegister.Detail)
+	preRegisterGroup.POST("save", preRegister.Save)
 }

+ 1 - 0
routers/crm.go

@@ -19,4 +19,5 @@ func InitCrm(rg *gin.RouterGroup) {
 	slGroup := rg.Group("company_seller/").Use(middleware.Token())
 	slGroup.GET("list", sl.List)
 	slGroup.GET("group_list", sl.GroupList)
+	slGroup.GET("all_list", sl.AllList)
 }

+ 64 - 1
services/crm/company_seller.go

@@ -200,4 +200,67 @@ func GetSellerDepartmentList() (resp crm.SellerAdminWithGroupList, err error) {
 	resp.FiccList = ficcList
 	resp.RaiList = raiList
 	return
-}
+}
+
+// GetSellerDepartmentAndGroupMap 获取销售部门列表-包含大组和小组
+func GetSellerDepartmentListWithGroupAndTeamByDepartment() (ficcList []*crm.SellerAdminWithGroupTeam,raiList []*crm.SellerAdminWithGroupTeam, err error) {
+	departmentIds := []int{crm.SellerDepartmentId,crm.RaiSellerDepartmentId}
+	ficcList = make([]*crm.SellerAdminWithGroupTeam, 0)
+	raiList = make([]*crm.SellerAdminWithGroupTeam, 0)
+	// 获取组别列表
+	groupCond := "department_id in (?)"
+	groupPars := make([]interface{}, 0)
+	groupPars = append(groupPars, departmentIds)
+	groupOB := new(crm.SysGroup)
+	groupList, e := groupOB.List(groupCond, groupPars)
+	if e != nil {
+		err = errors.New("获取组别列表失败, Err: " + e.Error())
+		return
+	}
+	groupMap := make(map[int]*crm.SysGroup)
+	for i := range groupList {
+		groupMap[groupList[i].GroupId] = groupList[i]
+	}
+
+	// 获取销售部门所有销售信息
+	adminCond := "department_id in (?) AND enabled = 1"
+	adminPars := make([]interface{}, 0)
+	adminPars = append(adminPars, departmentIds)
+	adminOB := new(crm.Admin)
+	adminList, e := adminOB.List(adminCond, adminPars)
+	if e != nil {
+		err = errors.New("获取销售列表失败, Err: " + e.Error())
+		return
+	}
+
+	// 销售列表
+	for i := range adminList {
+		v := new(crm.SellerAdminWithGroupTeam)
+		v.DepartmentId = adminList[i].DepartmentId
+		v.SellerId = adminList[i].AdminId
+		v.SellerName = adminList[i].RealName
+		g := groupMap[adminList[i].GroupId]
+		if g != nil {
+			if g.ParentId > 0 {
+				// 三级分组
+				p := groupMap[g.ParentId]
+				if p != nil {
+					v.GroupId = p.GroupId
+					v.GroupName = p.GroupName
+					v.TeamId = g.GroupId
+					v.TeamName = g.GroupName
+				}
+			} else {
+				// 二级分组
+				v.GroupId = g.GroupId
+				v.GroupName = g.GroupName
+			}
+		}
+		if v.DepartmentId == crm.SellerDepartmentId {
+			ficcList = append(ficcList, v)
+		} else {
+			raiList = append(raiList, v)
+		}
+	}
+	return
+}

+ 159 - 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,122 @@ func CalculatePaymentServiceAmount(registerId int) (err error)  {
 	return
 }
 
+// SummaryInvoicePaymentByPreRegister 预登记时汇总
+func SummaryInvoicePaymentByPreRegister(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.GetContractPreRegisterItemList(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].PreRegisterId)
+			} else if list[i].ServiceProductId == crm.CompanyProductRai {
+				raiInvoiceIds = append(raiInvoiceIds, list[i].PreRegisterId)
+			}
+			continue
+		}
+		if list[i].InvoiceType == fms.ContractInvoiceTypePrePay {
+			if list[i].ServiceProductId == crm.CompanyProductFicc {
+				ficcPaymentIds = append(ficcPaymentIds, list[i].PreRegisterId)
+			} else if list[i].ServiceProductId == crm.CompanyProductRai {
+				raiPaymentIds = append(raiPaymentIds, list[i].PreRegisterId)
+			}
+			continue
+		}
+	}
+	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
+}

部分文件因为文件数量过多而无法显示