瀏覽代碼

Merge branch 'master' into dev/2.4_rai_new

# Conflicts:
#	controller/contract/register.go
#	models/fms/contract_invoice.go
#	models/fms/contract_register.go
xiexiaoyuan 2 年之前
父節點
當前提交
c732c8867a

+ 256 - 53
controller/contract/pre_payment.go

@@ -8,6 +8,10 @@ import (
 	"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 合同登记
@@ -17,8 +21,8 @@ type PrePaymentController struct{}
 // @Title 到款预登记列表
 // @Description 到款预登记列表
 // @Param   Keyword			query	string	false	"关键词"
-// @Param   StartDate		query	string	false	"合同开始日期"
-// @Param   EndDate			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]
@@ -36,11 +40,11 @@ func (rg *PrePaymentController) List(c *gin.Context) {
 
 	cond := `1 = 1`
 	pars := make([]interface{}, 0)
-	// 合同编号/客户姓名/销售/实际使用方
+	// 客户姓名/销售
 	if req.Keyword != "" {
 		kw := "%" + req.Keyword + "%"
-		cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR actual_company_name LIKE ?)`
-		pars = append(pars, kw, kw, kw, kw)
+		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")
@@ -49,74 +53,273 @@ func (rg *PrePaymentController) List(c *gin.Context) {
 		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)
-	page.AddOrderItem(base.OrderItem{Column: "create_time", Asc: false})
+	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.GetContractRegisterItemPageList(page, cond, pars)
+	total, list, e := fms.GetPrePayItemPageList(page, cond, pars)
 	if e != nil {
-		resp.FailMsg("获取失败", "获取合同登记列表失败, Err: "+e.Error(), c)
+		resp.FailMsg("获取失败", "获取登记列表失败, Err: "+e.Error(), c)
 		return
 	}
-	registerIds := make([]int, 0)
 	for i := range list {
-		registerIds = append(registerIds, list[i].ContractRegisterId)
+		list[i].UnitName = unitMap[list[i].CurrencyUnit]
 	}
 
-	serviceMap := make(map[int]string, 0)
-	invoiceMap := make(map[int][]*fms.ContractInvoiceItem, 0)
-	paymentMap := make(map[int][]*fms.ContractInvoiceItem, 0)
-	if len(registerIds) > 0 {
-		// 获取服务套餐
-		servicesNameList, e := fms.GetContractRegisterServicesNameByRegisterIds(registerIds)
-		if e != nil {
-			resp.FailMsg("获取失败", "获取套餐拼接字符串失败, Err: "+e.Error(), c)
+	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
 		}
-		for i := range servicesNameList {
-			serviceMap[servicesNameList[i].ContractRegisterId] = servicesNameList[i].ServicesName
+		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)
+	ob.CompanyName = req.CompanyName
+	ob.SellerId = req.SellerId
+	ob.SellerName = req.SellerName
+	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.NewCompany = req.NewCompany
+	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
+	}
 
-		// 获取开票/到款列表
-		invoiceCond := `contract_register_id IN ?`
-		invoicePars := make([]interface{}, 0)
-		invoicePars = append(invoicePars, registerIds)
-		invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
-		if e != nil {
-			resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
+	ob := new(fms.ContractPrePayment)
+
+	item, e := ob.Fetch(req.PrePayId)
+	if e != nil {
+		if e == utils.ErrNoRow {
+			resp.Fail("预到款登记记录不存在或已被删除", c)
 			return
 		}
-		for i := range invoiceList {
-			if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
-				invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
-			}
-			if paymentMap[invoiceList[i].ContractRegisterId] == nil {
-				paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
-			}
-			if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
-				invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
-			}
-			if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
-				paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
-			}
+		resp.FailMsg("操作失败", "获取预到款登记信息失败, Err:"+e.Error(), c)
+		return
+	}
+	item.CompanyName = req.CompanyName
+	item.SellerId = req.SellerId
+	item.SellerName = req.SellerName
+	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.NewCompany = req.NewCompany
+	item.ModifyTime = time.Now().Local()
+
+	updateCols := []string{
+		"ContractCode", "CompanyName", "SellerId", "SellerName", "Amount", "StartDate", "EndDate",
+		"Remark", "ModifyTime","NewCompany", "OriginAmount", "CurrencyUnit",
+	}
+	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
 	}
 
-	respList := make([]*fms.ContractRegisterList, 0)
-	for i := range list {
-		v := new(fms.ContractRegisterList)
-		v.ContractRegisterItem = list[i]
-		v.ServicesName = serviceMap[list[i].ContractRegisterId]
-		v.InvoiceList = invoiceMap[list[i].ContractRegisterId]
-		v.PaymentList = paymentMap[list[i].ContractRegisterId]
-		respList = append(respList, v)
+	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
 	}
 
-	page.SetTotal(total)
-	baseData := new(base.BaseData)
-	baseData.SetPage(page)
-	baseData.SetList(respList)
-	resp.OkData("获取成功", baseData, c)
+	// 操作日志
+	//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)
 }

+ 106 - 3
controller/contract/register.go

@@ -279,9 +279,112 @@ func (rg *RegisterController) Add(c *gin.Context) {
 	}
 
 	// 新增合同及套餐
-	if e = fms.CreateContractRegisterAndServices(ob, serviceList, serviceAmountList); e != nil {
-		resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
-		return
+	if req.Supplement == 1 {
+		//新增到款信息
+		if ob.HasPayment == 1 {
+			resp.Fail("合同存在代付不允许添加开票/到款登记", c)
+			return
+		}
+
+		//新增合同信息
+		if e = fms.CreateContractRegisterAndServicesAndPayMent(ob, serviceList, req.PrePayId); e != nil {
+			resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
+			return
+		}
+
+		prePayOB := new(fms.ContractPrePayment)
+		ppItem, e := prePayOB.Fetch(req.PrePayId)
+		if e != nil {
+			if e == utils.ErrNoRow {
+				resp.Fail("预到款不存在或已被删除", c)
+				return
+			}
+			resp.FailMsg("获取预到款记录失败", "Err:"+e.Error(), c)
+			return
+		}
+		// 合同有效时长(计算付款方式)
+		dayDiff := ob.EndDate.Sub(ob.StartDate).Hours() / 24
+
+		// 获取销售分组信息
+		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]
+		}
+
+		v := &fms.ContractInvoice{
+			ContractRegisterId: ob.ContractRegisterId,
+			ContractCode:       ob.ContractCode,
+			Amount:             ppItem.Amount,
+			OriginAmount:       ppItem.OriginAmount,
+			CurrencyUnit:       ppItem.CurrencyUnit,
+			InvoiceType:        fms.ContractInvoiceTypePay,
+			InvoiceDate:        ppItem.CreateTime,
+			AdminId:            int(adminInfo.AdminId),
+			AdminName:          adminInfo.RealName,
+			Remark:             ppItem.Remark,
+			IsPrePay:           1,
+		}
+		v.Set()
+		// 到款登记-付款方式
+		v.PayType = fmsService.CalculateContractPaymentType(ppItem.Amount, ob.ContractAmount, dayDiff)
+
+		// 新增的记录
+		logList := make([]*fms.ContractRegisterLog, 0)
+		opData := ""
+		opDataByte, e := json.Marshal(req)
+		if e != nil {
+			return
+		}
+		opData = string(opDataByte)
+		opType := fms.ContractInvoiceTypePrePay
+		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
+		}
+		// 校验金额-是否修改状态
+		go fmsService.CheckContractRegisterAmount(ob.ContractRegisterId)
+
+		// 开票到款汇总
+		go fmsService.SummaryInvoicePaymentByContractRegisterId(ob.ContractRegisterId)
+
+		// 操作日志
+		go func() {
+			logOB := new(fms.ContractRegisterLog)
+			if e := logOB.AddInBatches(logList); e != nil {
+				return
+			}
+		}()
+	} else {
+		if e = fms.CreateContractRegisterAndServices(ob, serviceList, serviceAmountList); e != nil {
+			resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
+			return
+		}
 	}
 
 	// 操作日志

+ 3 - 3
controller/statistic.go

@@ -47,7 +47,7 @@ func getIncomeList(ch chan models.IncomeChartResp) (incomeChart models.IncomeCha
 		ch <- incomeChart
 	}()
 	todayStr := utils.GetToday("20060102")
-	key := "admin:home:incomeList:" + todayStr
+	key := "admin:home:fmsIncomeList:" + todayStr
 
 	redisJsonData, redisErr := global.Redis.Get(context.TODO(), key).Result()
 	if redisErr != nil {
@@ -85,7 +85,7 @@ func getIncomeList(ch chan models.IncomeChartResp) (incomeChart models.IncomeCha
 				return
 			}
 			contractMoneySlice = append(contractMoneySlice, item.ContractMoney)
-			ArrivalMoneySlice = append(contractMoneySlice, item.ArrivalMoney)
+			ArrivalMoneySlice = append(ArrivalMoneySlice, item.ArrivalMoney)
 		}
 		incomeChart.Title = "开票到款统计图"
 		incomeChart.Date = dateSlice
@@ -99,7 +99,7 @@ func getIncomeList(ch chan models.IncomeChartResp) (incomeChart models.IncomeCha
 	} else {
 		err = json.Unmarshal([]byte(redisJsonData), &incomeChart)
 		if err != nil {
-			fmt.Println("近6个月的收入统计数据,json转换失败")
+			fmt.Println("近两年的收入统计数据,json转换失败")
 		}
 	}
 

+ 2 - 0
models/fms/constants.go

@@ -24,10 +24,12 @@ const (
 	ContractRegisterOpTypeStatus  = 4 // 修改合同状态
 	ContractRegisterOpTypeDel     = 5 // 删除合同登记
 	ContractRegisterOpTypeEdit    = 6 // 合规编辑
+	ContractPrePayOpTypeEdit      = 7 // 到款预登记
 
 	// 合同登记开票类型
 	ContractInvoiceTypeMake = 1 // 开票登记
 	ContractInvoiceTypePay  = 2 // 到款登记
+	ContractInvoiceTypePrePay  = 3 // 到款预登记
 
 	// 到款登记付款方式
 	ContractPaymentPayTypeYear     = 1 // 年付

+ 5 - 1
models/fms/contract_invoice.go

@@ -30,6 +30,7 @@ type ContractInvoice struct {
 	Remark             string    `gorm:"column:remark" json:"remark" description:"备注信息"`
 	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-是"`
 	base.TimeBase
 }
 
@@ -53,6 +54,7 @@ type ContractInvoiceItem struct {
 	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-是"`
 	CreateTime         string  `gorm:"column:create_time" json:"create_time" description:"创建时间"`
 }
 
@@ -146,7 +148,7 @@ func (c *ContractInvoice) DeleteAndCreateNewInvoice(contractRegisterId, invoiceT
 // ContractInvoiceSaveReq 合同开票-请求体
 type ContractInvoiceSaveReq struct {
 	ContractRegisterId int                        `json:"contract_register_id" binding:"required,gte=1" description:"登记ID"`
-	InvoiceType        int                        `json:"invoice_type" binding:"oneof=1 2" description:"类型: 1-开票登记; 2-到款登记"`
+	InvoiceType        int                        `json:"invoice_type" binding:"oneof=1 2 3" description:"类型: 1-开票登记; 2-到款登记; 3-预到款登记"`
 	AmountList         []*ContractInvoiceSaveItem `json:"amount_list"`
 }
 
@@ -193,6 +195,7 @@ func formatContractInvoice2ItemList(list []*ContractInvoice) (itemList []*Contra
 			SellerName:         list[i].SellerName,
 			PayType:            list[i].PayType,
 			Remark:             list[i].Remark,
+			IsPrePay:           list[i].IsPrePay,
 			CreateTime:         utils.TimeTransferString(utils.FormatDateTime, list[i].CreateTime),
 			ServiceProductId:   list[i].ServiceProductId,
 		})
@@ -248,6 +251,7 @@ func formatContractInvoice2Item(item *ContractInvoice) (formatItem *ContractInvo
 	formatItem.SellerName = item.SellerName
 	formatItem.PayType = item.PayType
 	formatItem.Remark = item.Remark
+	formatItem.IsPrePay = item.IsPrePay
 	formatItem.CreateTime = utils.TimeTransferString(utils.FormatDateTime, item.CreateTime)
 	return
 }

+ 119 - 119
models/fms/contract_pre_payment.go

@@ -1,149 +1,149 @@
 package fms
 
 import (
+	"hongze/fms_api/global"
 	"hongze/fms_api/models/base"
+	"hongze/fms_api/utils"
 	"time"
 )
 
 // ContractInvoice 合同开票表
 type ContractPrePayment struct {
-	ContractInvoiceId  int       `gorm:"primaryKey;column:contract_invoice_id" json:"contract_invoice_id" description:"开票ID"`
+	PrePayId           int       `gorm:"primaryKey;column:pre_pay_id" json:"pre_pay_id" description:"预付款ID"`
+	CompanyName        string    `json:"company_name" description:"客户名称"`
 	ContractRegisterId int       `gorm:"column:contract_register_id" json:"contract_register_id" description:"登记ID"`
 	ContractCode       string    `gorm:"column:contract_code" json:"contract_code" description:"合同编号"`
 	Amount             float64   `gorm:"column:amount" json:"amount" description:"换算后的金额(人民币)"`
-	OriginAmount       float64   `gorm:"column:origin_amount" json:"origin_amount" description:"开票/到款金额"`
+	OriginAmount       float64   `gorm:"column:origin_amount" json:"origin_amount" description:"到款金额"`
 	CurrencyUnit       string    `gorm:"column:currency_unit" json:"currency_unit" description:"货币国际代码"`
-	InvoiceType        int       `gorm:"column:invoice_type" json:"invoice_type" description:"类型: 1-开票登记; 2-到款登记"`
-	InvoiceDate        time.Time `gorm:"column:invoice_time" json:"invoice_time" description:"开票日期/到款月"`
 	SellerId           int       `gorm:"column:seller_id" json:"seller_id" description:"销售ID"`
 	SellerName         string    `gorm:"column:seller_name" json:"seller_name" description:"销售名称"`
-	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:"销售小组名称"`
-	PayType            int       `gorm:"column:pay_type" json:"pay_type" description:"付款方式:0-无;1-年付;2-半年付;3-季付;4-次付;5-异常"`
 	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:"备注信息"`
-	IsDeleted          int       `gorm:"column:is_deleted" json:"is_deleted" 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:"约定结束时间"`
+	NewCompany         int       `gorm:"column:new_company" json:"new_company" description:"是否为新客户: 0-否; 1-是"`
 	base.TimeBase
 }
 
+type ContractPrePaymentRespItem struct {
+	PrePayId           int     `gorm:"primaryKey;column:pre_pay_id" json:"pre_pay_id" description:"预付款ID"`
+	CompanyName        string  `json:"company_name" description:"客户名称"`
+	ContractRegisterId int     `gorm:"column:contract_register_id" json:"contract_register_id" description:"登记ID"`
+	ContractCode       string  `gorm:"column:contract_code" json:"contract_code" 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:"货币国际代码"`
+	UnitName           string  `gorm:"unit_name" json:"unit_name" description:"单位名称"`
+	SellerId           int     `gorm:"column:seller_id" json:"seller_id" description:"销售ID"`
+	SellerName         string  `gorm:"column:seller_name" json:"seller_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:"备注信息"`
+	StartDate          string  `gorm:"column:start_date" json:"start_date" description:"约定开始时间"`
+	EndDate            string  `gorm:"column:end_date" json:"end_date" description:"约定结束时间"`
+	NewCompany         int     `gorm:"column:new_company" json:"new_company" description:"是否为新客户: 0-否; 1-是"`
+	CreateTime         string  `gorm:"autoCreateTime;column:create_time" json:"create_time" description:"创建时间"`
+	ModifyTime         string  `gorm:"autoUpdateTime:milli;column:modify_time" json:"modify_time" description:"最后更新时间"`
+}
+
 func (c *ContractPrePayment) TableName() string {
 	return "contract_pre_payment"
 }
 
-//// ContractInvoiceItem 合同开票/到款
-//type ContractInvoiceItem 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:"合同编号"`
-//	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:"货币国际代码"`
-//	UnitName           string  `json:"unit_name" description:"货币单位名称"`
-//	InvoiceType        int     `gorm:"column:invoice_type" json:"invoice_type" description:"类型: 1-开票登记; 2-到款登记"`
-//	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:"销售名称"`
-//	PayType            int     `gorm:"column:pay_type" json:"pay_type" description:"付款方式:0-无;1-年付;2-半年付;3-季付;4-次付;5-异常"`
-//	Remark             string  `gorm:"column:remark" json:"remark" description:"备注信息"`
-//	CreateTime         string  `gorm:"column:create_time" json:"create_time" description:"创建时间"`
-//}
-//
-//func (c *ContractInvoice) Create() (err error) {
-//	err = global.DEFAULT_MYSQL.Create(c).Error
-//	return
-//}
-//
-//func (c *ContractInvoice) AddInBatches(list []*ContractInvoice) (err error) {
-//	err = global.DEFAULT_MYSQL.CreateInBatches(list, len(list)).Error
-//	return
-//}
-//
-//func (c *ContractInvoice) Update(updateCols []string) (err error) {
-//	err = global.DEFAULT_MYSQL.Model(c).Select(updateCols).Updates(c).Error
-//	return
-//}
-//
-//func (c *ContractInvoice) Fetch(id int) (item *ContractInvoice, err error) {
-//	err = global.DEFAULT_MYSQL.Model(c).Where("is_deleted = 0 AND contract_invoice_id = ?", id).First(&item).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).
-//		Where("is_deleted = 0").
-//		Where(condition, pars...).
-//		Pluck(field, &totalList).Error
-//	for i := range totalList {
-//		total += totalList[i]
-//	}
-//	return
-//}
-//
-//func (c *ContractInvoice) List(condition string, pars []interface{}, orderRule string) (list []*ContractInvoice, err error) {
-//	list = make([]*ContractInvoice, 0)
-//	query := global.DEFAULT_MYSQL.Model(c).
-//		Where("is_deleted = 0").
-//		Where(condition, pars...)
-//	if orderRule != "" {
-//		query.Order(orderRule)
-//	} else {
-//		query.Order("contract_invoice_id ASC")
-//	}
-//	err = query.Find(&list).Error
-//	return
-//}
-//
-//func (c *ContractInvoice) PageList(page base.IPage, condition string, pars []interface{}) (count int64, results []*ContractInvoice, err error) {
-//	results = make([]*ContractInvoice, 0)
-//	query := global.DEFAULT_MYSQL.Model(c).
-//		Where("is_deleted = 0").
-//		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(&results).Error
-//	return
-//}
-//
-//// DeleteAndCreateNewInvoice 删除并新增登记
-//func (c *ContractInvoice) DeleteAndCreateNewInvoice(contractRegisterId, invoiceType int, deleteInvoiceIds []int, invoices []*ContractInvoice) (err error) {
-//	tx := global.DEFAULT_MYSQL.Begin()
-//	defer func() {
-//		if err != nil {
-//			tx.Rollback()
-//		} else {
-//			tx.Commit()
-//		}
-//	}()
-//
-//	if len(deleteInvoiceIds) > 0 {
-//		err = tx.Model(c).
-//			Where("contract_register_id = ? AND invoice_type = ? AND contract_invoice_id IN (?)", contractRegisterId, invoiceType, deleteInvoiceIds).
-//			UpdateColumn("is_deleted", 1).Error
-//		if err != nil {
-//			return
-//		}
-//	}
-//	if len(invoices) > 0 {
-//		err = tx.CreateInBatches(invoices, len(invoices)).Error
-//		if err != nil {
-//			return
-//		}
-//	}
-//	return
-//}
-
-
 // ContractRegisterListReq 合同登记列表请求体
 type PrePayListReq struct {
-	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:"合同结束日期"`
+	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:"约定结束时间"`
+	SortType  int    `json:"sort_type" form:"sort_type" description:"排序方式: 1-正序; 2-倒序"`
 	base.PageReq
 }
 
+// GetPrePayItemPageList 获取预登记列表-分页
+func GetPrePayItemPageList(page base.IPage, condition string, pars []interface{}) (count int64, results []*ContractPrePaymentRespItem, err error) {
+	list := make([]*ContractPrePayment, 0)
+	query := global.DEFAULT_MYSQL.Table("contract_pre_payment").
+		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, formatPrePay2Item(list[i]))
+	}
+	return
+}
+
+// formatPrePay2Item 格式化PrePay
+func formatPrePay2Item(item *ContractPrePayment) (formatItem *ContractPrePaymentRespItem) {
+	formatItem = new(ContractPrePaymentRespItem)
+	formatItem.PrePayId = item.PrePayId
+	formatItem.ContractRegisterId = item.ContractRegisterId
+	formatItem.ContractCode = item.ContractCode
+	formatItem.CompanyName = item.CompanyName
+	formatItem.SellerId = item.SellerId
+	formatItem.SellerName = item.SellerName
+	formatItem.Amount = item.Amount
+	formatItem.OriginAmount = item.OriginAmount
+	formatItem.CurrencyUnit = item.CurrencyUnit
+	formatItem.StartDate = utils.TimeTransferString(utils.FormatDate, item.StartDate)
+	formatItem.EndDate = utils.TimeTransferString(utils.FormatDate, item.EndDate)
+	formatItem.AdminId = item.AdminId
+	formatItem.AdminName = item.AdminName
+	formatItem.Remark = item.Remark
+	formatItem.NewCompany = item.NewCompany
+	formatItem.CreateTime = utils.TimeTransferString(utils.FormatDateTime, item.CreateTime)
+	formatItem.ModifyTime = utils.TimeTransferString(utils.FormatDateTime, item.ModifyTime)
+	return
+}
+
+// PrepayAddReq 新增到款预登记请求体
+type PrepayAddReq struct {
+	CompanyName  string  `json:"company_name" binding:"required" description:"客户名称"`
+	SellerId     int     `json:"seller_id" binding:"required" description:"CRM系统-销售ID"`
+	SellerName   string  `json:"seller_name" binding:"required" description:"CRM系统-销售名称"`
+	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:"备注信息"`
+	NewCompany   int     `json:"new_company" description:"是否为新客户: 0-否; 1-是"`
+}
+
+func (c *ContractPrePayment) Create() (err error) {
+	err = global.DEFAULT_MYSQL.Create(c).Error
+	return
+}
+
+func (c *ContractPrePayment) Fetch(id int) (item *ContractPrePayment, err error) {
+	err = global.DEFAULT_MYSQL.Model(c).Where(" pre_pay_id = ?", id).First(&item).Error
+	return
+}
+
+func (c *ContractPrePayment) Update(updateCols []string) (err error) {
+	err = global.DEFAULT_MYSQL.Model(c).Select(updateCols).Updates(c).Error
+	return
+}
+
+// 删除
+func (c *ContractPrePayment) Delete() (err error) {
+	err = global.DEFAULT_MYSQL.Delete(c).Error
+	return
+}
+
+// PrepayEditReq 编辑到款预登记请求体
+type PrepayEditReq struct {
+	PrePayId int `json:"pre_pay_id" binding:"required,gte=1" description:"预付款ID"`
+	PrepayAddReq
+}
+
+// PrepayDelReq 删除到款预登记
+type PrepayDelReq struct {
+	PrePayId int `json:"pre_pay_id" binding:"required,gte=1" description:"预付款ID"`
+}

+ 52 - 3
models/fms/contract_register.go

@@ -166,8 +166,8 @@ type ContractRegisterAddReq struct {
 	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:"实际使用方"`
-	SellerId           int                           `json:"seller_id" description:"CRM系统-销售ID"`
-	SellerName         string                        `json:"seller_name" description:"CRM系统-销售名称"`
+	SellerId           int                           `json:"seller_id" binding:"required" description:"CRM系统-销售ID"`
+	SellerName         string                        `json:"seller_name" binding:"required" description:"CRM系统-销售名称"`
 	RaiSellerId        int                           `json:"rai_seller_id" description:"CRM系统-权益销售ID"`
 	RaiSellerName      string                        `json:"rai_seller_name" description:"CRM系统-权益销售名称"`
 	ContractType       int                           `json:"contract_type" binding:"oneof=1 2 3 4" description:"合同类型: 1-新签; 2-续约; 3-代付; 4-补充协议"`
@@ -179,10 +179,12 @@ type ContractRegisterAddReq struct {
 	AgreedPayTime      string                        `json:"agreed_pay_time" description:"约定付款时间(如:生效日起10日内)"`
 	ContractStatus     int                           `json:"contract_status" binding:"oneof=1 2 3 4" description:"合同状态: 1-已审批; 2-单章寄出; 3-已签回; 4-已终止"`
 	Remark             string                        `json:"remark" description:"备注信息"`
-	ServiceRemark      string                        `json:"service_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:"服务套餐金额"`
 }
@@ -484,3 +486,50 @@ func CreateImportContractRegister(item *ContractRegister, serviceList []*Contrac
 	}
 	return
 }
