Browse Source

Merge branch 'fms_2.7'

ziwen 1 year ago
parent
commit
3d5ff6cc03

+ 14 - 3
controller/census/invoice_payment.go

@@ -535,8 +535,8 @@ func (ct *InvoicePaymentController) List(c *gin.Context) {
 	}
 	if req.SellerIds != "" {
 		sellerIds := strings.Split(req.SellerIds, ",")
-		cond += ` AND (c.seller_id in ?)`
-		pars = append(pars, sellerIds)
+		cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
+		pars = append(pars, sellerIds, sellerIds)
 	}
 	// 套餐筛选
 	if req.ServiceTypes != "" {
@@ -816,7 +816,7 @@ func (ct *InvoicePaymentController) List(c *gin.Context) {
 		}()
 
 		// 开票到款金额合计(换算后)
-		var invoiceTotal, paymentTotal float64
+		var invoiceTotal, paymentTotal,amountTotal float64
 		wg.Add(1)
 		go func() {
 			defer wg.Done()
@@ -839,6 +839,16 @@ func (ct *InvoicePaymentController) List(c *gin.Context) {
 				return
 			}
 			paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
+
+			amountCond := `a.id IN ? AND (a.invoice_id <> 0 OR (a.payment_id <> 0 AND a.invoice_id =0))`
+			amountPars := make([]interface{}, 0)
+			amountPars = append(amountTotalPars, summaryIds)
+			amountSum, e := fms.GetContractSummaryInvoicePaymentAmount(amountCond, amountPars)
+			if e != nil {
+				totalErr = fmt.Errorf("获取汇总金额合计失败, Err: %s", e.Error())
+				return
+			}
+			amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
 		}()
 
 		// 分币种金额统计
@@ -927,6 +937,7 @@ func (ct *InvoicePaymentController) List(c *gin.Context) {
 		results.DataList = respList
 		results.InvoiceTotal = invoiceTotal
 		results.PaymentTotal = paymentTotal
+		results.AmountTotal = amountTotal
 		results.InvoiceCurrencyTotal = invoiceCurrencyTotals
 		results.PaymentCurrencyTotal = paymentCurrencyTotals
 	}

+ 121 - 50
controller/contract/pre_register.go

@@ -219,7 +219,7 @@ func (rg *PreRegisterController) Add(c *gin.Context) {
 		resp.FailMsg("操作失败", "新增合同失败, Err: "+e.Error(), c)
 		return
 	}
-	if ob.ContractRegisterId == 0{
+	if ob.ContractRegisterId == 0 {
 		resp.FailMsg("操作失败", "新增合同失败,合同ID为0", c)
 		return
 	}
@@ -274,21 +274,19 @@ func (rg *PreRegisterController) Add(c *gin.Context) {
 		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
+		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)
@@ -330,6 +328,13 @@ func (rg *PreRegisterController) Add(c *gin.Context) {
 			pp.SellerGroupName = sellerItem.GroupName
 			pp.SellerTeamId = sellerItem.TeamId
 			pp.SellerTeamName = sellerItem.TeamName
+
+			pp.PaymentSellerId = sellerItem.SellerId
+			pp.PaymentSellerName = sellerItem.SellerName
+			pp.PaymentSellerGroupId = sellerItem.GroupId
+			pp.PaymentSellerGroupName = sellerItem.GroupName
+			pp.PaymentSellerTeamId = sellerItem.TeamId
+			pp.PaymentSellerTeamName = sellerItem.TeamName
 		} else {
 			//到款
 			pp.ArriveId = v.ContractInvoiceId
@@ -338,10 +343,22 @@ func (rg *PreRegisterController) Add(c *gin.Context) {
 			a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", pp.ArriveOriginAmount/rate), 64)
 			pp.ArriveAmount = a
 			pp.ArriveRemark = r.Remark
+
+			sellerItem := sellerMap[r.SellerId]
+			if sellerItem == nil {
+				resp.Fail("销售信息异常", c)
+				return
+			}
+			pp.PaymentSellerId = sellerItem.SellerId
+			pp.PaymentSellerName = sellerItem.SellerName
+			pp.PaymentSellerGroupId = sellerItem.GroupId
+			pp.PaymentSellerGroupName = sellerItem.GroupName
+			pp.PaymentSellerTeamId = sellerItem.TeamId
+			pp.PaymentSellerTeamName = sellerItem.TeamName
 		}
 
 		// 新增开票到款记录
-		if pp.ContractRegisterId == 0{
+		if pp.ContractRegisterId == 0 {
 			resp.FailMsg("操作失败", "新增预登记失败,合同ID为0", c)
 			return
 		}
@@ -474,6 +491,7 @@ func (rg *PreRegisterController) Edit(c *gin.Context) {
 
 	invoiceList := make([]*fms.ContractInvoice, 0)
 	ppList := make([]*fms.ContractPreRegister, 0)
+	var sellerItem *crm.SellerAdminWithGroupTeam
 	for _, r := range req.List {
 		// 货币及汇率
 		rateList, e := fmsService.GetTodayCurrencyRateList()
@@ -519,20 +537,19 @@ func (rg *PreRegisterController) Edit(c *gin.Context) {
 		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
+		sellerItem = sellerMap[r.SellerId]
+		if sellerItem == nil {
+			resp.Fail("销售信息异常", c)
+			return
 		}
+		fmt.Println("SellerId",sellerItem.SellerId)
+		fmt.Println("SellerName",sellerItem.SellerName)
+		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{
@@ -559,7 +576,7 @@ func (rg *PreRegisterController) Edit(c *gin.Context) {
 			a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", pp.OriginAmount/rate), 64)
 			pp.Amount = a
 
-			sellerItem := sellerMap[r.SellerId]
+			sellerItem = sellerMap[r.SellerId]
 			if sellerItem == nil {
 				resp.Fail("销售信息异常", c)
 				return
@@ -572,8 +589,16 @@ func (rg *PreRegisterController) Edit(c *gin.Context) {
 			pp.SellerGroupName = sellerItem.GroupName
 			pp.SellerTeamId = sellerItem.TeamId
 			pp.SellerTeamName = sellerItem.TeamName
+
+			pp.PaymentSellerId = sellerItem.SellerId
+			pp.PaymentSellerName = sellerItem.SellerName
+			pp.PaymentSellerGroupId = sellerItem.GroupId
+			pp.PaymentSellerGroupName = sellerItem.GroupName
+			pp.PaymentSellerTeamId = sellerItem.TeamId
+			pp.PaymentSellerTeamName = sellerItem.TeamName
 			ppUpdateCols = append(ppUpdateCols, "InvoiceDate", "Amount", "OriginAmount", "SellerId",
-				"SellerName", "SellerGroupId", "SellerGroupName", "SellerTeamId", "SellerTeamName", "InvoiceId")
+				"SellerName", "SellerGroupId", "SellerGroupName", "SellerTeamId", "SellerTeamName", "InvoiceId",
+				"PaymentSellerId", "PaymentSellerName", "PaymentSellerGroupId", "PaymentSellerGroupName", "PaymentSellerTeamId", "PaymentSellerTeamName")
 		} else {
 			//到款
 			pp.ArriveRemark = r.Remark
@@ -582,7 +607,21 @@ func (rg *PreRegisterController) Edit(c *gin.Context) {
 			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")
+
+			sellerItem = sellerMap[r.SellerId]
+			if sellerItem == nil {
+				resp.Fail("销售信息异常", c)
+				return
+			}
+
+			pp.PaymentSellerId = sellerItem.SellerId
+			pp.PaymentSellerName = sellerItem.SellerName
+			pp.PaymentSellerGroupId = sellerItem.GroupId
+			pp.PaymentSellerGroupName = sellerItem.GroupName
+			pp.PaymentSellerTeamId = sellerItem.TeamId
+			pp.PaymentSellerTeamName = sellerItem.TeamName
+			ppUpdateCols = append(ppUpdateCols, "CurrencyUnit", "ArriveDate", "ArriveAmount", "ArriveOriginAmount", "ArriveId",
+				"PaymentSellerId", "PaymentSellerName", "PaymentSellerGroupId", "PaymentSellerGroupName", "PaymentSellerTeamId", "PaymentSellerTeamName")
 		}
 
 		if pp.PreRegisterId == 0 {
@@ -606,10 +645,10 @@ func (rg *PreRegisterController) Edit(c *gin.Context) {
 	}
 	invoiceUpdateCols := []string{
 		"CurrencyUnit", "OriginAmount", "Amount", "InvoiceDate", "AdminId", "AdminName", "Remark",
-		"ServiceProductId", "StartDate", "EndDate", "ModifyTime",
+		"ServiceProductId", "StartDate", "EndDate", "ModifyTime", "SellerId", "SellerName", "SellerGroupId", "SellerGroupName", "SellerTeamId", "SellerTeamName",
 	}
 	// 更新合同登记、套餐、开票到款
-	if e = fms.UpdateContractPreRegister(ob, updateCols, serviceList, invoiceList, invoiceUpdateCols, req.DelInvoiceIds, req.DelPreRegisterIds, ppList); e != nil {
+	if e = fms.UpdateContractPreRegister(ob, updateCols, serviceList, invoiceList, invoiceUpdateCols, req.DelInvoiceIds, req.DelPreRegisterIds, ppList, sellerItem, req.RegisterType); e != nil {
 		resp.FailMsg("操作失败", "更新合同及套餐失败, Err: "+e.Error(), c)
 		return
 	}
@@ -792,6 +831,19 @@ func (rg *PreRegisterController) Detail(c *gin.Context) {
 		return
 	}
 
+	if req.DetailType == 1 {
+		dupList, e := fms.GetDuplicateContractInvoiceDetailItemListWithType(nItme.CompanyName, nItme.StartDate, nItme.EndDate, req.InvoiceType)
+		if e != nil {
+			err = fmt.Errorf("获取开票到款列表失败, Err: %s", e.Error())
+			return
+		}
+		for _, v := range dupList {
+			if v.ContractRegisterId != req.ContractRegisterId {
+				list = append(list, v)
+			}
+		}
+	}
+
 	//获取ficc小套餐品种
 	sysConf := new(system.SysConfig)
 	confCond := `config_code = ?`
@@ -1030,23 +1082,21 @@ func (rg *PreRegisterController) Save(c *gin.Context) {
 		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")
+		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 {
 			//更新
@@ -1097,8 +1147,15 @@ func (rg *PreRegisterController) Save(c *gin.Context) {
 			pp.SellerGroupName = sellerItem.GroupName
 			pp.SellerTeamId = sellerItem.TeamId
 			pp.SellerTeamName = sellerItem.TeamName
+			pp.PaymentSellerId = sellerItem.SellerId
+			pp.PaymentSellerName = sellerItem.SellerName
+			pp.PaymentSellerGroupId = sellerItem.GroupId
+			pp.PaymentSellerGroupName = sellerItem.GroupName
+			pp.PaymentSellerTeamId = sellerItem.TeamId
+			pp.PaymentSellerTeamName = sellerItem.TeamName
 			ppUpdateCols = append(ppUpdateCols, "InvoiceDate", "Amount", "OriginAmount", "SellerId",
-				"SellerName", "SellerGroupId", "SellerGroupName", "SellerTeamId", "SellerTeamName", "Remark")
+				"SellerName", "SellerGroupId", "SellerGroupName", "SellerTeamId", "SellerTeamName", "Remark",
+				"PaymentSellerId", "PaymentSellerName", "PaymentSellerGroupId", "PaymentSellerGroupName", "PaymentSellerTeamId", "PaymentSellerTeamName")
 		} else {
 			//到款
 			pp.ArriveRemark = r.Remark
@@ -1106,7 +1163,21 @@ func (rg *PreRegisterController) Save(c *gin.Context) {
 			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")
+
+			sellerItem := sellerMap[r.SellerId]
+			if sellerItem == nil {
+				resp.Fail("销售信息异常", c)
+				return
+			}
+
+			pp.PaymentSellerId = sellerItem.SellerId
+			pp.PaymentSellerName = sellerItem.SellerName
+			pp.PaymentSellerGroupId = sellerItem.GroupId
+			pp.PaymentSellerGroupName = sellerItem.GroupName
+			pp.PaymentSellerTeamId = sellerItem.TeamId
+			pp.PaymentSellerTeamName = sellerItem.TeamName
+			ppUpdateCols = append(ppUpdateCols, "ArriveRemark", "CurrencyUnit", "ArriveDate", "ArriveAmount", "ArriveOriginAmount",
+				"PaymentSellerId", "PaymentSellerName", "PaymentSellerGroupId", "PaymentSellerGroupName", "PaymentSellerTeamId", "PaymentSellerTeamName")
 		}
 
 		ppUpdateCols = append(ppUpdateCols,

+ 652 - 37
controller/contract/register.go

@@ -21,6 +21,7 @@ import (
 	"net/http"
 	"os"
 	"path"
+	"sort"
 	"strconv"
 	"strings"
 	"time"
@@ -381,8 +382,13 @@ func (rg *RegisterController) Add(c *gin.Context) {
 		resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
 		return
 	}
-
+	// 合同有效时长(计算付款方式)
+	dayDiff := ob.EndDate.Sub(ob.StartDate).Hours() / 24
 	// 新增合同及套餐
+	logList := make([]*fms.ContractRegisterLog, 0)
+
+	//是否补录合同
+	sellerItemMap := make(map[int]*crm.SellerAdminWithGroupTeam)
 	if req.Supplement == 1 {
 		//新增到款信息
 		if ob.HasInvoice == 0 {
@@ -405,8 +411,6 @@ func (rg *RegisterController) Add(c *gin.Context) {
 			resp.FailMsg("操作失败", "获取合同开票到款列表失败, Err: "+e.Error(), c)
 			return
 		}
-		// 合同有效时长(计算付款方式)
-		dayDiff := ob.EndDate.Sub(ob.StartDate).Hours() / 24
 
 		// 获取销售分组信息
 		sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
@@ -418,8 +422,48 @@ func (rg *RegisterController) Add(c *gin.Context) {
 		for i := range sellerList {
 			sellerMap[sellerList[i].SellerId] = sellerList[i]
 		}
-		logList := make([]*fms.ContractRegisterLog, 0)
+		//处理重复公司名日期等重复的开票到款记录
+		dupList, e := fms.GetDuplicateContractInvoiceDetailItemList(ob.CompanyName, req.StartDate, req.EndDate)
+		if e != nil {
+			err = fmt.Errorf("获取开票到款列表失败, Err: %s", e.Error())
+			return
+		}
+		templateIds := make([]int, 0)
+		for _, detail := range serviceList {
+			templateIds = append(templateIds, detail.ServiceTemplateId)
+		}
+		sort.Ints(templateIds)
+		ids := make([]string, 0)
+		for _, id := range templateIds {
+			ids = append(ids, strconv.Itoa(id))
+		}
+		templateIdStr := strings.Join(ids, ",")
+		nDupList := make([]*fms.DupInvoice, 0)
+		for _, dup := range dupList {
+			if templateIdStr == dup.TemplateIds {
+				nDupList = append(nDupList, dup)
+			}
+		}
+
+		//先遍历一遍拿到开票销售信息
+		for _, ppItem := range nDupList {
+			if ppItem.ContractRegisterId != req.ContractRegisterId {
+				j := 0
+				if ppItem.InvoiceType == 3 {
+					sellerItemMap[j] = &crm.SellerAdminWithGroupTeam{
+						SellerId:   ppItem.SellerId,
+						SellerName: ppItem.SellerName,
+						GroupId:    ppItem.SellerGroupId,
+						GroupName:  ppItem.SellerGroupName,
+						TeamId:     ppItem.SellerTeamId,
+						TeamName:   ppItem.SellerTeamName,
+					}
+					j++
+				}
+			}
+		}
 		for _, ppItem := range invoiceList {
+			j,k := 0,0
 			v := &fms.ContractInvoice{
 				ContractRegisterId: ob.ContractRegisterId,
 				ContractCode:       ob.ContractCode,
@@ -441,10 +485,29 @@ func (rg *RegisterController) Add(c *gin.Context) {
 				StartDate:          ppItem.StartDate,
 				EndDate:            ppItem.EndDate,
 			}
+
 			if ppItem.InvoiceType == 3 {
 				v.InvoiceType = 1
+				sellerItemMap[j] = &crm.SellerAdminWithGroupTeam{
+					SellerId:   ppItem.SellerId,
+					SellerName: ppItem.SellerName,
+					GroupId:    ppItem.SellerGroupId,
+					GroupName:  ppItem.SellerGroupName,
+					TeamId:     ppItem.SellerTeamId,
+					TeamName:   ppItem.SellerTeamName,
+				}
+				j++
 			} else if ppItem.InvoiceType == 4 {
 				v.InvoiceType = 2
+				if sellerItem, ok := sellerItemMap[k]; ok {
+					v.SellerId = sellerItem.SellerId
+					v.SellerName = sellerItem.SellerName
+					v.SellerGroupId = sellerItem.GroupId
+					v.SellerGroupName = sellerItem.GroupName
+					v.SellerTeamId = sellerItem.TeamId
+					v.SellerTeamName = sellerItem.TeamName
+				}
+				k++
 			}
 			v.Set()
 			// 到款登记-付款方式
@@ -457,7 +520,10 @@ func (rg *RegisterController) Add(c *gin.Context) {
 				return
 			}
 			opData = string(opDataByte)
-			opType := fms.ContractRegisterOpTypePreInvoice
+			opType := fms.ContractRegisterOpTypePrePay
+			if ppItem.InvoiceType == 3 {
+				opType = fms.ContractRegisterOpTypePreInvoice
+			}
 			newAmount := decimal.NewFromFloat(0).Round(2)
 			a := decimal.NewFromFloat(v.Amount).Round(2)
 			newAmount = newAmount.Add(a)
@@ -484,6 +550,106 @@ func (rg *RegisterController) Add(c *gin.Context) {
 				return
 			}
 		}
+
+		for _, ppItem := range nDupList {
+			if ppItem.ContractRegisterId != req.ContractRegisterId {
+				j := 0
+				v := &fms.ContractInvoice{
+					ContractRegisterId: ob.ContractRegisterId,
+					ContractCode:       ob.ContractCode,
+					Amount:             ppItem.Amount,
+					OriginAmount:       ppItem.OriginAmount,
+					CurrencyUnit:       ppItem.CurrencyUnit,
+					InvoiceDate:        ppItem.InvoiceDate,
+					SellerId:           ppItem.SellerId,
+					SellerName:         ppItem.SellerName,
+					SellerGroupId:      ppItem.SellerGroupId,
+					SellerGroupName:    ppItem.SellerGroupName,
+					SellerTeamId:       ppItem.SellerTeamId,
+					SellerTeamName:     ppItem.SellerTeamName,
+					AdminId:            int(adminInfo.AdminId),
+					AdminName:          adminInfo.RealName,
+					Remark:             ppItem.Remark,
+					ServiceProductId:   ppItem.ServiceProductId,
+					IsPrePay:           1,
+					StartDate:          ppItem.StartDate,
+					EndDate:            ppItem.EndDate,
+				}
+				if ppItem.InvoiceType == 3 {
+					v.InvoiceType = 1
+				} else if ppItem.InvoiceType == 4 {
+					v.InvoiceType = 2
+					if sellerItem, ok := sellerItemMap[j]; ok {
+						v.SellerId = sellerItem.SellerId
+						v.SellerName = sellerItem.SellerName
+						v.SellerGroupId = sellerItem.GroupId
+						v.SellerGroupName = sellerItem.GroupName
+						v.SellerTeamId = sellerItem.TeamId
+						v.SellerTeamName = sellerItem.TeamName
+					}
+					j++
+				}
+				v.Set()
+				// 到款登记-付款方式
+				v.PayType = fmsService.CalculateContractPaymentType(ppItem.Amount, ob.ContractAmount, dayDiff)
+
+				// 新增的记录
+				opData := ""
+				opDataByte, e := json.Marshal(req)
+				if e != nil {
+					return
+				}
+				opData = string(opDataByte)
+				opType := fms.ContractRegisterOpTypePrePay
+				if ppItem.InvoiceType == 3 {
+					opType = fms.ContractRegisterOpTypePreInvoice
+				}
+				newAmount := decimal.NewFromFloat(0).Round(2)
+				a := decimal.NewFromFloat(v.Amount).Round(2)
+				newAmount = newAmount.Add(a)
+				ia, _ := newAmount.Round(2).Float64()
+				logList = append(logList, &fms.ContractRegisterLog{
+					ContractRegisterId: ob.ContractRegisterId,
+					AdminId:            int(adminInfo.AdminId),
+					AdminName:          adminInfo.RealName,
+					OpData:             opData,
+					OpType:             opType,
+					CreateTime:         nowTime,
+					AmountRemark:       fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
+				})
+
+				if e := v.Create(); e != nil {
+					resp.FailData("日期格式有误", "Err:"+e.Error(), c)
+					return
+				}
+
+				//最后删除预到款记录
+				e = ppItem.Delete()
+				if e != nil {
+					resp.FailMsg("删除预到款记录失败", "Err:"+e.Error(), c)
+					return
+				}
+			}
+
+			ppOB := new(fms.ContractPreRegister)
+			items, e := ppOB.FetchByRegisterId(ppItem.ContractRegisterId)
+			if e != nil {
+				if e == utils.ErrNoRow {
+					resp.Fail("预登记记录不存在或已被删除", c)
+					return
+				}
+				resp.FailMsg("获取预登记失败", "Err:"+e.Error(), c)
+				return
+			}
+			for _, item := range items {
+				e = item.Delete()
+				if e != nil {
+					resp.FailMsg("删除预登记失败", "Err:"+e.Error(), c)
+					return
+				}
+			}
+		}
+
 		ppOB := new(fms.ContractPreRegister)
 		items, e := ppOB.FetchByRegisterId(req.ContractRegisterId)
 		if e != nil {
@@ -526,6 +692,151 @@ func (rg *RegisterController) Add(c *gin.Context) {
 			resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
 			return
 		}
+		//处理重复公司名日期等重复的开票到款记录
+		dupList, e := fms.GetDuplicateContractInvoiceDetailItemList(ob.CompanyName, req.StartDate, req.EndDate)
+		if e != nil {
+			err = fmt.Errorf("获取开票到款列表失败, Err: %s", e.Error())
+			return
+		}
+		templateIds := make([]int, 0)
+		for _, detail := range serviceList {
+			templateIds = append(templateIds, detail.ServiceTemplateId)
+		}
+		sort.Ints(templateIds)
+		ids := make([]string, 0)
+		for _, id := range templateIds {
+			ids = append(ids, strconv.Itoa(id))
+		}
+		templateIdStr := strings.Join(ids, ",")
+		nDupList := make([]*fms.DupInvoice, 0)
+		for _, dup := range dupList {
+			if templateIdStr == dup.TemplateIds {
+				nDupList = append(nDupList, dup)
+			}
+		}
+		//先遍历一遍拿到开票销售信息
+		for _, ppItem := range nDupList {
+			j := 0
+			if ppItem.ContractRegisterId != req.ContractRegisterId {
+				if ppItem.InvoiceType == 3 {
+					sellerItemMap[j] = &crm.SellerAdminWithGroupTeam{
+						SellerId:   ppItem.SellerId,
+						SellerName: ppItem.SellerName,
+						GroupId:    ppItem.SellerGroupId,
+						GroupName:  ppItem.SellerGroupName,
+						TeamId:     ppItem.SellerTeamId,
+						TeamName:   ppItem.SellerTeamName,
+					}
+				}
+				j++
+			}
+		}
+		for _, ppItem := range nDupList {
+			j := 0
+			if ppItem.ContractRegisterId != req.ContractRegisterId {
+				v := &fms.ContractInvoice{
+					ContractRegisterId: ob.ContractRegisterId,
+					ContractCode:       ob.ContractCode,
+					Amount:             ppItem.Amount,
+					OriginAmount:       ppItem.OriginAmount,
+					CurrencyUnit:       ppItem.CurrencyUnit,
+					InvoiceDate:        ppItem.InvoiceDate,
+					SellerId:           ppItem.SellerId,
+					SellerName:         ppItem.SellerName,
+					SellerGroupId:      ppItem.SellerGroupId,
+					SellerGroupName:    ppItem.SellerGroupName,
+					SellerTeamId:       ppItem.SellerTeamId,
+					SellerTeamName:     ppItem.SellerTeamName,
+					AdminId:            int(adminInfo.AdminId),
+					AdminName:          adminInfo.RealName,
+					Remark:             ppItem.Remark,
+					ServiceProductId:   ppItem.ServiceProductId,
+					IsPrePay:           1,
+					StartDate:          ppItem.StartDate,
+					EndDate:            ppItem.EndDate,
+				}
+				if ppItem.InvoiceType == 3 {
+					v.InvoiceType = 1
+				} else if ppItem.InvoiceType == 4 {
+					v.InvoiceType = 2
+					if sellerItem, ok := sellerItemMap[j]; ok{
+						v.SellerId = sellerItem.SellerId
+						v.SellerName = sellerItem.SellerName
+						v.SellerGroupId = sellerItem.GroupId
+						v.SellerGroupName = sellerItem.GroupName
+						v.SellerTeamId = sellerItem.TeamId
+						v.SellerTeamName = sellerItem.TeamName
+
+						j++
+					}
+				}
+				v.Set()
+				// 到款登记-付款方式
+				v.PayType = fmsService.CalculateContractPaymentType(ppItem.Amount, ob.ContractAmount, dayDiff)
+
+				// 新增的记录
+				opData := ""
+				opDataByte, e := json.Marshal(req)
+				if e != nil {
+					return
+				}
+				opData = string(opDataByte)
+				opType := fms.ContractRegisterOpTypePrePay
+				if ppItem.InvoiceType == 3 {
+					opType = fms.ContractRegisterOpTypePreInvoice
+				}
+				newAmount := decimal.NewFromFloat(0).Round(2)
+				a := decimal.NewFromFloat(v.Amount).Round(2)
+				newAmount = newAmount.Add(a)
+				ia, _ := newAmount.Round(2).Float64()
+				logList = append(logList, &fms.ContractRegisterLog{
+					ContractRegisterId: ob.ContractRegisterId,
+					AdminId:            int(adminInfo.AdminId),
+					AdminName:          adminInfo.RealName,
+					OpData:             opData,
+					OpType:             opType,
+					CreateTime:         nowTime,
+					AmountRemark:       fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
+				})
+
+				if e := v.Create(); e != nil {
+					resp.FailData("日期格式有误", "Err:"+e.Error(), c)
+					return
+				}
+
+				//最后删除预到款记录
+				e = ppItem.Delete()
+				if e != nil {
+					resp.FailMsg("删除预到款记录失败", "Err:"+e.Error(), c)
+					return
+				}
+
+				ppOB := new(fms.ContractPreRegister)
+				items, e := ppOB.FetchByRegisterId(ppItem.ContractRegisterId)
+				if e != nil {
+					if e == utils.ErrNoRow {
+						resp.Fail("预登记记录不存在或已被删除", c)
+						return
+					}
+					resp.FailMsg("获取预登记失败", "Err:"+e.Error(), c)
+					return
+				}
+				for _, item := range items {
+					e = item.Delete()
+					if e != nil {
+						resp.FailMsg("删除预登记失败", "Err:"+e.Error(), c)
+						return
+					}
+				}
+			}
+		}
+		// 操作日志
+		go func() {
+			logOB := new(fms.ContractRegisterLog)
+			if e := logOB.AddInBatches(logList); e != nil {
+				return
+			}
+		}()
 	}
 
 	// 操作日志
@@ -962,11 +1273,11 @@ func (rg *RegisterController) Detail(c *gin.Context) {
 	result.InvoiceList = make([]*fms.ContractInvoiceItem, 0)
 	result.PaymentList = make([]*fms.ContractInvoiceItem, 0)
 	for i := range invoiceList {
-		if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake  || invoiceList[i].InvoiceType == fms.ContractInvoiceTypePreMake{
+		if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake || invoiceList[i].InvoiceType == fms.ContractInvoiceTypePreMake {
 			result.InvoiceList = append(result.InvoiceList, invoiceList[i])
 			continue
 		}
-		if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay || invoiceList[i].InvoiceType == fms.ContractInvoiceTypePrePay{
+		if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay || invoiceList[i].InvoiceType == fms.ContractInvoiceTypePrePay {
 			result.PaymentList = append(result.PaymentList, invoiceList[i])
 		}
 	}
@@ -1091,6 +1402,7 @@ func (rg *RegisterController) Invoice(c *gin.Context) {
 
 	noChangeInvoiceIds := make([]int, 0)
 	newInvoice := make([]*fms.ContractInvoice, 0)
+	sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
 	if len(req.AmountList) > 0 {
 		// 合同有效时长(计算付款方式)
 		dayDiff := item.EndDate.Sub(item.StartDate).Hours() / 24
@@ -1101,7 +1413,6 @@ func (rg *RegisterController) Invoice(c *gin.Context) {
 			resp.FailData("获取销售失败", "Err:"+e.Error(), c)
 			return
 		}
-		sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
 		for i := range sellerList {
 			sellerMap[sellerList[i].SellerId] = sellerList[i]
 		}
@@ -1155,10 +1466,6 @@ func (rg *RegisterController) Invoice(c *gin.Context) {
 						resp.Fail("销售信息异常", c)
 						return
 					}
-					if req.AmountList[i].ServiceProductId == crm.CompanyProductFicc && sellerItem.DepartmentId != crm.SellerDepartmentId {
-						resp.Fail("销售类型和所选套餐类型不一致", c)
-						return
-					}
 					if req.AmountList[i].ServiceProductId == crm.CompanyProductRai && sellerItem.DepartmentId != crm.RaiSellerDepartmentId {
 						resp.Fail("销售类型和所选套餐类型不一致", c)
 						return
@@ -1172,6 +1479,21 @@ func (rg *RegisterController) Invoice(c *gin.Context) {
 				}
 				// 到款登记-付款方式
 				if req.InvoiceType == fms.ContractInvoiceTypePay {
+					sellerItem := sellerMap[req.AmountList[i].SellerId]
+					if sellerItem == nil {
+						resp.Fail("销售信息异常", c)
+						return
+					}
+					if req.AmountList[i].ServiceProductId == crm.CompanyProductRai && sellerItem.DepartmentId != crm.RaiSellerDepartmentId {
+						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
 					v.PayType = fmsService.CalculateContractPaymentType(req.AmountList[i].Amount, item.ContractAmount, dayDiff)
 				}
 				newInvoice = append(newInvoice, v)
@@ -1244,6 +1566,33 @@ func (rg *RegisterController) Invoice(c *gin.Context) {
 		return
 	}
 
+	//如果是开票,强制修改到款记录的销售
+	if len(newInvoice) > 0 && req.InvoiceType == fms.ContractInvoiceTypeMake {
+		invoiceItem, err := fms.GetContractInvoiceByRegisterIdAndType(req.ContractRegisterId)
+		if err != nil && err != utils.ErrNoRow {
+			resp.FailMsg("获取到款数据失败", "获取到款数据失败, Err: "+err.Error(), c)
+			return
+		}
+		if err == nil {
+			sellerItem := sellerMap[newInvoice[0].SellerId]
+			if sellerItem == nil {
+				resp.Fail("销售信息异常", c)
+				return
+			}
+			invoiceItem.SellerId = sellerItem.SellerId
+			invoiceItem.SellerName = sellerItem.SellerName
+			invoiceItem.SellerGroupId = sellerItem.GroupId
+			invoiceItem.SellerGroupName = sellerItem.GroupName
+			invoiceItem.SellerTeamId = sellerItem.TeamId
+			invoiceItem.SellerTeamName = sellerItem.TeamName
+			e = invoiceItem.Update([]string{"SellerId", "SellerName", "SellerGroupId", "SellerGroupName", "SellerTeamId", "SellerTeamName"})
+			if e != nil {
+				resp.FailMsg("更新到款销售失败", "更新到款销售失败, Err: "+e.Error(), c)
+				return
+			}
+		}
+	}
+
 	// todo 判断是否符合均分金额的条件,如果符合,需要生成金额分配记录表
 	if req.InvoiceType == fms.ContractInvoiceTypePay {
 		err = fmsService.CalculatePaymentServiceAmount(req.ContractRegisterId)
@@ -1682,7 +2031,7 @@ func (rg *RegisterController) Export(c *gin.Context) {
 	row3Title := make([]string, 0)
 	row3TitleParent := make([]string, 0)
 	row3Title = append(row3Title, "客户名称", "新客户\n0-是\n1-否", "合同类型\n0-自付合同\n1-代付合同",
-		"合同子类型\n续约-0\n新签-1\n补充协议-2", "合同所属方", "代付方" ,"关联主合同(补充协议)", "关联合同(代付合同)")
+		"合同子类型\n续约-0\n新签-1\n补充协议-2", "合同所属方", "代付方", "关联主合同(补充协议)", "关联合同(代付合同)")
 	if req.ListParam == 0 {
 		row3Title = append(row3Title, "FICC销售", "权益销售", "FICC大套餐")
 		for i := range permissionList {
@@ -1756,7 +2105,7 @@ func (rg *RegisterController) Export(c *gin.Context) {
 			row3Title = append(row3Title, t)
 		}
 	}
-	paymentTitle := []string{"到款日", "到款金额", "套餐类型", "备注"}
+	paymentTitle := []string{"到款日", "到款金额", "套餐类型", "销售", "备注"}
 	for i := 0; i < maxPayment; i++ {
 		n := i + 1
 		for ii := range paymentTitle {
@@ -1803,16 +2152,15 @@ func (rg *RegisterController) Export(c *gin.Context) {
 		dataRow.AddCell().SetString(v.ActualPayCompanies)
 		dataRow.AddCell().SetString(v.RelateContractMainCode)
 		dataRow.AddCell().SetString(v.RelateContractCode)
-		if req.ListParam == 0{
+		if req.ListParam == 0 {
 			dataRow.AddCell().SetString(v.SellerName)
 			dataRow.AddCell().SetString(v.RaiSellerName)
-		} else if req.ListParam == 1{
+		} else if req.ListParam == 1 {
 			dataRow.AddCell().SetString(v.SellerName)
 		} else {
 			dataRow.AddCell().SetString(v.RaiSellerName)
 		}
 
-
 		if req.ListParam != 0 {
 			k += 10
 		} else {
@@ -1879,13 +2227,13 @@ func (rg *RegisterController) Export(c *gin.Context) {
 		dataRow.AddCell().SetString(v.CurrencyUnit)                                      // 货币单位
 		if ficcAmount != nil {
 			dataRow.AddCell().SetString(fmt.Sprint("¥", ficcAmount.ServiceAmount)) // FICC套餐总金额
-			if raiAmount == nil{
-				dataRow.AddCell().SetString("")                                        // 权益套餐总金额
+			if raiAmount == nil {
+				dataRow.AddCell().SetString("") // 权益套餐总金额
 			}
 		}
 		if raiAmount != nil {
-			if ficcAmount == nil{
-				dataRow.AddCell().SetString("")                                       // 权益套餐总金额
+			if ficcAmount == nil {
+				dataRow.AddCell().SetString("") // 权益套餐总金额
 			}
 			dataRow.AddCell().SetString(fmt.Sprint("¥", raiAmount.ServiceAmount)) // FICC套餐总金额
 		}
@@ -1928,6 +2276,7 @@ func (rg *RegisterController) Export(c *gin.Context) {
 					dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", pyList[ib].InvoiceDate)) // 收款日
 					dataRow.AddCell().SetString(fmt.Sprint(pyList[ib].OriginAmount))                            // 收款金额
 					dataRow.AddCell().SetString(serviceProductIdMap[pyList[ib].ServiceProductId])               // 套餐类型
+					dataRow.AddCell().SetString(pyList[ib].SellerName)                                          // 销售名称
 					dataRow.AddCell().SetString(pyList[ib].Remark)                                              // 收款备注
 					continue
 				}
@@ -2223,7 +2572,8 @@ func (rg *RegisterController) Import(c *gin.Context) {
 		resp.Fail("请上传Excel文件", c)
 		return
 	}
-
+	claims, _ := c.Get("adminInfo")
+	adminInfo := claims.(*system.SysAdmin)
 	uploadDir := "static/xls"
 	err = os.MkdirAll(uploadDir, 766)
 	if err != nil {
@@ -2244,7 +2594,7 @@ func (rg *RegisterController) Import(c *gin.Context) {
 		resp.FailData("打开文件失败", "Err:"+err.Error(), c)
 		return
 	}
-
+	logList := make([]*fms.ContractRegisterLog, 0)
 	// 获取所有已登记,根据合同编号去重
 	contractCodeArr := make([]string, 0)
 	registerOB := new(fms.ContractRegister)
@@ -2371,6 +2721,8 @@ func (rg *RegisterController) Import(c *gin.Context) {
 	for _, sheet := range xlFile.Sheets {
 		// 遍历行读取
 		maxRow := sheet.MaxRow
+		fmt.Println("maxRow", maxRow)
+		var dayDiff float64
 		for i := 0; i < maxRow; i++ {
 			// 第三行开始读取表头
 			if i == 2 {
@@ -2479,11 +2831,12 @@ func (rg *RegisterController) Import(c *gin.Context) {
 					v := utils.TrimStr(cell.String())
 					// 客户名称
 					if k == 0 {
-						if v == "" {
+						//pool_474 客户名称保留空格
+						if cell.String() == "" {
 							resp.Fail(fmt.Sprintf("第%d行客户名称不可为空, 请按模板导入", i+1), c)
 							return
 						}
-						rowRegister.CompanyName = v
+						rowRegister.CompanyName = cell.String()
 						continue
 					}
 					// 是否新客户
@@ -2517,7 +2870,7 @@ func (rg *RegisterController) Import(c *gin.Context) {
 						continue
 					}
 					if k == 4 {
-						if rowRegister.HasPayment == 1{
+						if rowRegister.HasPayment == 1 {
 							if v == "0" {
 								//所属方为实际使用方,不走开票到款流程
 								rowRegister.HasInvoice = 0
@@ -2823,11 +3176,7 @@ func (rg *RegisterController) Import(c *gin.Context) {
 					// FICC 套餐总金额
 					if k == 62 {
 						amountStr := v
-						amount, e := strconv.ParseFloat(amountStr, 64)
-						if e != nil {
-							resp.Fail(fmt.Sprintf("第%d行FICC套餐总金额有误, 请按模板导入", i+1), c)
-							return
-						}
+						amount, _ := strconv.ParseFloat(amountStr, 64)
 						if amount > 0 {
 							tmp := &fms.ContractServiceAmount{
 								ProductId:     crm.CompanyProductFicc,
@@ -2842,11 +3191,7 @@ func (rg *RegisterController) Import(c *gin.Context) {
 					// 权益套餐总金额
 					if k == 63 {
 						amountStr := v
-						amount, e := strconv.ParseFloat(amountStr, 64)
-						if e != nil {
-							resp.Fail(fmt.Sprintf("第%d行权益套餐总金额有误, 请按模板导入", i+1), c)
-							return
-						}
+						amount, _ := strconv.ParseFloat(amountStr, 64)
 						if amount > 0 {
 							tmp := &fms.ContractServiceAmount{
 								ProductId:     crm.CompanyProductRai,
@@ -3046,7 +3391,7 @@ func (rg *RegisterController) Import(c *gin.Context) {
 									return
 								}
 								// 付款方式
-								dayDiff := rowRegister.EndDate.Sub(rowRegister.StartDate).Hours() / 24
+								dayDiff = rowRegister.EndDate.Sub(rowRegister.StartDate).Hours() / 24
 								contractAmount := rowRegister.ContractAmount
 								payType := fmsService.CalculateContractPaymentType(amount, contractAmount, dayDiff)
 								rowPayments[ir].PayType = payType
@@ -3073,6 +3418,25 @@ func (rg *RegisterController) Import(c *gin.Context) {
 							continue
 						}
 
+						// 到款销售
+						k2 += 1
+						if k == k2 {
+							if v != "" {
+								sellerItem := sellerMap[v]
+								if sellerItem == nil {
+									resp.Fail(fmt.Sprintf("第%d行到款销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
+									return
+								}
+								rowPayments[ir].SellerId = sellerItem.SellerId
+								rowPayments[ir].SellerName = sellerItem.SellerName
+								rowPayments[ir].SellerGroupId = sellerItem.GroupId
+								rowPayments[ir].SellerGroupName = sellerItem.GroupName
+								rowPayments[ir].SellerTeamId = sellerItem.TeamId
+								rowPayments[ir].SellerTeamName = sellerItem.TeamName
+							}
+							continue
+						}
+
 						// 备注
 						k2 += 1
 						if k == k2 {
@@ -3147,13 +3511,163 @@ func (rg *RegisterController) Import(c *gin.Context) {
 					resp.FailData(fmt.Sprintf("第%d行导入失败", i+1), "新增导入登记失败, Err: "+e.Error(), c)
 					return
 				}
+
+				//处理重复公司名日期等重复的开票到款记录
+				sellerItemMap := make(map[int]*crm.SellerAdminWithGroupTeam)
+				dupList, e := fms.GetDuplicateContractInvoiceDetailItemList(rowRegister.CompanyName, rowRegister.StartDate.Format(utils.FormatDate), rowRegister.EndDate.Format(utils.FormatDate))
+				if e != nil {
+					err = fmt.Errorf("获取开票到款列表失败, Err: %s", e.Error())
+					return
+				}
+				templateIds := make([]int, 0)
+				for _, detail := range rowServices {
+					templateIds = append(templateIds, detail.ServiceTemplateId)
+				}
+				sort.Ints(templateIds)
+				ids := make([]string, 0)
+				for _, id := range templateIds {
+					ids = append(ids, strconv.Itoa(id))
+				}
+				templateIdStr := strings.Join(ids, ",")
+				nDupList := make([]*fms.DupInvoice, 0)
+				for _, dup := range dupList {
+					if templateIdStr == dup.TemplateIds {
+						nDupList = append(nDupList, dup)
+					}
+				}
+				//先遍历一遍拿到开票销售信息
+				for _, ppItem := range dupList {
+					j := 0
+					if ppItem.ContractRegisterId != newId {
+						if ppItem.InvoiceType == 3 {
+							sellerItemMap[j] = &crm.SellerAdminWithGroupTeam{
+								SellerId:   ppItem.SellerId,
+								SellerName: ppItem.SellerName,
+								GroupId:    ppItem.SellerGroupId,
+								GroupName:  ppItem.SellerGroupName,
+								TeamId:     ppItem.SellerTeamId,
+								TeamName:   ppItem.SellerTeamName,
+							}
+						}
+						j++
+					}
+				}
+				for _, ppItem := range dupList {
+					j := 0
+					if ppItem.ContractRegisterId != newId {
+						v := &fms.ContractInvoice{
+							ContractRegisterId: newId,
+							ContractCode:       rowRegister.ContractCode,
+							Amount:             ppItem.Amount,
+							OriginAmount:       ppItem.OriginAmount,
+							CurrencyUnit:       ppItem.CurrencyUnit,
+							InvoiceDate:        ppItem.InvoiceDate,
+							SellerId:           ppItem.SellerId,
+							SellerName:         ppItem.SellerName,
+							SellerGroupId:      ppItem.SellerGroupId,
+							SellerGroupName:    ppItem.SellerGroupName,
+							SellerTeamId:       ppItem.SellerTeamId,
+							SellerTeamName:     ppItem.SellerTeamName,
+							AdminId:            int(adminInfo.AdminId),
+							AdminName:          adminInfo.RealName,
+							Remark:             ppItem.Remark,
+							ServiceProductId:   ppItem.ServiceProductId,
+							IsPrePay:           1,
+							StartDate:          ppItem.StartDate,
+							EndDate:            ppItem.EndDate,
+						}
+						if ppItem.InvoiceType == 3 {
+							v.InvoiceType = 1
+						} else if ppItem.InvoiceType == 4 {
+							v.InvoiceType = 2
+							if sellerItem, ok := sellerItemMap[j]; ok{
+								v.SellerId = sellerItem.SellerId
+								v.SellerName = sellerItem.SellerName
+								v.SellerGroupId = sellerItem.GroupId
+								v.SellerGroupName = sellerItem.GroupName
+								v.SellerTeamId = sellerItem.TeamId
+								v.SellerTeamName = sellerItem.TeamName
+
+								j++
+							}
+						}
+						v.Set()
+						// 到款登记-付款方式
+						v.PayType = fmsService.CalculateContractPaymentType(ppItem.Amount, rowRegister.ContractAmount, dayDiff)
+
+						// 新增的记录
+						opData := ""
+						//opDataByte, e := json.Marshal(req)
+						if e != nil {
+							return
+						}
+						//opData = string(opDataByte)
+						opType := fms.ContractRegisterOpTypePrePay
+						if ppItem.InvoiceType == 3 {
+							opType = fms.ContractRegisterOpTypePreInvoice
+						}
+						newAmount := decimal.NewFromFloat(0).Round(2)
+						a := decimal.NewFromFloat(v.Amount).Round(2)
+						newAmount = newAmount.Add(a)
+						ia, _ := newAmount.Round(2).Float64()
+						logList = append(logList, &fms.ContractRegisterLog{
+							ContractRegisterId: newId,
+							AdminId:            int(adminInfo.AdminId),
+							AdminName:          adminInfo.RealName,
+							OpData:             opData,
+							OpType:             opType,
+							CreateTime:         time.Now().Local(),
+							AmountRemark:       fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
+						})
+
+						if e := v.Create(); e != nil {
+							resp.FailData("日期格式有误", "Err:"+e.Error(), c)
+							return
+						}
+
+						//最后删除预到款记录
+						e = ppItem.Delete()
+						if e != nil {
+							resp.FailMsg("删除预到款记录失败", "Err:"+e.Error(), c)
+							return
+						}
+
+						ppOB := new(fms.ContractPreRegister)
+						items, e := ppOB.FetchByRegisterId(ppItem.ContractRegisterId)
+						if e != nil {
+							if e == utils.ErrNoRow {
+								resp.Fail("预登记记录不存在或已被删除", c)
+								return
+							}
+							resp.FailMsg("获取预登记失败", "Err:"+e.Error(), c)
+							return
+						}
+						for _, item := range items {
+							e = item.Delete()
+							if e != nil {
+								resp.FailMsg("删除预登记失败", "Err:"+e.Error(), c)
+								return
+							}
+						}
+					}
+				}
 				// 自动分配套餐金额
 				go fmsService.CalculatePaymentServiceAmount(newId)
 				newIds = append(newIds, newId)
+
+
 			}
 		}
 	}
 
+	// 操作日志
+	go func() {
+		logOB := new(fms.ContractRegisterLog)
+		if e := logOB.AddInBatches(logList); e != nil {
+			return
+		}
+	}()
+
 	resp.Ok("操作成功", c)
 }
 
@@ -3265,3 +3779,104 @@ func (rg *RegisterController) CheckContractName(c *gin.Context) {
 	resp.OkData("查询成功", data, c)
 	return
 }
+
+// CheckContract
+// @Title 货币单位列表
+// @Description 货币单位列表
+// @Success 200 {object} fms.CheckContractNameResp
+// @router /contract/register/check_contract_duplicate [post]
+func (rg *RegisterController) CheckContractDuplicate(c *gin.Context) {
+	var req fms.CheckContractDuplicateReq
+	if e := c.ShouldBind(&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
+	}
+	existCond := ""
+	existPars := make([]interface{}, 0)
+	if req.CompanyName != "" {
+		// 是否存在相同的合同名称的登记
+		existCond = ` company_name = ?`
+		existPars = append(existPars, req.CompanyName)
+	}
+
+	if req.StartDate != "" && req.EndDate != "" {
+		// 日期校验
+		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
+		}
+		if existCond != "" {
+			existCond += ` AND (start_date =? and end_date=?)`
+		} else {
+			existCond = ` start_date = ? and end_date=?`
+		}
+
+		existPars = append(existPars, startDate, endDate)
+	}
+
+	if existCond == "" {
+		resp.Fail("请输入合同名称或者合同有效期", c)
+		return
+	}
+	data := fms.CheckContractDuplicateResp{
+		Exist: 0,
+	}
+
+	// 是否存在相同合同名称的登记
+	list, e := fms.CheckContractDuplicate(existCond, existPars)
+	if e != nil {
+		resp.FailMsg("操作失败", "查询重复合同失败, Err: "+e.Error(), c)
+		return
+	}
+
+	registerIds := make([]int, 0)
+	for i := range list {
+		registerIds = append(registerIds, list[i].ContractRegisterId)
+	}
+
+	idlist, e := fms.CheckContractServiceDuplicate(registerIds)
+	if e != nil {
+		resp.FailMsg("操作失败", "查询重复合同套餐失败, Err: "+e.Error(), c)
+		return
+	}
+
+	//校验套餐
+	if len(req.Services) > 0 {
+		serviceAmountMap := make(map[int]float64)
+		serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
+		if e != nil {
+			resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
+			return
+		}
+		templateIds := make([]int, 0)
+		for _, detail := range serviceList {
+			templateIds = append(templateIds, detail.ServiceTemplateId)
+		}
+		sort.Ints(templateIds)
+		ids := make([]string, 0)
+		for _, id := range templateIds {
+			ids = append(ids, strconv.Itoa(id))
+		}
+		templateIdStr := strings.Join(ids, ",")
+
+		for _, s := range idlist {
+			if templateIdStr == *s {
+				data.Exist = 1
+			}
+		}
+	}
+
+	resp.OkData("查询成功", data, c)
+	return
+}

+ 3 - 2
models/fms/constants.go

@@ -25,8 +25,9 @@ const (
 	ContractRegisterOpTypeStatus     = 4 // 修改合同状态
 	ContractRegisterOpTypeDel        = 5 // 删除合同登记
 	ContractRegisterOpTypeEdit       = 6 // 合规编辑
-	ContractRegisterOpTypePreInvoice = 7 // 开票预登记
-	ContractRegisterOpTypePrePay     = 8 // 到款预登记
+	ContractRegisterOpTypePrePay     = 7 // 到款预登记
+	ContractRegisterOpTypePreInvoice = 8 // 开票预登记
+
 
 	// 合同登记开票类型
 	ContractInvoiceTypeMake    = 1 // 开票登记

+ 43 - 0
models/fms/contract_invoice.go

@@ -331,6 +331,7 @@ type InvoicePaymentCensusResp struct {
 	DataList             []*InvoicePaymentCensusItem `json:"data_list"`
 	InvoiceTotal         float64                     `json:"invoice_total" description:"开票总金额(换算后)"`
 	PaymentTotal         float64                     `json:"payment_total" description:"到款总金额(换算后)"`
+	AmountTotal          float64                     `json:"amount_total" description:"合计总金额(换算后)"`
 	InvoiceCurrencyTotal []*InvoiceListCurrencyTotal `json:"invoice_currency_total" description:"开票-分币种总金额"`
 	PaymentCurrencyTotal []*InvoiceListCurrencyTotal `json:"payment_currency_total" description:"到款-分币种总金额"`
 }
@@ -596,3 +597,45 @@ func (c *ContractInvoice) FetchByRegisterId(registerId int) (items []*ContractIn
 	err = global.DEFAULT_MYSQL.Model(c).Where("is_deleted = 0 AND contract_register_id = ?", registerId).Scan(&items).Error
 	return
 }
+
+// GetDuplicateContractInvoiceDetailItemListWithType 预登记列表详情用-获取开票到款列表
+func GetDuplicateContractInvoiceDetailItemListWithType(companyName, startDate, endDate string, invoiceType int) (itemList []*ContractInvoiceDetailItem, err error) {
+	list := make([]*ContractInvoice, 0)
+	err = global.DEFAULT_MYSQL.Table("contract_invoice as a ").
+		Select(" a.* ").
+		Joins(" JOIN contract_register as b ON a.contract_register_id = b.contract_register_id ").
+		Where(fmt.Sprintf("a.is_deleted = 0 AND b.company_name = '%s' AND b.start_date= '%s' AND b.end_date= '%s' AND b.is_deleted=0 AND (a.invoice_type=3 OR a.invoice_type=4) AND a.invoice_type = %v ",companyName, startDate, endDate, invoiceType)).
+		Order("a.contract_invoice_id ASC").
+		Find(&list).Error
+	if err != nil {
+		return
+	}
+	itemList = formatContractInvoice2DetailItemList(list)
+	return
+}
+
+func GetContractInvoiceByRegisterIdAndType(registerId int) (items *ContractInvoice, err error) {
+	err = global.DEFAULT_MYSQL.Model(ContractInvoice{}).Where("is_deleted = 0 AND contract_register_id = ? AND invoice_type = 2", registerId).Order("create_time DESC").First(&items).Error
+	return
+}
+
+type DupInvoice struct {
+	ContractInvoice
+	TemplateIds string
+}
+
+// GetDuplicateContractInvoiceDetailItemList 预登记列表详情用-获取开票到款列表
+func GetDuplicateContractInvoiceDetailItemList(companyName, startDate, endDate string) (list []*DupInvoice, err error) {
+	err = global.DEFAULT_MYSQL.Table("contract_invoice as a ").
+		Select(" a.*,GROUP_CONCAT(c.service_template_id ORDER BY c.service_template_id ) AS template_ids ").
+		Joins(" JOIN contract_register as b ON a.contract_register_id = b.contract_register_id ").
+		Joins("JOIN contract_service AS c ON a.contract_register_id = c.contract_register_id").
+		Where(fmt.Sprintf("a.is_deleted = 0 AND b.company_name = '%s' AND b.start_date= '%s' AND b.end_date= '%s' AND b.is_deleted=0 AND (a.invoice_type=3 OR a.invoice_type=4) ",companyName, startDate, endDate)).
+		Group("a.contract_register_id").
+		Order("a.contract_invoice_id ASC").
+		Find(&list).Error
+	if err != nil {
+		return
+	}
+	return
+}

+ 71 - 52
models/fms/contract_pre_register.go

@@ -9,33 +9,39 @@ import (
 
 // 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:"约定结束时间"`
+	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:"约定结束时间"`
+	PaymentSellerId        int       `gorm:"column:payment_seller_id;default:0;NOT NULL" json:"payment_seller_id"`             // 销售ID
+	PaymentSellerName      string    `gorm:"column:payment_seller_name;NOT NULL" json:"payment_seller_name"`                   // 销售名称
+	PaymentSellerGroupId   int       `gorm:"column:payment_seller_group_id;default:0;NOT NULL" json:"payment_seller_group_id"` // 销售分组ID
+	PaymentSellerGroupName string    `gorm:"column:payment_seller_group_name;NOT NULL" json:"payment_seller_group_name"`       // 销售分组名称
+	PaymentSellerTeamId    int       `gorm:"column:payment_seller_team_id;default:0;NOT NULL" json:"payment_seller_team_id"`   // 销售小组ID
+	PaymentSellerTeamName  string    `gorm:"column:payment_seller_team_name;NOT NULL" json:"payment_seller_team_name"`         // 销售小组名称
 	base.TimeBase
 }
 
@@ -45,31 +51,37 @@ func (c *ContractPreRegister) TableName() string {
 
 // 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:"创建时间"`
+	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:"创建时间"`
+	PaymentSellerId        int     `gorm:"column:payment_seller_id;default:0;NOT NULL" json:"payment_seller_id"`             // 销售ID
+	PaymentSellerName      string  `gorm:"column:payment_seller_name;NOT NULL" json:"payment_seller_name"`                   // 销售名称
+	PaymentSellerGroupId   int     `gorm:"column:payment_seller_group_id;default:0;NOT NULL" json:"payment_seller_group_id"` // 销售分组ID
+	PaymentSellerGroupName string  `gorm:"column:payment_seller_group_name;NOT NULL" json:"payment_seller_group_name"`       // 销售分组名称
+	PaymentSellerTeamId    int     `gorm:"column:payment_seller_team_id;default:0;NOT NULL" json:"payment_seller_team_id"`   // 销售小组ID
+	PaymentSellerTeamName  string  `gorm:"column:payment_seller_team_name;NOT NULL" json:"payment_seller_team_name"`         // 销售小组名称
 }
 
 // formatContractInvoice2Item 格式化ContractInvoiceItem
@@ -98,6 +110,12 @@ func formatContractPreRegister2Item(item *ContractPreRegister) (formatItem *Cont
 	formatItem.CreateTime = utils.TimeTransferString(utils.FormatDateTime, item.CreateTime)
 	formatItem.StartDate = item.StartDate.Format(utils.FormatDate)
 	formatItem.EndDate = item.EndDate.Format(utils.FormatDate)
+	formatItem.PaymentSellerId = item.PaymentSellerId
+	formatItem.PaymentSellerName = item.PaymentSellerName
+	formatItem.PaymentSellerGroupId = item.PaymentSellerGroupId
+	formatItem.PaymentSellerGroupName = item.PaymentSellerGroupName
+	formatItem.PaymentSellerTeamId = item.PaymentSellerTeamId
+	formatItem.PaymentSellerTeamName = item.PaymentSellerTeamName
 	return
 }
 
@@ -201,6 +219,7 @@ type PreRegisterDetailReq struct {
 	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"`
+	DetailType         int `json:"detail_type" description:"请求类型"`
 }
 
 // ContractPreRegisterDetail 预登记详情

+ 95 - 20
models/fms/contract_register.go

@@ -4,6 +4,7 @@ import (
 	"fmt"
 	"hongze/fms_api/global"
 	"hongze/fms_api/models/base"
+	"hongze/fms_api/models/crm"
 	"hongze/fms_api/utils"
 	"time"
 )
@@ -563,7 +564,7 @@ type CheckContractNameResp struct {
 
 // UpdateContractPreRegister 更新合同预登记
 func UpdateContractPreRegister(item *ContractRegister, updateCols []string, serviceDetail []*ContractServiceAndDetail,
-	invoiceList []*ContractInvoice, invoiceUpdateCols []string, delInvoiceIds, delPreRegisterIds []int, ppList []*ContractPreRegister) (err error) {
+	invoiceList []*ContractInvoice, invoiceUpdateCols []string, delInvoiceIds, delPreRegisterIds []int, ppList []*ContractPreRegister, sellerItem *crm.SellerAdminWithGroupTeam, registerType int) (err error) {
 	tx := global.DEFAULT_MYSQL.Begin()
 	defer func() {
 		if err != nil {
@@ -615,6 +616,8 @@ func UpdateContractPreRegister(item *ContractRegister, updateCols []string, serv
 	}
 
 	for i := range invoiceList {
+		fmt.Println("invoiceList[i].SellerName",invoiceList[i].SellerName)
+		fmt.Println("invoiceList[i].SellerId",invoiceList[i].SellerId)
 		if invoiceList[i].ContractInvoiceId == 0 {
 			if e := invoiceList[i].Create(); e != nil {
 				err = e
@@ -653,8 +656,39 @@ func UpdateContractPreRegister(item *ContractRegister, updateCols []string, serv
 		StartDate:          item.StartDate,
 		EndDate:            item.EndDate,
 		CurrencyUnit:       item.CurrencyUnit,
-	}
-	tx.Model(&invoiceItem).Select([]string{"StartDate", "EndDate", "CurrencyUnit"}).Where("ContractRegisterId", item.ContractRegisterId).Updates(invoiceItem)
+		SellerId:           sellerItem.SellerId,
+		SellerName:         sellerItem.SellerName,
+		SellerGroupId:      sellerItem.GroupId,
+		SellerGroupName:    sellerItem.GroupName,
+		SellerTeamId:       sellerItem.TeamId,
+		SellerTeamName:     sellerItem.TeamName,
+	}
+	if registerType == 3{
+		tx.Model(&invoiceItem).Select([]string{"StartDate", "EndDate", "CurrencyUnit","SellerId",
+			"SellerName","SellerGroupId","SellerGroupName","SellerTeamId","SellerTeamName"}).Where("contract_register_id = ? AND invoice_type = 4", item.ContractRegisterId).Updates(invoiceItem)
+	} else {
+		tx.Model(&invoiceItem).Select([]string{"StartDate", "EndDate", "CurrencyUnit"}).Where("contract_register_id", item.ContractRegisterId).Updates(invoiceItem)
+	}
+
+	//pp := &ContractPreRegister{}
+	//ppItem, e := pp.Fetch(ppList[0].PreRegisterId)
+	//if e != nil {
+	//	err = e
+	//}
+	//otherInvoiceItem := ContractInvoice{}
+	//if ppList[0].InvoiceType == ContractInvoiceTypePreMake {
+	//	otherInvoiceItem.ContractInvoiceId = ppItem.ArriveId
+	//	if ppItem.ArriveId > 0 {
+	//		//如果是开票类型,那么更新预登记里的预到款销售信息
+	//		otherInvoiceItem.SellerId = invoiceList[0].SellerId
+	//		otherInvoiceItem.SellerName = invoiceList[0].SellerName
+	//		otherInvoiceItem.SellerGroupId = invoiceList[0].SellerGroupId
+	//		otherInvoiceItem.SellerGroupName = invoiceList[0].SellerGroupName
+	//		otherInvoiceItem.SellerTeamId = invoiceList[0].SellerTeamId
+	//		otherInvoiceItem.SellerTeamName = invoiceList[0].SellerTeamName
+	//	}
+	//	tx.Model(&otherInvoiceItem).Select([]string{"SellerId", "SellerName", "SellerGroupId","SellerGroupName","SellerTeamId","SellerTeamName"}).Updates(otherInvoiceItem)
+	//}
 
 	//删除
 	if len(delInvoiceIds) > 0 {
@@ -735,6 +769,34 @@ func UpdateContractRegisterPre(item *ContractRegister, updateCols []string, serv
 		productId = invoiceList[0].ServiceProductId
 	}
 
+	pp := &ContractPreRegister{}
+	ppItem, e := pp.Fetch(ppList[0].PreRegisterId)
+	if e != nil {
+		err = e
+	}
+	//更新同一预登记记录下的productid
+	otherInvoiceItem := ContractInvoice{
+		ServiceProductId: productId,
+	}
+	if ppList[0].InvoiceType == ContractInvoiceTypePreMake {
+		otherInvoiceItem.ContractInvoiceId = ppItem.ArriveId
+		if ppItem.ArriveId > 0 {
+			//如果是开票类型,那么更新预登记里的预到款销售信息
+			otherInvoiceItem.SellerId = invoiceList[0].SellerId
+			otherInvoiceItem.SellerName = invoiceList[0].SellerName
+			otherInvoiceItem.SellerGroupId = invoiceList[0].SellerGroupId
+			otherInvoiceItem.SellerGroupName = invoiceList[0].SellerGroupName
+			otherInvoiceItem.SellerTeamId = invoiceList[0].SellerTeamId
+			otherInvoiceItem.SellerTeamName = invoiceList[0].SellerTeamName
+		}
+		tx.Model(&otherInvoiceItem).Select([]string{"ServiceProductId","SellerId", "SellerName", "SellerGroupId","SellerGroupName","SellerTeamId","SellerTeamName"}).Updates(otherInvoiceItem)
+	} else {
+		otherInvoiceItem.ContractInvoiceId = ppItem.InvoiceId
+		tx.Model(&otherInvoiceItem).Select([]string{"ServiceProductId"}).Updates(otherInvoiceItem)
+	}
+
+
+
 	//更新另一类型的invoice表数据
 	invoiceItem := ContractInvoice{
 		ContractRegisterId: item.ContractRegisterId,
@@ -779,23 +841,6 @@ func UpdateContractRegisterPre(item *ContractRegister, updateCols []string, serv
 		}
 	}
 
-	pp := &ContractPreRegister{}
-	ppItem, e := pp.Fetch(ppList[0].PreRegisterId)
-	if e != nil {
-		err = e
-	}
-	//更新同一预登记记录下的productid
-	otherInvoiceItem := ContractInvoice{
-		ServiceProductId: productId,
-	}
-	if ppList[0].InvoiceType == 3 {
-		otherInvoiceItem.ContractInvoiceId = ppItem.ArriveId
-	} else {
-		otherInvoiceItem.ContractInvoiceId = ppItem.InvoiceId
-	}
-
-	tx.Model(&otherInvoiceItem).Select([]string{"ServiceProductId"}).Updates(otherInvoiceItem)
-
 	return
 }
 
@@ -863,3 +908,33 @@ func UpdateSupplementContractPreRegister(item *ContractRegister, serviceAmountLi
 
 	return
 }
+
+type CheckContractDuplicateReq 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:"合同结束日期"`
+	Services    []ContractServiceAddReq `json:"services" description:"服务套餐内容"`
+}
+
+func CheckContractDuplicate(condition string, pars []interface{}) (list []*ContractRegister,err error) {
+	query := global.DEFAULT_MYSQL.Table("contract_register AS a").
+		Select("a.* ").
+		Joins(" JOIN contract_service AS b ON a.contract_register_id = b.contract_register_id ").
+		Where(condition, pars...).
+		Group("a.contract_register_id")
+	err = query.Find(&list).Error
+	return
+}
+
+
+type CheckContractDuplicateResp struct {
+	Exist int `json:"exist" description:"是否存在重复的合同:0不存在,1存在"`
+}
+
+func CheckContractServiceDuplicate(registerIds []int) (ids []*string, err error) {
+	err = global.DEFAULT_MYSQL.Table("contract_service").
+		Select("GROUP_CONCAT(service_template_id ORDER BY service_template_id)  AS ids ").
+		Where("contract_register_id IN (?)", registerIds).
+		Group("contract_register_id").Scan(&ids).Error
+	return
+}

+ 24 - 2
models/fms/invoice_payment_summary.go

@@ -95,8 +95,8 @@ type InvoicePaymentSummaryItem struct {
 // GetInvoicePaymentCensusSummaryData 获取商品到款统计列表-汇总数据
 func GetInvoicePaymentCensusSummaryData(condition string, pars []interface{}) (results []*InvoicePaymentSummaryItem, err error) {
 	fields := []string{"a.id AS summary_id", "a.register_id", "a.invoice_id", "a.payment_id", "a.service_product_id", "b.company_name", "b.start_date", "b.end_date",
-		"c.origin_amount AS invoice_amount", "c.invoice_time AS invoice_date", "c.seller_id", "c.seller_name", "c.seller_group_id",
-		"c.seller_group_name", "d.origin_amount AS payment_amount", "d.invoice_time AS payment_date", "d.pay_type",
+		"c.origin_amount AS invoice_amount", "c.invoice_time AS invoice_date", "IF(c.seller_id > 0, c.seller_id, d.seller_id) AS seller_id", "IF(c.seller_name = '' OR c.seller_name IS NULL, d.seller_name, c.seller_name) AS seller_name", "IF(c.seller_group_id > 0,c.seller_group_id,d.seller_group_id) AS seller_group_id",
+		"IF(c.seller_group_name = '' OR c.seller_group_name IS NULL, d.seller_group_name, c.seller_group_name) AS seller_group_name", "d.origin_amount AS payment_amount", "d.invoice_time AS payment_date", "d.pay_type",
 	}
 	query := global.DEFAULT_MYSQL.Table("invoice_payment_summary AS a").
 		Select(strings.Join(fields, ",")).
@@ -161,4 +161,26 @@ func DeleteInvoicePaymentSummaryByInvoiceIdAndPaymentId(invoiceId, arriveId, reg
 	sql := `DELETE FROM invoice_payment_summary WHERE invoice_id = ? AND payment_id = ? AND register_id = ?`
 	err = global.DEFAULT_MYSQL.Exec(sql, invoiceId, arriveId, registerId).Error
 	return
+}
+
+// GetContractSummaryInvoicePaymentAmount 获取汇总金额合计信息
+func GetContractSummaryInvoicePaymentAmount(condition string, pars []interface{}) (amountTotal float64, err error) {
+	joinCond := ` (a.invoice_id = b.contract_invoice_id OR a.payment_id = b.contract_invoice_id) `
+
+	query := global.DEFAULT_MYSQL.Table("invoice_payment_summary AS a").
+		Select("b.amount").
+		Joins(fmt.Sprintf(" JOIN contract_invoice AS b ON %s AND b.is_deleted = 0 ", joinCond)).
+		Where(condition, pars...).Group("id")
+	nq := global.DEFAULT_MYSQL.Table("(?) AS e", query).
+		Select(" IFNULL( SUM( e.amount ), 0 ) ")
+
+	err = nq.Find(&amountTotal).Error
+	return
+}
+
+// GetInvoicePaymentSummaryByRegisterIdAndInvoiceId 根据合同登记ID和开票ID获取汇总数据
+func GetInvoicePaymentSummaryByRegisterIdAndInvoiceId(registerId,invocieId int) (results []*ContractRegisterSummary, err error) {
+	sql := `SELECT * FROM invoice_payment_summary WHERE register_id = ? AND invoice_id= ? `
+	err = global.DEFAULT_MYSQL.Exec(sql, registerId, invocieId).Find(&results).Error
+	return
 }

+ 1 - 0
routers/contract.go

@@ -23,6 +23,7 @@ func InitContract(rg *gin.RouterGroup) {
 	crGroup.POST("import", cr.Import)
 	crGroup.GET("currency_list", cr.CurrencyList)
 	crGroup.GET("check_contract_code", cr.CheckContractName)
+	crGroup.POST("check_contract_duplicate", cr.CheckContractDuplicate)
 
 	// 合同套餐
 	sr := new(contract.ServiceController)