소스 검색

新商品到款统计列表

hsun 2 년 전
부모
커밋
ba35197535

+ 358 - 15
controller/census/invoice_payment.go

@@ -15,27 +15,15 @@ import (
 	"net/http"
 	"strconv"
 	"strings"
+	"sync"
 	"time"
 )
 
 // InvoicePaymentController 商品到款统计
 type InvoicePaymentController struct{}
 
-// List
-// @Title 商品到款统计列表
-// @Description 商品到款统计列表
-// @Param   Keyword			query	string	false	"关键词"
-// @Param   SellGroupId		query	int		false	"销售组别ID"
-// @Param   ServiceType		query	int		false	"套餐类型"
-// @Param   StartDate		query	string	false	"合同开始日期"
-// @Param   EndDate			query	string	false	"合同结束日期"
-// @Param   TimeType		query	int		false	"时间类型: 1-开票时间; 2-到款时间"
-// @Param   HasInvoice		query	int		false	"是否已开票: 0-否; 1-是"
-// @Param   HasPayment		query	int		false	"是否已到款: 0-否; 1-是"
-// @Param   IsExport		query	int		false	"是否导出: 0-否; 1-是"
-// @Success 200 {object} fms.ContractRegisterItem
-// @router /census/invoice_payment/list [get]
-func (ct *InvoicePaymentController) List(c *gin.Context) {
+// List2 原版(已废弃)
+func (ct *InvoicePaymentController) List2(c *gin.Context) {
 	var req fms.InvoicePaymentCensusListReq
 	if e := c.BindQuery(&req); e != nil {
 		err, ok := e.(validator.ValidationErrors)
@@ -433,3 +421,358 @@ func ExportInvoicePaymentCensusList(c *gin.Context, results *fms.InvoicePaymentC
 	c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
 	http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
 }
+
+// List
+// @Title 商品到款统计列表
+// @Description 商品到款统计列表
+// @Param   Keyword			query	string	false	"关键词"
+// @Param   SellGroupId		query	int		false	"销售组别ID"
+// @Param   ServiceType		query	int		false	"套餐类型"
+// @Param   StartDate		query	string	false	"合同开始日期"
+// @Param   EndDate			query	string	false	"合同结束日期"
+// @Param   TimeType		query	int		false	"时间类型: 1-开票时间; 2-到款时间"
+// @Param   HasInvoice		query	int		false	"是否已开票: 0-否; 1-是"
+// @Param   HasPayment		query	int		false	"是否已到款: 0-否; 1-是"
+// @Param   IsExport		query	int		false	"是否导出: 0-否; 1-是"
+// @Success 200 {object} fms.ContractRegisterItem
+// @router /census/invoice_payment/list [get]
+func (ct *InvoicePaymentController) List(c *gin.Context) {
+	var req fms.InvoicePaymentCensusListReq
+	if e := c.BindQuery(&req); e != nil {
+		err, ok := e.(validator.ValidationErrors)
+		if !ok {
+			resp.FailData("参数解析失败", "Err:"+e.Error(), c)
+			return
+		}
+		resp.FailData("参数解析失败", err.Translate(global.Trans), c)
+		return
+	}
+
+	cond := `1 = 1`
+	pars := make([]interface{}, 0)
+	// 客户姓名/销售
+	if req.Keyword != "" {
+		kw := "%" + req.Keyword + "%"
+		cond += ` AND b.company_name LIKE ? OR c.seller_name LIKE ?`
+		pars = append(pars, kw, kw)
+	}
+	if req.SellGroupId > 0 {
+		cond += ` AND a.seller_group_id = ?`
+		pars = append(pars, req.SellGroupId)
+	}
+	// 套餐筛选
+	if req.ServiceType != 0 {
+		tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
+		if e != nil {
+			resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
+			return
+		}
+		if len(tempRegisterIds) > 0 {
+			cond += ` AND a.register_id IN ?`
+			pars = append(pars, tempRegisterIds)
+		} else {
+			cond += ` AND 1 = 2`
+		}
+	}
+	// 开票到款日期
+	if req.TimeType > 0 && req.StartDate != "" && req.EndDate != "" {
+		st := fmt.Sprint(req.StartDate, " 00:00:00")
+		ed := fmt.Sprint(req.EndDate, " 23:59:59")
+		if req.TimeType == 1 {
+			cond += ` AND (c.invoice_time BETWEEN ? AND ?)`
+		}
+		if req.TimeType == 2 {
+			cond += ` AND (d.invoice_time BETWEEN ? AND ?)`
+		}
+		pars = append(pars, req.TimeType, st, ed)
+	}
+	// 已开票
+	if req.HasInvoice == 1 {
+		cond += ` AND a.invoice_id > 0`
+	}
+	// 已到款
+	if req.HasPayment == 1 {
+		cond += ` AND a.payment_id > 0`
+	}
+
+	page := new(base.Page)
+	page.SetPageSize(req.PageSize)
+	page.SetCurrent(req.Current)
+	page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
+	if req.IsExport == 1 {
+		page.SetPageSize(10000)
+		page.SetCurrent(1)
+	}
+
+	registerList, registerIds, e := fms.GetInvoicePaymentCensusPageList(page, cond, pars)
+	if e != nil {
+		resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
+		return
+	}
+	total := int64(len(registerIds))
+	queryRegisterIds := make([]int, 0)
+	for i := range registerList {
+		queryRegisterIds = append(queryRegisterIds, registerList[i].ContractRegisterId)
+	}
+
+	results := new(fms.InvoicePaymentCensusResp)
+	if len(queryRegisterIds) > 0 {
+		// 获取汇总数据
+		summaryCond := `a.register_id IN ?`
+		summaryPars := make([]interface{}, 0)
+		summaryPars = append(summaryPars, queryRegisterIds)
+		summaryList, e := fms.GetInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
+		if e != nil {
+			resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
+			return
+		}
+		summaryIds := make([]int, 0)
+		paymentIds := make([]int, 0)
+		for i := range summaryList {
+			summaryIds = append(summaryIds, summaryList[i].SummaryId)
+			if summaryList[i].PaymentId > 0 {
+				paymentIds = append(paymentIds, summaryList[i].PaymentId)
+			}
+		}
+
+		var listErr, totalErr, totalGroupErr error
+		wg := sync.WaitGroup{}
+
+		// 响应列表
+		respList := make([]*fms.InvoicePaymentCensusItem, 0)
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+
+			// 合同套餐
+			contractServiceCond := `contract_register_id IN ?`
+			contractServicePars := make([]interface{}, 0)
+			contractServicePars = append(contractServicePars, queryRegisterIds)
+			contractServiceOB := new(fms.ContractService)
+			contractServiceList, e := contractServiceOB.List(contractServiceCond, contractServicePars)
+			if e != nil {
+				listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
+				return
+			}
+			contractServiceMap := make(map[int][]*fms.ContractService, 0)
+			servicesNameMap := make(map[int][]string, 0)
+			for i := range contractServiceList {
+				if contractServiceMap[contractServiceList[i].ContractRegisterId] == nil {
+					contractServiceMap[contractServiceList[i].ContractRegisterId] = make([]*fms.ContractService, 0)
+				}
+				contractServiceMap[contractServiceList[i].ContractRegisterId] = append(contractServiceMap[contractServiceList[i].ContractRegisterId], contractServiceList[i])
+				servicesNameMap[contractServiceList[i].ContractRegisterId] = append(servicesNameMap[contractServiceList[i].ContractRegisterId], contractServiceList[i].Title)
+			}
+
+			// 到款套餐分配
+			serviceAmountMap := make(map[int][]*fms.ContractPaymentServiceAmount, 0)
+			if len(paymentIds) > 0 {
+				serviceAmountCond := `contract_payment_id IN ?`
+				serviceAmountPars := make([]interface{}, 0)
+				serviceAmountPars = append(serviceAmountPars, paymentIds)
+				serviceAmountOB := new(fms.ContractPaymentServiceAmount)
+				serviceAmountList, e := serviceAmountOB.List(serviceAmountCond, serviceAmountPars)
+				if e != nil {
+					listErr = fmt.Errorf("获取到款套餐分配列表失败, Err: %s", e.Error())
+					return
+				}
+				for i := range serviceAmountList {
+					if serviceAmountMap[serviceAmountList[i].ContractPaymentId] == nil {
+						serviceAmountMap[serviceAmountList[i].ContractPaymentId] = make([]*fms.ContractPaymentServiceAmount, 0)
+					}
+					serviceAmountMap[serviceAmountList[i].ContractPaymentId] = append(serviceAmountMap[serviceAmountList[i].ContractPaymentId], serviceAmountList[i])
+				}
+			}
+
+			// 重组汇总数据
+			summaryMap := make(map[int][]*fms.InvoicePaymentCensusInfo)
+			amountMap := make(map[string]*fms.ContractPaymentServiceAmount)
+			for i := range summaryList {
+				if summaryMap[summaryList[i].RegisterId] == nil {
+					summaryMap[summaryList[i].RegisterId] = make([]*fms.InvoicePaymentCensusInfo, 0)
+				}
+				v := new(fms.InvoicePaymentCensusInfo)
+				v.InvoiceId = summaryList[i].InvoiceId
+				v.InvoiceDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].InvoiceDate)
+				v.InvoiceAmount = summaryList[i].InvoiceAmount
+				v.SellerId = summaryList[i].SellerId
+				v.SellerName = summaryList[i].SellerName
+				v.SellerGroupId = summaryList[i].SellerGroupId
+				v.SellerGroupName = summaryList[i].SellerGroupName
+				v.PaymentId = summaryList[i].PaymentId
+				v.PaymentDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].PaymentDate)
+				v.PaymentAmount = summaryList[i].PaymentAmount
+				v.PayType = summaryList[i].PayType
+				// 套餐到款分配
+				svaList := make([]*fms.ContractPaymentServiceAmountItem, 0)
+				amountList := serviceAmountMap[summaryList[i].PaymentId]
+				if amountList != nil {
+					for i := range amountList {
+						k := fmt.Sprintf("%d-%d", amountList[i].ContractPaymentId, amountList[i].ServiceTemplateId)
+						amountMap[k] = amountList[i]
+					}
+				}
+				// 合同对应的所有套餐
+				svList := contractServiceMap[summaryList[i].RegisterId]
+				if svList != nil {
+					for ii := range svList {
+						vv := new(fms.ContractPaymentServiceAmountItem)
+						vv.ServiceTemplateId = svList[ii].ServiceTemplateId
+						vv.ServiceTemplateName = svList[ii].Title
+						k2 := fmt.Sprintf("%d-%d", summaryList[i].PaymentId, svList[ii].ServiceTemplateId)
+						a := amountMap[k2]
+						if a != nil {
+							vv.ContractPaymentServiceAmountId = a.ContractPaymentServiceAmountId
+							vv.ContractPaymentId = a.ContractPaymentId
+							vv.Amount = a.Amount
+						}
+						svaList = append(svaList, vv)
+					}
+				}
+				v.ServiceAmountList = svaList
+
+				summaryMap[summaryList[i].RegisterId] = append(summaryMap[summaryList[i].RegisterId], v)
+			}
+
+			// 响应列表
+			for i := range registerList {
+				v := new(fms.InvoicePaymentCensusItem)
+				v.ContractRegisterId = registerList[i].ContractRegisterId
+				v.CompanyName = registerList[i].CompanyName
+				v.NewCompany = registerList[i].NewCompany
+				v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
+				v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
+				svList := servicesNameMap[registerList[i].ContractRegisterId]
+				v.ServicesName = strings.Join(svList, ",")
+				v.InvoicePaymentList = summaryMap[registerList[i].ContractRegisterId]
+				respList = append(respList, v)
+			}
+		}()
+
+		// 开票到款金额合计(换算后)
+		var invoiceTotal, paymentTotal float64
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+
+			if len(summaryIds) == 0 {
+				return
+			}
+			amountTotalCond := `a.id IN ?`
+			amountTotalPars := make([]interface{}, 0)
+			amountTotalPars = append(amountTotalPars, summaryIds)
+			invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
+			if e != nil {
+				totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
+				return
+			}
+			invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
+			paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
+			if e != nil {
+				totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
+				return
+			}
+			paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
+		}()
+
+		// 分币种金额统计
+		invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
+		paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+
+			currencyOB := new(fms.CurrencyUnit)
+			currencyCond := `enable = 1`
+			currencyPars := make([]interface{}, 0)
+			currencyList, e := currencyOB.List(currencyCond, currencyPars)
+			if e != nil {
+				totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
+				return
+			}
+			unitMap := make(map[string]string)
+			for i := range currencyList {
+				unitMap[currencyList[i].Code] = currencyList[i].UnitName
+				invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
+					Name:     currencyList[i].Name,
+					UnitName: currencyList[i].UnitName,
+					Code:     currencyList[i].Code,
+					FlagImg:  currencyList[i].FlagImg,
+				})
+				paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
+					Name:     currencyList[i].Name,
+					UnitName: currencyList[i].UnitName,
+					Code:     currencyList[i].Code,
+					FlagImg:  currencyList[i].FlagImg,
+				})
+			}
+
+			if len(summaryIds) == 0 {
+				return
+			}
+			totalGroupCond := `a.id IN ?`
+			totalGroupPars := make([]interface{}, 0)
+			totalGroupPars = append(totalGroupPars, summaryIds)
+			invoiceSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 1)
+			if e != nil {
+				totalGroupErr = fmt.Errorf("获取汇总货币合计开票金额失败, Err: %s", e.Error())
+				return
+			}
+			paymentSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 2)
+			if e != nil {
+				totalGroupErr = fmt.Errorf("获取汇总货币合计到款金额失败, Err: %s", e.Error())
+				return
+			}
+			invoiceSumMap := make(map[string]float64)
+			paymentSumMap := make(map[string]float64)
+			for i := range invoiceSumGroup {
+				invoiceSumMap[invoiceSumGroup[i].CurrencyUnit] = invoiceSumGroup[i].OriginAmountTotal
+				continue
+			}
+			for i := range paymentSumGroup {
+				paymentSumMap[paymentSumGroup[i].CurrencyUnit] = paymentSumGroup[i].OriginAmountTotal
+				continue
+			}
+			for i := range invoiceCurrencyTotals {
+				a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
+				invoiceCurrencyTotals[i].Amount = a
+			}
+			for i := range paymentCurrencyTotals {
+				a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
+				paymentCurrencyTotals[i].Amount = a
+			}
+		}()
+
+		wg.Wait()
+
+		if listErr != nil {
+			resp.FailMsg("获取失败", listErr.Error(), c)
+			return
+		}
+		if totalErr != nil {
+			resp.FailMsg("获取失败", totalErr.Error(), c)
+			return
+		}
+		if totalGroupErr != nil {
+			resp.FailMsg("获取失败", totalGroupErr.Error(), c)
+			return
+		}
+
+		results.DataList = respList
+		results.InvoiceTotal = invoiceTotal
+		results.PaymentTotal = paymentTotal
+		results.InvoiceCurrencyTotal = invoiceCurrencyTotals
+		results.PaymentCurrencyTotal = paymentCurrencyTotals
+	}
+
+	// 是否导出
+	if req.IsExport == 1 {
+		ExportInvoicePaymentCensusList(c, results)
+		return
+	}
+	page.SetTotal(total)
+	baseData := new(base.BaseData)
+	baseData.SetPage(page)
+	baseData.SetList(results)
+	resp.OkData("获取成功", baseData, c)
+}