+
+// CreateContractRegisterAndServices 新增合同登记及套餐
+func CreateContractRegisterAndServicesAndPayMent(item *ContractRegister, serviceDetail []*ContractServiceAndDetail, prePayId int) (err error) {
+	tx := global.DEFAULT_MYSQL.Begin()
+	defer func() {
+		if err != nil {
+			tx.Rollback()
+		} else {
+			tx.Commit()
+		}
+	}()
+
+	// 合同登记
+	tx.Create(item)
+
+	//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
+}

+ 4 - 0
models/fms/invoice_payment_summary.go

@@ -22,6 +22,10 @@ func (c *InvoicePaymentSummary) TableName() string {
 	return "invoice_payment_summary"
 }
 
+func (c *InvoicePaymentSummary) Create() (err error) {
+	err = global.DEFAULT_MYSQL.Create(c).Error
+	return
+}
 // DeleteAndCreate 删除并新增汇总
 func (c *InvoicePaymentSummary) DeleteAndCreate(registerId int, summaryList []*InvoicePaymentSummary) (err error) {
 	tx := global.DEFAULT_MYSQL.Begin()

+ 4 - 1
routers/contract.go

@@ -37,6 +37,9 @@ func InitContract(rg *gin.RouterGroup) {
 
 	//到款预登记
 	prepay := new(contract.PrePaymentController)
-	prepayGroup := rg.Group("pre_payment/").Use(middleware.Token())
+	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)
 }