+ 4 - 0
controller/contract/register.go

@@ -886,6 +886,9 @@ func (rg *RegisterController) Invoice(c *gin.Context) {
 	// 校验金额-是否修改状态
 	go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
 
+	// 开票到款汇总
+	go fmsService.SummaryInvoicePaymentByContractRegisterId(req.ContractRegisterId)
+
 	// 操作日志
 	go func() {
 		logOB := new(fms.ContractRegisterLog)
@@ -1638,6 +1641,7 @@ func (rg *RegisterController) Import(c *gin.Context) {
 			go func() {
 				for i := range newIds {
 					fmsService.CheckContractRegisterAmount(newIds[i])
+					fmsService.SummaryInvoicePaymentByContractRegisterId(newIds[i])
 				}
 			}()
 		}

+ 1 - 0
init_serve/task.go

@@ -9,5 +9,6 @@ func InitTask() {
 	fmt.Println("task start")
 	//fmsService.FixContractInvoiceSellerInfo()
 	//fmsService.FixContractInvoicePaymentType()
+	//fmsService.FixContractSummaryData()
 	fmt.Println("task end")
 }

+ 2 - 2
models/fms/contract_invoice.go

@@ -268,8 +268,8 @@ type InvoicePaymentCensusListReq struct {
 	base.PageReq
 }
 
-// GetInvoicePaymentCensusPageList 获取商品到款统计列表-分页
-func GetInvoicePaymentCensusPageList(page base.IPage, condition string, pars []interface{}) (results []*ContractRegister, registerIds []int, err error) {
+// GetInvoicePaymentCensusPageListV2 获取商品到款统计列表-分页
+func GetInvoicePaymentCensusPageListV2(page base.IPage, condition string, pars []interface{}) (results []*ContractRegister, registerIds []int, err error) {
 	query := global.DEFAULT_MYSQL.Table("contract_invoice AS a").
 		Select("b.*").
 		Joins("JOIN contract_register AS b ON a.contract_register_id = b.contract_register_id").

+ 136 - 0
models/fms/invoice_payment_summary.go

@@ -0,0 +1,136 @@
+package fms
+
+import (
+	"fmt"
+	"hongze/fms_api/global"
+	"hongze/fms_api/models/base"
+	"strings"
+	"time"
+)
+
+// InvoicePaymentSummary 开票到款汇总表
+type InvoicePaymentSummary struct {
+	Id         int `gorm:"primaryKey;column:id" json:"id" description:"汇总ID"`
+	RegisterId int `gorm:"column:register_id" json:"register_id" description:"登记ID"`
+	InvoiceId  int `gorm:"column:invoice_id" json:"invoice_id" description:"开票ID"`
+	PaymentId  int `gorm:"column:payment_id" json:"payment_id" description:"到款ID"`
+	base.TimeBase
+}
+
+func (c *InvoicePaymentSummary) TableName() string {
+	return "invoice_payment_summary"
+}
+
+// DeleteAndCreate 删除并新增汇总
+func (c *InvoicePaymentSummary) DeleteAndCreate(registerId int, summaryList []*InvoicePaymentSummary) (err error) {
+	tx := global.DEFAULT_MYSQL.Begin()
+	defer func() {
+		if err != nil {
+			tx.Rollback()
+		} else {
+			tx.Commit()
+		}
+	}()
+
+	sql := `DELETE FROM invoice_payment_summary WHERE register_id = ?`
+	tx.Exec(sql, registerId)
+	if len(summaryList) > 0 {
+		err = tx.CreateInBatches(summaryList, len(summaryList)).Error
+		if err != nil {
+			return
+		}
+	}
+	return
+}
+
+// GetInvoicePaymentCensusPageList 获取商品到款统计列表-总数
+func GetInvoicePaymentCensusPageList(page base.IPage, condition string, pars []interface{}) (results []*ContractRegister, registerIds []int, err error) {
+	query := global.DEFAULT_MYSQL.Table("invoice_payment_summary AS a").
+		Select("b.*").
+		Joins("JOIN contract_register AS b ON a.register_id = b.contract_register_id AND b.is_deleted = 0").
+		Joins("LEFT JOIN contract_invoice AS c ON a.invoice_id = c.contract_invoice_id AND c.is_deleted = 0").
+		Joins("LEFT JOIN contract_invoice AS d ON a.payment_id = d.contract_invoice_id AND d.is_deleted = 0").
+		Where(condition, pars...).
+		Group("a.register_id")
+	if len(page.GetOrderItemsString()) > 0 {
+		query = query.Order(page.GetOrderItemsString())
+	}
+	err = query.Limit(int(page.GetPageSize())).Offset(int(page.Offset())).Find(&results).Error
+	if err != nil {
+		return
+	}
+	queryCount := global.DEFAULT_MYSQL.Table("invoice_payment_summary AS a").
+		Select("a.register_id").
+		Joins("JOIN contract_register AS b ON a.register_id = b.contract_register_id AND b.is_deleted = 0").
+		Joins("LEFT JOIN contract_invoice AS c ON a.invoice_id = c.contract_invoice_id AND c.is_deleted = 0").
+		Joins("LEFT JOIN contract_invoice AS d ON a.payment_id = d.contract_invoice_id AND d.is_deleted = 0").
+		Where(condition, pars...).
+		Group("a.register_id")
+	queryCount.Find(&registerIds)
+	return
+}
+
+type InvoicePaymentSummaryItem struct {
+	SummaryId       int       `json:"summary_id" description:"汇总ID"`
+	RegisterId      int       `json:"register_id" description:"登记ID"`
+	CompanyName     string    `json:"company_name" description:"客户名称"`
+	NewCompany      int       `json:"new_company" description:"是否为新客户: 0-否; 1-是"`
+	StartDate       time.Time `json:"start_date" description:"合同开始日期"`
+	EndDate         time.Time `json:"end_date" description:"合同结束日期"`
+	InvoiceId       int       `json:"invoice_id" description:"开票ID"`
+	InvoiceDate     time.Time `json:"invoice_time" description:"开票日期"`
+	InvoiceAmount   float64   `json:"invoice_amount" description:"开票金额"`
+	SellerId        int       `json:"seller_id" description:"销售ID"`
+	SellerName      string    `json:"seller_name" description:"销售名称"`
+	SellerGroupId   int       `json:"seller_group_id" description:"销售组别ID"`
+	SellerGroupName string    `json:"seller_group_name" description:"销售组别名称"`
+	PaymentId       int       `json:"payment_id" description:"到款ID"`
+	PaymentDate     time.Time `json:"payment_date" description:"到款日期"`
+	PaymentAmount   float64   `json:"payment_amount" description:"到款金额"`
+	PayType         int       `json:"pay_type" description:"付款方式:0-无;1-年付;2-半年付;3-季付;4-次付;5-异常"`
+}
+
+// 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", "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",
+	}
+	query := global.DEFAULT_MYSQL.Table("invoice_payment_summary AS a").
+		Select(strings.Join(fields, ",")).
+		Joins("JOIN contract_register AS b ON a.register_id = b.contract_register_id AND b.is_deleted = 0").
+		Joins("LEFT JOIN contract_invoice AS c ON a.invoice_id = c.contract_invoice_id AND c.is_deleted = 0").
+		Joins("LEFT JOIN contract_invoice AS d ON a.payment_id = d.contract_invoice_id AND d.is_deleted = 0").
+		Where(condition, pars...)
+	query.Find(&results)
+	return
+}
+
+// GetContractSummaryInvoicePaymentAmountTotal 获取汇总金额合计信息
+func GetContractSummaryInvoicePaymentAmountTotal(condition string, pars []interface{}, amountType int) (amountTotal float64, err error) {
+	joinCond := `a.invoice_id = b.contract_invoice_id`
+	if amountType == 2 {
+		joinCond = `a.payment_id = b.contract_invoice_id`
+	}
+	query := global.DEFAULT_MYSQL.Table("invoice_payment_summary AS a").
+		Select("SUM(b.amount)").
+		Joins(fmt.Sprintf("JOIN contract_invoice AS b ON %s AND b.is_deleted = 0", joinCond)).
+		Where(condition, pars...)
+	err = query.Find(&amountTotal).Error
+	return
+}
+
+// GetSummaryListCurrencySum 获取汇总分货币合计
+func GetSummaryListCurrencySum(condition string, pars []interface{}, amountType int) (results []*InvoiceListCurrencySum, err error) {
+	joinCond := `a.invoice_id = b.contract_invoice_id`
+	if amountType == 2 {
+		joinCond = `a.payment_id = b.contract_invoice_id`
+	}
+	query := global.DEFAULT_MYSQL.Table("invoice_payment_summary AS a").
+		Select("b.currency_unit, b.invoice_type, SUM(b.amount) AS amount_total, SUM(b.origin_amount) AS origin_amount_total").
+		Joins(fmt.Sprintf("JOIN contract_invoice AS b ON %s AND b.is_deleted = 0", joinCond)).
+		Where(condition, pars...).
+		Group("b.currency_unit")
+	err = query.Find(&results).Error
+	return
+}

+ 19 - 0
services/fms/contract_register.go

@@ -357,3 +357,22 @@ func FixContractInvoicePaymentType() {
 	fmt.Println("end 修复")
 	return
 }
+
+// FixContractSummaryData 修复开票到款汇总数据(一次性)
+func FixContractSummaryData() {
+	registerCond := ``
+	registerPars := make([]interface{}, 0)
+	registerOB := new(fms.ContractRegister)
+	registerList, e := registerOB.List(registerCond, registerPars)
+	if e != nil {
+		fmt.Println("获取合同登记列表失败, Err: " + e.Error())
+		return
+	}
+	fmt.Println("start 修复")
+	for i := range registerList {
+		fmt.Printf("正在修复-%d", registerList[i].ContractRegisterId)
+		SummaryInvoicePaymentByContractRegisterId(registerList[i].ContractRegisterId)
+	}
+	fmt.Println("end 修复")
+	return
+}

+ 74 - 0
services/fms/invoice_payment.go

@@ -4,7 +4,9 @@ import (
 	"fmt"
 	"github.com/shopspring/decimal"
 	"hongze/fms_api/models/fms"
+	"hongze/fms_api/services/alarm_msg"
 	"hongze/fms_api/utils"
+	"time"
 )
 
 // CalculateContractPaymentType 计算到款登记付款方式
@@ -154,3 +156,75 @@ func MergeInvoiceList2InvoicePaymentCensusInfo(invoiceList []*fms.ContractInvoic
 	}
 	return
 }
+
+// SummaryInvoicePaymentByContractRegisterId 汇总合同登记的开票到款, 即一一进行对应存入汇总表
+func SummaryInvoicePaymentByContractRegisterId(registerId int) {
+	var err error
+	defer func() {
+		if err != nil {
+			alarm_msg.SendAlarmMsg(fmt.Sprintf("汇总开票到款失败, ErrMsg: \n%s", err.Error()), 3)
+		}
+	}()
+
+	// 获取开票到款信息
+	cond := `contract_register_id = ?`
+	pars := make([]interface{}, 0)
+	pars = append(pars, registerId)
+	list, e := fms.GetContractInvoiceItemList(cond, pars)
+	if e != nil {
+		err = fmt.Errorf("获取开票到款列表失败, Err: %s", e.Error())
+		return
+	}
+	invoiceIds := make([]int, 0)
+	paymentIds := make([]int, 0)
+	for i := range list {
+		if list[i].InvoiceType == fms.ContractInvoiceTypeMake {
+			invoiceIds = append(invoiceIds, list[i].ContractInvoiceId)
+			continue
+		}
+		if list[i].InvoiceType == fms.ContractInvoiceTypePay {
+			paymentIds = append(paymentIds, list[i].ContractInvoiceId)
+		}
+	}
+	invoiceLen := len(invoiceIds)
+	paymentLen := len(paymentIds)
+
+	// 汇总数据
+	nowTime := time.Now().Local()
+	summaryList := make([]*fms.InvoicePaymentSummary, 0)
+	if invoiceLen >= paymentLen {
+		for i := range invoiceIds {
+			v := new(fms.InvoicePaymentSummary)
+			v.RegisterId = registerId
+			v.InvoiceId = invoiceIds[i]
+			v.CreateTime = nowTime
+			v.ModifyTime = nowTime
+			// 取对应key的到款ID
+			if i+1 <= paymentLen {
+				v.PaymentId = paymentIds[i]
+			}
+			summaryList = append(summaryList, v)
+		}
+	}
+	if paymentLen > invoiceLen {
+		for i := range paymentIds {
+			v := new(fms.InvoicePaymentSummary)
+			v.RegisterId = registerId
+			v.PaymentId = paymentIds[i]
+			v.CreateTime = nowTime
+			v.ModifyTime = nowTime
+			// 取对应key的开票ID
+			if i+1 <= invoiceLen {
+				v.InvoiceId = invoiceIds[i]
+			}
+			summaryList = append(summaryList, v)
+		}
+	}
+
+	// 删除并新增汇总数据
+	summaryOB := new(fms.InvoicePaymentSummary)
+	if e = summaryOB.DeleteAndCreate(registerId, summaryList); e != nil {
+		err = fmt.Errorf("新增汇总数据失败, Err: %s", e.Error())
+	}
+	return
+}