Răsfoiți Sursa

Merge branch 'fms_2.8'

ziwen 1 an în urmă
părinte
comite
5586835ff7

+ 1 - 0
.gitignore

@@ -8,3 +8,4 @@ go.sum
 latest_binlog
 /rdlucklog
 /*.exe
+/fms_api

+ 669 - 41
config/config.go

@@ -8,11 +8,14 @@ import (
 	"github.com/tealeg/xlsx"
 	"hongze/fms_api/controller/resp"
 	"hongze/fms_api/global"
+	"hongze/fms_api/models"
 	"hongze/fms_api/models/base"
 	"hongze/fms_api/models/fms"
+	"hongze/fms_api/services/alarm_msg"
 	fmsService "hongze/fms_api/services/fms"
 	"hongze/fms_api/utils"
 	"net/http"
+	"sort"
 	"strconv"
 	"strings"
 	"sync"
@@ -337,7 +340,7 @@ func ExportInvoicePaymentCensusList(c *gin.Context, results *fms.InvoicePaymentC
 		return
 	}
 	serviceTempListMap := make(map[int]*fms.ContractServiceTemplate)
-	var serviceTempShow [] *fms.ContractServiceTemplate
+	var serviceTempShow []*fms.ContractServiceTemplate
 	for i := range serviceTempList {
 		serviceTempListMap[serviceTempList[i].ServiceTemplateId] = serviceTempList[i]
 	}
@@ -345,17 +348,17 @@ func ExportInvoicePaymentCensusList(c *gin.Context, results *fms.InvoicePaymentC
 		if serviceTempList[i].ProductId == 1 {
 			rowTitle = append(rowTitle, serviceTempList[i].Title)
 			serviceTempShow = append(serviceTempShow, serviceTempList[i])
-		}else if serviceTempList[i].ProductId == 2{
-			if serviceTempList[i].Title == "行业套餐" || serviceTempList[i].Title == "权益大套餐" || (serviceTempList[i].Title == "策略" && serviceTempListMap[serviceTempList[i].Pid].Pid==0){
-			}else if serviceTempList[i].Title == "医药" || serviceTempList[i].Title == "消费" || serviceTempList[i].Title == "科技" || serviceTempList[i].Title == "智造" {
-			}else {
+		} else if serviceTempList[i].ProductId == 2 {
+			if serviceTempList[i].Title == "行业套餐" || serviceTempList[i].Title == "权益大套餐" || (serviceTempList[i].Title == "策略" && serviceTempListMap[serviceTempList[i].Pid].Pid == 0) {
+			} else if serviceTempList[i].Title == "医药" || serviceTempList[i].Title == "消费" || serviceTempList[i].Title == "科技" || serviceTempList[i].Title == "智造" {
+			} else {
 				serviceTempShow = append(serviceTempShow, serviceTempList[i])
 			}
-			if serviceTempList[i].Title == "行业套餐" || serviceTempList[i].Title == "45万" ||  serviceTempList[i].Title == "70万" {
+			if serviceTempList[i].Title == "行业套餐" || serviceTempList[i].Title == "45万" || serviceTempList[i].Title == "70万" {
 				continue
 			}
 
-			if serviceTempList[i].Pid > 0 &&  serviceTempListMap[serviceTempList[i].Pid].Pid > 0 {
+			if serviceTempList[i].Pid > 0 && serviceTempListMap[serviceTempList[i].Pid].Pid > 0 {
 				continue
 			}
 
@@ -372,8 +375,8 @@ func ExportInvoicePaymentCensusList(c *gin.Context, results *fms.InvoicePaymentC
 		v.SetStyle(style)
 		if rowTitle[i] != "权益大套餐" && rowTitle[i] != "医药" && rowTitle[i] != "消费" && rowTitle[i] != "科技" && rowTitle[i] != "智造" {
 			v.VMerge = 1
-			hi ++
-		}else{
+			hi++
+		} else {
 			if insertHi == 0 {
 				insertHi = hi
 			}
@@ -384,7 +387,7 @@ func ExportInvoicePaymentCensusList(c *gin.Context, results *fms.InvoicePaymentC
 
 	// 新增一行放主观和客观
 	specialRow := sheet.AddRow()
-	for i:=0; i< hi; i++ {
+	for i := 0; i < hi; i++ {
 		if i == insertHi {
 			v1 := specialRow.AddCell()
 			v1.SetString("45万")
@@ -392,25 +395,25 @@ func ExportInvoicePaymentCensusList(c *gin.Context, results *fms.InvoicePaymentC
 			v1 = specialRow.AddCell()
 			v1.SetString("70万")
 			v1.SetStyle(style)
-			for j:=0; j<8;j++ {
-				if j%2 ==0 {
+			for j := 0; j < 8; j++ {
+				if j%2 == 0 {
 					v1 = specialRow.AddCell()
 					v1.SetString("主观")
 					v1.SetStyle(style)
-				}else{
+				} else {
 					v1 = specialRow.AddCell()
 					v1.SetString("客观")
 					v1.SetStyle(style)
 				}
 			}
-		}else{
+		} else {
 			v := specialRow.AddCell()
 			v.SetString("")
 		}
 	}
 
 	newCompanyMap := map[int]string{0: "否", 1: "是"}
-	sellerTypeMap := map[int]string{1:"FICC销售", 2:"权益销售"}
+	sellerTypeMap := map[int]string{1: "FICC销售", 2: "权益销售"}
 	for k, v := range list {
 		dataRow := sheet.AddRow()
 		// 前四个单元格根据每行开票到款条数向下合并
@@ -453,15 +456,15 @@ func ExportInvoicePaymentCensusList(c *gin.Context, results *fms.InvoicePaymentC
 					if item.ServiceTemplateId == serviceTempShow[i].ServiceTemplateId {
 						serviceTempShowAmount[serviceTempShow[i].ServiceTemplateId] = fmt.Sprint(item.Amount)
 						break
-					}else if serviceTempShow[i].Pid == item.ServiceTemplateId {
-						serviceTempShowAmount[serviceTempShow[i].ServiceTemplateId] = fmt.Sprint(item.Amount/2)
+					} else if serviceTempShow[i].Pid == item.ServiceTemplateId {
+						serviceTempShowAmount[serviceTempShow[i].ServiceTemplateId] = fmt.Sprint(item.Amount / 2)
 						break
 					}
 				}
 			}
 			for i := range serviceTempShow {
 				sa := ""
-				if am, ok :=  serviceTempShowAmount[serviceTempShow[i].ServiceTemplateId]; ok {
+				if am, ok := serviceTempShowAmount[serviceTempShow[i].ServiceTemplateId]; ok {
 					sa = am
 				}
 				rowData = append(rowData, sa)
@@ -554,25 +557,25 @@ func (ct *InvoicePaymentController) List(c *gin.Context) {
 		}
 	}
 
-	if req.ListParam == 1{
+	if req.ListParam == 1 {
 		cond += ` AND a.service_product_id = 1 `
-	}else if req.ListParam == 2 {
+	} else if req.ListParam == 2 {
 		cond += ` AND a.service_product_id = 2 `
 	}
 
 	// 开票到款日期
 	if req.TimeType != 0 {
-		if req.TimeType == 1 &&  req.StartDate != "" && req.EndDate != "" {
+		if req.TimeType == 1 && req.StartDate != "" && req.EndDate != "" {
 			st := fmt.Sprint(req.StartDate, " 00:00:00")
 			ed := fmt.Sprint(req.EndDate, " 23:59:59")
 			cond += ` AND (c.invoice_time BETWEEN ? AND ?) `
 			pars = append(pars, st, ed)
-		}else if req.TimeType == 2 &&  req.StartDate != "" && req.EndDate != "" {
+		} else if req.TimeType == 2 && req.StartDate != "" && req.EndDate != "" {
 			st := fmt.Sprint(req.StartDate, " 00:00:00")
 			ed := fmt.Sprint(req.EndDate, " 23:59:59")
 			cond += ` AND (d.invoice_time BETWEEN ? AND ?) `
 			pars = append(pars, st, ed)
-		}else if req.TimeType == 3 &&  req.StartDate != "" && req.EndDate != "" {
+		} else if req.TimeType == 3 && req.StartDate != "" && req.EndDate != "" {
 			st := fmt.Sprint(req.StartDate, " 00:00:00")
 			ed := fmt.Sprint(req.EndDate, " 23:59:59")
 			cond += ` AND (c.invoice_time BETWEEN ? AND ?) AND (d.invoice_time BETWEEN ? AND ?) `
@@ -585,21 +588,18 @@ func (ct *InvoicePaymentController) List(c *gin.Context) {
 		pars = append(pars, st, ed, st, ed)
 	}
 
-
 	if req.HasInvoice == "1" {
 		cond += ` AND a.invoice_id > 0 `
-	}else if req.HasInvoice == "0" {
+	} else if req.HasInvoice == "0" {
 		cond += ` AND a.invoice_id = 0 `
 	}
 
 	if req.HasPayment == "1" {
 		cond += ` AND a.payment_id > 0 `
-	}else if req.HasPayment == "0" {
+	} else if req.HasPayment == "0" {
 		cond += ` AND a.payment_id = 0 `
 	}
 
-
-
 	page := new(base.Page)
 	page.SetPageSize(req.PageSize)
 	page.SetCurrent(req.Current)
@@ -612,41 +612,40 @@ func (ct *InvoicePaymentController) List(c *gin.Context) {
 		return
 	}
 	if req.SortParam == "" {
-			page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: true})
-			page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: false})
-			page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: false})
-			page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: false})
-			page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
-	}else if req.SortParam == "invoice_time" {
+		page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: true})
+		page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: false})
+		page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: false})
+		page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: false})
+		page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
+	} else if req.SortParam == "invoice_time" {
 		if req.SortType == "asc" {
 			page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: false})
 			page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: true})
 			page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: true})
 			page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: true})
-		}else{
+		} else {
 			page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: true})
 			page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: false})
 			page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: false})
 			page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
 		}
-	}else if req.SortParam == "payment_date" {
+	} else if req.SortParam == "payment_date" {
 		if req.SortType == "asc" {
 			page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: false})
 			page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: true})
 			page.AddOrderItem(base.OrderItem{Column: "d.amount", Asc: true})
 			page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: true})
-		}else{
+		} else {
 			page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: true})
 			page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: false})
 			page.AddOrderItem(base.OrderItem{Column: "d.amount", Asc: false})
 			page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
 		}
-	}else{
+	} else {
 		resp.Fail("排序字段不正确", c)
 		return
 	}
 
-
 	if req.IsExport == 1 {
 		page.SetPageSize(10000)
 		page.SetCurrent(1)
@@ -724,7 +723,7 @@ func (ct *InvoicePaymentController) List(c *gin.Context) {
 				contractServiceMap[contractServiceList[i].ContractRegisterId] = append(contractServiceMap[contractServiceList[i].ContractRegisterId], contractServiceList[i])
 				servicesNameMap[contractServiceList[i].ContractRegisterId] = append(servicesNameMap[contractServiceList[i].ContractRegisterId], contractServiceList[i].Title)
 			}
-*/
+			*/
 			servicesNameMap, serviceFormatMap, e := fmsService.GetContractServiceNameFormat(queryRegisterIds)
 			if e != nil {
 				listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
@@ -817,7 +816,7 @@ func (ct *InvoicePaymentController) List(c *gin.Context) {
 		}()
 
 		// 开票到款金额合计(换算后)
-		var invoiceTotal, paymentTotal,amountTotal float64
+		var invoiceTotal, paymentTotal, amountTotal float64
 		wg.Add(1)
 		go func() {
 			defer wg.Done()
@@ -955,4 +954,633 @@ func (ct *InvoicePaymentController) List(c *gin.Context) {
 	resp.OkData("获取成功", baseData, c)
 }
 
+// IncomeList
+// @Title 业务收入统计表
+// @Description 获取业务收入统计表接口
+// @Param   ListParam		query	int		false	"套餐类型: 0-月度; 1-季度; 2-半年度;3-年度;4-月度累计"
+// @Success 200 {object} fms.CensusIncomeChartResp
+// @router /census/income/list [get]
+func (this *InvoicePaymentController) IncomeList(c *gin.Context) {
+	var req fms.IncomeListReq
+	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
+	}
+	//收入统计
+	var incomeList models.CensusIncomeChartResp
+	ch := make(chan models.CensusIncomeChartResp, 1)
+	go getCensusIncomeListV2(ch, req)
+
+	for v := range ch {
+		incomeList = v
+		close(ch)
+	}
+	// 是否导出
+	if req.IsExport == 1 {
+		ExportIncomeList(c, incomeList.DataList)
+		return
+	}
+	resp.OkData("获取成功", incomeList, c)
+}
+
+func getCensusIncomeListV2(ch chan models.CensusIncomeChartResp, req fms.IncomeListReq) (incomeChart models.CensusIncomeChartResp, err error) {
+	defer func() {
+		if err != nil {
+			global.LOG.Error(err)
+			go alarm_msg.SendAlarmMsg("获取近两年的收入统计数据异常,Err:"+err.Error(), 3)
+			//go utils.SendEmail(utils.APPNAME+"获取近12个月的收入统计数据异常:"+time.Now().Format("2006-01-02 15:04:05"), err.Error(), utils.EmailSendToUsers)
+		}
+		ch <- incomeChart
+	}()
+	//todayStr := utils.GetToday("20060102")
+	//key := "admin:home:fmsIncomeList:" + todayStr
+	//
+	//redisJsonData, redisErr := global.Redis.Get(context.TODO(), key).Result()
+	//if redisErr != nil {
+
+	//获取最新的开票到款日期
+	cond := ``
+	pars := make([]interface{}, 0)
+
+	if req.SellerIds != "" {
+		sellerIds := strings.Split(req.SellerIds, ",")
+		cond += ` AND (a.seller_id in ? )`
+		pars = append(pars, sellerIds, sellerIds)
+	}
+	if req.CompanyType == 1 {
+		cond += ` AND b.new_company = 1 `
+	} else if req.CompanyType == 2 {
+		cond += ` AND b.new_company = 0 `
+	}
+	invoiceItem, err := fms.GetLatestIncome(cond, pars)
+	if err != nil {
+		err = fmt.Errorf("获取最新的开票或到款日期, Err: %s", err.Error())
+		return
+	}
+	invoiceItem.InvoiceDate = invoiceItem.InvoiceDate.AddDate(0,0,-invoiceItem.InvoiceDate.Day()+1)
+
+	var dateSlice []string
+	var totalMoneySlice, prevTotalMoneySlice []float64
+	var yoySlice []string
+	var yearNum, monthNum int
+	var reqStartDate, reqEndDate time.Time
+	historyTime, _ := time.Parse(utils.FormatDate, "2023-04-01")
+
+	if req.StartDate != "" && req.EndDate != "" {
+		st := fmt.Sprint(req.StartDate, "-01 00:00:00")
+		ed := fmt.Sprint(req.EndDate, "-01 23:59:59")
+		reqStartDate, _ = time.Parse(utils.FormatDateTime, st)
+		reqEndDate, _ = time.Parse(utils.FormatDateTime, ed)
+		if reqEndDate.After(invoiceItem.InvoiceDate) {
+			yearNum = invoiceItem.InvoiceDate.Year() - reqStartDate.Year()
+			monthNum = int(invoiceItem.InvoiceDate.Month() - reqStartDate.Month())
+		} else {
+			yearNum = reqEndDate.Year() - reqStartDate.Year()
+			monthNum = int(reqEndDate.Month() - reqStartDate.Month())
+		}
+	} else {
+		yearNum = invoiceItem.InvoiceDate.Year() - 2020
+		monthNum = int(invoiceItem.InvoiceDate.Month() - 1)
+	}
+
+	if yearNum < 0 {
+		yearNum = -yearNum
+	}
+	if monthNum < 0 {
+		monthNum = -monthNum
+	}
+	numMonth := yearNum*12 + monthNum //共存在多少个月
+	//if req.ListParam == "1" {
+	//	numMonth = numMonth / 3
+	//} else if req.ListParam == "2" {
+	//	numMonth = numMonth / 6
+	//} else if req.ListParam == "3" {
+	//	numMonth = numMonth / 12
+	//}
+	// 累计值
+	var accumulate float64
+	var partAccumulate float64
+	var historyAccumulate float64
+	var partHistoryAccumulate float64
+	//dataList := make([]*fms.IncomeSummaryItem, 0)
+	//historydataList := make([]*fms.IncomeSummaryItem, 0)
+	fmt.Println("numMonth:", numMonth)
+	fmt.Println("InvoiceDate:", invoiceItem.InvoiceDate)
+
+	var j int
+	for i := 0; i <= numMonth; i++ {
+		//timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
+
+		var endDateTime time.Time
+		var prevEndDateTime time.Time
+		var prevStartDate, prevEndDate string
+		var startDate, endDate string
+		//开始日期
+		if req.StartDate != "" && req.EndDate != "" {
+			startDate = reqStartDate.AddDate(0, i, 0).Format("2006-01")
+			prevStartDate = reqStartDate.AddDate(-1, i, 0).Format("2006-01")
+		} else {
+			startDate = invoiceItem.InvoiceDate.AddDate(0, i-numMonth, 0).Format("2006-01")
+			prevStartDate = invoiceItem.InvoiceDate.AddDate(-1, i-numMonth, 0).Format("2006-01")
+		}
+		startDate = fmt.Sprint(startDate, "-01")
+		prevStartDate = fmt.Sprint(prevStartDate, "-01")
+		startDateTime, _ := time.Parse(utils.FormatDate, startDate)
+		prevStartDateTime, _ := time.Parse(utils.FormatDate, prevStartDate)
+
+		//结束日期
+		if req.StartDate != "" && req.EndDate != "" {
+			endDateTime = reqStartDate.AddDate(0, i+1, -1)
+			prevEndDateTime = reqStartDate.AddDate(-1, i+1, -1)
+			if reqEndDate.After(invoiceItem.InvoiceDate) {
+				endDateTime = invoiceItem.InvoiceDate.AddDate(0, i-numMonth+1, -1)
+				prevEndDateTime = invoiceItem.InvoiceDate.AddDate(-1, i-numMonth+1, -1)
+			}
+		} else {
+			endDateTime = invoiceItem.InvoiceDate.AddDate(0, i-numMonth+1, -1)
+			prevEndDateTime = invoiceItem.InvoiceDate.AddDate(-1, i-numMonth+1, -1)
+		}
+		endDate = endDateTime.Format(utils.FormatDate)
+		prevEndDate = prevEndDateTime.Format(utils.FormatDate)
+
+		cond := `1 = 1`
+		histrtyCond := `1 = 1`
+		pars := make([]interface{}, 0)
+		historyPars := make([]interface{}, 0)
+
+		prevCond := `1 = 1`
+		prevHistoryCond := `1 = 1`
+		prevPars := make([]interface{}, 0)
+		prevHistoryPars := make([]interface{}, 0)
+
+		if req.CompanyType == 1 {
+			cond += ` AND b.new_company = 1 `
+			prevCond += ` AND b.new_company = 1 `
+			histrtyCond += ` AND new_company = 1 `
+			prevHistoryCond += ` AND new_company = 1 `
+		} else if req.CompanyType == 2 {
+			cond += ` AND b.new_company = 0 `
+			prevCond += ` AND b.new_company = 0 `
+			histrtyCond += ` AND new_company = 0 `
+			prevHistoryCond += ` AND new_company = 0 `
+		}
+
+		if req.SellerIds != "" {
+			sellerIds := strings.Split(req.SellerIds, ",")
+			cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
+			pars = append(pars, sellerIds, sellerIds)
+			prevCond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
+			prevPars = append(prevPars, sellerIds, sellerIds)
+			histrtyCond += ` AND seller_id in ? `
+			prevHistoryCond += ` AND seller_id in ? `
+			historyPars = append(historyPars, sellerIds)
+			prevHistoryPars = append(prevHistoryPars, sellerIds)
+		}
+//fmt.Println("i:",i)
+//fmt.Println("j:",j)
+		{
+			//本期
+			st := fmt.Sprint(startDate, " 00:00:00")
+			ed := fmt.Sprint(endDate, " 23:59:59")
+			//校验日期,分段查询
+			if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
+				//全部走新查询
+				//fmt.Println("新查询")
+				cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
+				pars = append(pars, st, ed, st, ed)
+				summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
+				if e != nil {
+					return
+				}
+
+				// 开票到款金额合计(换算后)
+				var amountTotal float64
+
+				if len(summaryIds) > 0 {
+					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(amountPars, summaryIds)
+					amountCond += ` AND (b.invoice_time BETWEEN ? AND ?)`
+					amountPars = append(amountPars, st, ed)
+					results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
+					if e != nil {
+						err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
+						return
+					}
+					//dataList = append(dataList, results...)
+					var amountSum float64
+					for _, result := range results {
+						incomeChart.DataList = append(incomeChart.DataList, result)
+						amountSum += result.Amount
+					}
+					amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
+					accumulate += amountTotal
+					partAccumulate += amountTotal
+				}
+				if i == j || i == numMonth {
+					if req.ListParam == "4" {
+						totalMoneySlice = append(totalMoneySlice, accumulate)
+					} else if req.ListParam == "0" {
+						totalMoneySlice = append(totalMoneySlice, amountTotal)
+					} else if i > 0 || i == numMonth {
+						totalMoneySlice = append(totalMoneySlice, partAccumulate)
+						fmt.Println("partAccumulate:",partAccumulate)
+						partAccumulate  = 0.0
+					}
+				}
+			} else if endDateTime.Before(historyTime) || endDateTime.Equal(historyTime) {
+				//全部走旧查询
+				//fmt.Println("旧查询")
+				fmt.Println("st:",st)
+				fmt.Println("ed:",ed)
+				histrtyCond += ` AND (invoice_time BETWEEN ? AND ? )`
+				historyPars = append(historyPars, st, ed)
+				//fmt.Println("st:",st)
+				//fmt.Println("ed:",ed)
+				// 开票到款金额合计(换算后)
+				var amountTotal float64
+				results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
+				if e != nil {
+					err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
+					return
+				}
+				var amountSum float64
+				//dataList = append(dataList, results...)
+				for _, result := range results {
+					incomeChart.DataList = append(incomeChart.DataList, result)
+					amountSum += result.Amount
+				}
+				amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
+				accumulate += amountTotal
+				partAccumulate += amountTotal
+
+				if i == j || i == numMonth {
+					if req.ListParam == "4" {
+						totalMoneySlice = append(totalMoneySlice, accumulate)
+					} else if req.ListParam == "0" {
+						totalMoneySlice = append(totalMoneySlice, amountTotal)
+					} else if i > 0 || i == numMonth {
+						totalMoneySlice = append(totalMoneySlice, partAccumulate)
+						partAccumulate  = 0.0
+					}
+				}
+
+				//fmt.Println("partAccumulate:",partAccumulate)
+			}
+			//else {
+			//	//刚好跨过20230301的,各查一部分
+			//	//fmt.Println("查询3")
+			//	var historyAmountTotal float64
+			//	histrtyCond += ` AND (invoice_time BETWEEN ? AND '2023-03-01 23:59:59' ) `
+			//	historyPars = append(historyPars, st)
+			//	//// 开票到款金额合计(换算后)
+			//	var amountTotal float64
+			//	results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
+			//	if e != nil {
+			//		err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
+			//		return
+			//	}
+			//	var amountSum float64
+			//	for _, result := range results {
+			//		incomeChart.DataList = append(incomeChart.DataList, result)
+			//		amountSum += result.Amount
+			//	}
+			//	amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
+			//	accumulate += amountTotal
+			//	historyAmountTotal = amountTotal
+			//
+			//	cond += ` AND ((c.invoice_time BETWEEN '2023-03-02 00:00:00' AND ?) or (d.invoice_time BETWEEN '2023-03-02 00:00:00' AND ?))`
+			//	pars = append(pars, ed, ed)
+			//	summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
+			//	if e != nil {
+			//		return
+			//	}
+			//
+			//	if len(summaryIds) > 0 {
+			//		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(amountPars, summaryIds)
+			//		results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
+			//		if e != nil {
+			//			err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
+			//			return
+			//		}
+			//		var amountSum float64
+			//		for _, result := range results {
+			//			incomeChart.DataList = append(incomeChart.DataList, result)
+			//			amountSum += result.Amount
+			//		}
+			//		amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
+			//		accumulate += amountTotal
+			//	}
+			//	if req.ListParam == "4" {
+			//		totalMoneySlice = append(totalMoneySlice, accumulate)
+			//	} else {
+			//		totalMoneySlice = append(totalMoneySlice, amountTotal+historyAmountTotal)
+			//	}
+			//
+			//}
+
+		}
+
+		{ //去年同期,用于计算同比值
+			prevSt := fmt.Sprint(prevStartDate, " 00:00:00")
+			prevEd := fmt.Sprint(prevEndDate, " 23:59:59")
+
+			//校验日期,分段查询
+			if prevStartDateTime.After(historyTime) || prevStartDateTime.Equal(historyTime) {
+				//全部走新查询
+				prevCond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
+				prevPars = append(prevPars, prevSt, prevEd, prevSt, prevEd)
+				prevSummaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(prevCond, prevPars)
+				if e != nil {
+					return
+				}
+
+				// 开票到款金额合计(换算后)
+				var prevAmountTotal float64
+
+				if len(prevSummaryIds) > 0 {
+					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(amountPars, prevSummaryIds)
+					amountCond += ` AND (b.invoice_time BETWEEN ? AND ?)`
+					amountPars = append(amountPars, prevSt, prevEd)
+					results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
+					if e != nil {
+						err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
+						return
+					}
+					var amountSum float64
+					//historydataList = append(historydataList, results...)
+					for _, result := range results {
+						amountSum += result.Amount
+					}
+					prevAmountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
+					historyAccumulate += prevAmountTotal
+					partHistoryAccumulate += prevAmountTotal
+				}
+				if i == j || i == numMonth {
+					if req.ListParam == "4" {
+						prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate)
+					} else if req.ListParam == "0" {
+						prevTotalMoneySlice = append(prevTotalMoneySlice, prevAmountTotal)
+					} else if i > 0 || i == numMonth {
+						prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate)
+						fmt.Println("partHistoryAccumulate:",partHistoryAccumulate)
+						partHistoryAccumulate = 0.0
+					}
+				}
+			} else if prevEndDateTime.Before(historyTime) || prevEndDateTime.Equal(historyTime) {
+				//全部走旧查询
+				fmt.Println("prevSt:",prevSt)
+				fmt.Println("prevEd:",prevEd)
+				prevHistoryCond += ` AND (invoice_time BETWEEN ? AND ?)`
+				prevHistoryPars = append(prevHistoryPars, prevSt, prevEd)
+				// 开票到款金额合计(换算后)
+				var amountTotal float64
+				results, e := fms.GetIncomeHistory(prevHistoryCond, prevHistoryPars)
+				if e != nil {
+					err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
+					return
+				}
+				//historydataList = append(historydataList, results...)
+				var amountSum float64
+				for _, result := range results {
+					amountSum += result.Amount
+				}
+				amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
+				historyAccumulate += amountTotal
+				partHistoryAccumulate += amountTotal
+
+				if i == j || i == numMonth {
+					if req.ListParam == "4" {
+						prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate)
+					} else if req.ListParam == "0" {
+						prevTotalMoneySlice = append(prevTotalMoneySlice, amountTotal)
+					} else if i > 0 || i == numMonth {
+						prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate)
+						fmt.Println("partHistoryAccumulate:",partHistoryAccumulate)
+						partHistoryAccumulate = 0.0
+					}
+				}
+				//fmt.Println("partHistoryAccumulate:",partHistoryAccumulate)
+			}
+			//else {
+			//	//刚好跨过20230301的,各查一部分
+			//	var historyAmountTotal float64
+			//	prevHistoryCond += ` AND (invoice_time BETWEEN ? AND '2023-03-01 23:59:59' ) `
+			//	prevHistoryPars = append(prevHistoryPars, prevSt)
+			//	// 开票到款金额合计(换算后)
+			//	var amountTotal float64
+			//	results, e := fms.GetIncomeHistory(prevHistoryCond, prevHistoryPars)
+			//	if e != nil {
+			//		err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
+			//		return
+			//	}
+			//	var amountSum float64
+			//	for _, result := range results {
+			//		amountSum += result.Amount
+			//	}
+			//	amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
+			//	historyAccumulate += amountTotal
+			//
+			//
+			//	prevCond += ` AND ((c.invoice_time BETWEEN '2023-03-02 00:00:00' AND ?) or (d.invoice_time BETWEEN '2023-03-02 00:00:00' AND ?))`
+			//	prevPars = append(prevPars, prevEd, prevEd)
+			//	prevSummaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(prevCond, prevPars)
+			//	if e != nil {
+			//		return
+			//	}
+			//
+			//	// 开票到款金额合计(换算后)
+			//	var prevAmountTotal float64
+			//
+			//	if len(prevSummaryIds) > 0 {
+			//		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(amountPars, prevSummaryIds)
+			//		results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
+			//		if e != nil {
+			//			err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
+			//			return
+			//		}
+			//		var amountSum float64
+			//		for _, result := range results {
+			//			amountSum += result.Amount
+			//		}
+			//		prevAmountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
+			//		historyAccumulate += prevAmountTotal
+			//	}
+			//	if req.ListParam == "4" {
+			//		prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate)
+			//	} else {
+			//		prevTotalMoneySlice = append(prevTotalMoneySlice, prevAmountTotal+historyAmountTotal)
+			//	}
+			//}
+			if req.ListParam == "1" && i == j {
+				if i == 0{
+					dateSlice = append(dateSlice, startDateTime.AddDate(0, 2, 0).Format("06/01"))
+					j = j + 2
+				} else {
+					dateSlice = append(dateSlice, startDateTime.AddDate(0, 3, 0).Format("06/01"))
+					j = j + 3
+				}
+			} else if req.ListParam == "2" && i == j {
+				if i == 0{
+					dateSlice = append(dateSlice, startDateTime.AddDate(0, 5, 0).Format("06/01"))
+					j = j + 5
+				} else {
+					dateSlice = append(dateSlice, startDateTime.AddDate(0, 6, 0).Format("06/01"))
+					j = j + 6
+				}
+			} else if req.ListParam == "3" && i == j {
+				if i == 0{
+					dateSlice = append(dateSlice, startDateTime.AddDate(0, 11, 0).Format("06/01"))
+					j = j + 11
+				} else {
+					dateSlice = append(dateSlice, startDateTime.AddDate(0, 12, 0).Format("06/01"))
+					j = j + 12
+				}
+			} else if i == j {
+				dateSlice = append(dateSlice, startDateTime.Format("06/01"))
+				j++
+			}
+		}
+	}
+	//for i, v := range dataList {
+	//	amountTotal, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", v.Amount), 64)
+	//	accumulate += amountTotal
+	//
+	//	if req.ListParam == "4" {
+	//		totalMoneySlice = append(totalMoneySlice, accumulate)
+	//	} else {
+	//		totalMoneySlice = append(totalMoneySlice, amountTotal)
+	//	}
+	//	if req.ListParam == "1" {
+	//		i = i + 2
+	//	} else if req.ListParam == "2" {
+	//		i = i + 5
+	//	} else if req.ListParam == "3" {
+	//		i = i + 11
+	//	}
+	//}
+	//
+	//for i, v := range historydataList {
+	//	historyAmountTotal, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", v.Amount), 64)
+	//	historyAccumulate += historyAmountTotal
+	//
+	//	if req.ListParam == "4" {
+	//		prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate)
+	//	} else {
+	//		prevTotalMoneySlice = append(prevTotalMoneySlice, historyAmountTotal)
+	//	}
+	//	if req.ListParam == "1" {
+	//		i = i + 2
+	//	} else if req.ListParam == "2" {
+	//		i = i + 5
+	//	} else if req.ListParam == "3" {
+	//		i = i + 11
+	//	}
+	//}
+
+	fmt.Println("prevTotalMoneySlice:", len(prevTotalMoneySlice))
+	fmt.Println("totalMoneySlice:", len(totalMoneySlice))
+
+	//计算同比值
+	for i := range prevTotalMoneySlice {
+		var yoy float64
+		var yoyStr string
+		//fmt.Println("1:", prevTotalMoneySlice[i])
+		//fmt.Println("2:", totalMoneySlice[i])
+		//fmt.Println("3:", totalMoneySlice[i]-prevTotalMoneySlice[i])
+		if prevTotalMoneySlice[i] != 0 && totalMoneySlice[i] != 0 {
+			yoy = (totalMoneySlice[i] - prevTotalMoneySlice[i]) / prevTotalMoneySlice[i]
+			yoyStr = fmt.Sprintf("%.4f", yoy)
+
+			if i == len(prevTotalMoneySlice)-1 && i > 0 && req.ListParam == "3"{
+				fmt.Println("totalMoneySlice[i-1]:",totalMoneySlice[i-1])
+				yoy = (totalMoneySlice[i] - totalMoneySlice[i-1]) / totalMoneySlice[i-1]
+				yoyStr = fmt.Sprintf("%.4f", yoy)
+			}
+		}
+		yoySlice = append(yoySlice, yoyStr)
+	}
+
+	incomeChart.Title = "开票到款统计图"
+	incomeChart.Date = dateSlice
+	incomeChart.TotalMoney = totalMoneySlice
+	incomeChart.PrevTotalMoney = prevTotalMoneySlice
+	incomeChart.Yoy = yoySlice
+
+	//redisJsonData, err := json.Marshal(incomeChart)
+	//if err == nil {
+	//	global.Redis.SetEX(context.TODO(), key, string(redisJsonData), time.Minute*30)
+	//}
+	//} else {
+	//	err = json.Unmarshal([]byte(redisJsonData), &incomeChart)
+	//	if err != nil {
+	//		fmt.Println("近两年的收入统计数据,json转换失败")
+	//	}
+	//}
+
+	return
+}
+
+// ExportIncomeList 导出业务收入统计列表
+func ExportIncomeList(c *gin.Context, list []*fms.IncomeSummaryItem) {
+	// 生成Excel文件
+	xlsxFile := xlsx.NewFile()
+	style := xlsx.NewStyle()
+	alignment := xlsx.Alignment{
+		Horizontal: "center",
+		Vertical:   "center",
+		WrapText:   true,
+	}
+	style.Alignment = alignment
+	style.ApplyAlignment = true
+
+	sheetName := "业务收入统计表"
+	sheet, err := xlsxFile.AddSheet(sheetName)
+	if err != nil {
+		resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
+		return
+	}
 
+	// 数据表头
+	rowTitle := []string{"开票日期", "新客户(1)", "客户名称", "金额", "销售"}
+	titleRow := sheet.AddRow()
+	for i := range rowTitle {
+		v := titleRow.AddCell()
+		v.SetString(rowTitle[i])
+		v.SetStyle(style)
+	}
+	incomeSummaryItemList := make(fms.IncomeSummaryItemList, 0)
+	incomeSummaryItemList = list
+	sort.Sort(incomeSummaryItemList)
+	// 填充数据
+	for _, v := range incomeSummaryItemList {
+		dataRow := sheet.AddRow()
+		dataRow.AddCell().SetString(v.InvoiceDate.Format(utils.FormatDate)) // 开票日期
+		dataRow.AddCell().SetString(strconv.Itoa(v.NewCompany))             // 新客户
+		dataRow.AddCell().SetString(v.CompanyName)                          // 客户名称
+		dataRow.AddCell().SetString(fmt.Sprint(v.Amount))                   // 金额
+		dataRow.AddCell().SetString(v.SellerName)                           // 销售员
+	}
+
+	// 输出文件
+	var buffer bytes.Buffer
+	_ = xlsxFile.Write(&buffer)
+	content := bytes.NewReader(buffer.Bytes())
+	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
+	fileName := sheetName + randStr + ".xlsx"
+
+	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
+	c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
+	http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
+}

+ 49 - 0
controller/census/seller.go

@@ -1,11 +1,13 @@
 package crm
 
 import (
+	"fmt"
 	"github.com/gin-gonic/gin"
 	"github.com/go-playground/validator/v10"
 	"hongze/fms_api/controller/resp"
 	"hongze/fms_api/global"
 	"hongze/fms_api/models/crm"
+	"hongze/fms_api/models/fms"
 	crmService "hongze/fms_api/services/crm"
 )
 
@@ -83,4 +85,51 @@ func (rg *CompanySellerController) AllList(c *gin.Context) {
 		RaiSeller:  raiLits,
 	}
 	resp.OkData("获取成功", respItem, c)
+}
+
+// List
+// @Title 销售列表
+// @Description 销售列表
+// @Success 200 {object} crm.SellerAdminWithGroupList
+// @router /crm/company_seller/team_list [get]
+func (rg *CompanySellerController) TeamList(c *gin.Context) {
+	// 此处调整为只取销售部门的人员, 而不是原先的根据角色取
+	list, e := crmService.GetSellerList()
+	if e != nil {
+		resp.FailData("获取销售失败", "Err:"+e.Error(), c)
+		return
+	}
+
+
+	resp.OkData("获取成功", list, c)
+}
+
+func FIX() (err error) {
+	adminCond := ``
+	adminPars := make([]interface{}, 0)
+	adminOB := new(crm.Admin)
+	adminList, e := adminOB.List(adminCond, adminPars)
+	if e != nil {
+		return
+	}
+	sellerMap := make(map[string]*crm.Admin)
+	for i := range adminList {
+		sellerMap[adminList[i].RealName] = adminList[i]
+	}
+
+	list,err := fms.GetIncomeHistoryList()
+	if err != nil {
+		return
+	}
+	for _, v := range list {
+		fmt.Println("v:", v.IncomeId)
+		if seller, ok := sellerMap[v.SellerName]; ok{
+			v.SellerId = seller.AdminId
+			if e = v.Update([]string{"SellerId"}); e != nil {
+				fmt.Println("更新销售失败, Err: " + e.Error())
+				return
+			}
+		}
+	}
+	return
 }

+ 49 - 5
controller/crm/contract.go

@@ -1,6 +1,6 @@
 module hongze/fms_api
 
-go 1.15
+go 1.19
 
 require (
 	github.com/aliyun/alibaba-cloud-sdk-go v1.61.1754
@@ -14,11 +14,8 @@ require (
 	github.com/go-playground/validator/v10 v10.9.0
 	github.com/go-redis/redis/v8 v8.11.4
 	github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0
-	github.com/jonboulle/clockwork v0.2.2 // indirect
 	github.com/json-iterator/go v1.1.12
 	github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
-	github.com/lestrrat-go/strftime v1.0.5 // indirect
-	github.com/mattn/go-isatty v0.0.14 // indirect
 	github.com/olivere/elastic/v7 v7.0.31
 	github.com/op/go-logging v0.0.0-20160315200505-970db520ece7
 	github.com/rdlucklib/rdluck_tools v1.0.3
@@ -27,8 +24,55 @@ require (
 	github.com/swaggo/gin-swagger v1.3.3
 	github.com/swaggo/swag v1.7.4
 	github.com/tealeg/xlsx v1.0.5
-	golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect
 	golang.org/x/image v0.0.0-20190802002840-cff245a6509b
 	gorm.io/driver/mysql v1.1.3
 	gorm.io/gorm v1.22.2
 )
+
+require (
+	github.com/KyleBanks/depth v1.2.1 // indirect
+	github.com/PuerkitoBio/purell v1.1.1 // indirect
+	github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
+	github.com/cespare/xxhash/v2 v2.1.2 // indirect
+	github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
+	github.com/emersion/go-sasl v0.0.0-20200509203442-7bfe0ed36a21 // indirect
+	github.com/emersion/go-textwrapper v0.0.0-20200911093747-65d896831594 // indirect
+	github.com/gin-contrib/sse v0.1.0 // indirect
+	github.com/go-openapi/jsonpointer v0.19.5 // indirect
+	github.com/go-openapi/jsonreference v0.19.5 // indirect
+	github.com/go-openapi/spec v0.20.3 // indirect
+	github.com/go-openapi/swag v0.19.14 // indirect
+	github.com/go-sql-driver/mysql v1.6.0 // indirect
+	github.com/golang/protobuf v1.5.2 // indirect
+	github.com/hashicorp/hcl v1.0.0 // indirect
+	github.com/jinzhu/inflection v1.0.0 // indirect
+	github.com/jinzhu/now v1.1.2 // indirect
+	github.com/jmespath/go-jmespath v0.4.0 // indirect
+	github.com/jonboulle/clockwork v0.2.2 // indirect
+	github.com/josharian/intern v1.0.0 // indirect
+	github.com/leodido/go-urn v1.2.1 // indirect
+	github.com/lestrrat-go/strftime v1.0.5 // indirect
+	github.com/magiconair/properties v1.8.5 // indirect
+	github.com/mailru/easyjson v0.7.7 // indirect
+	github.com/mattn/go-isatty v0.0.14 // indirect
+	github.com/mitchellh/mapstructure v1.4.2 // indirect
+	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
+	github.com/modern-go/reflect2 v1.0.2 // indirect
+	github.com/pelletier/go-toml v1.9.4 // indirect
+	github.com/pkg/errors v0.9.1 // indirect
+	github.com/spf13/afero v1.6.0 // indirect
+	github.com/spf13/cast v1.4.1 // indirect
+	github.com/spf13/jwalterweatherman v1.1.0 // indirect
+	github.com/spf13/pflag v1.0.5 // indirect
+	github.com/subosito/gotenv v1.2.0 // indirect
+	github.com/ugorji/go/codec v1.1.7 // indirect
+	golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect
+	golang.org/x/net v0.0.0-20211209124913-491a49abca63 // indirect
+	golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf // indirect
+	golang.org/x/text v0.3.7 // indirect
+	golang.org/x/time v0.0.0-20191024005414-555d28b269f0 // indirect
+	golang.org/x/tools v0.1.5 // indirect
+	google.golang.org/protobuf v1.27.1 // indirect
+	gopkg.in/ini.v1 v1.66.2 // indirect
+	gopkg.in/yaml.v2 v2.4.0 // indirect
+)

+ 49 - 0
init_serve/mysql.go

@@ -0,0 +1,49 @@
+package fms
+
+import (
+	"hongze/fms_api/global"
+	"time"
+)
+
+type ContractIncomeHistory struct {
+	IncomeId    int       `json:"income_id" gorm:"primaryKey;column:income_id"`       //
+	Amount      float64   `json:"amount" gorm:"column:amount"`             // 开票金额
+	InvoiceTime time.Time `json:"invoice_time" gorm:"column:invoice_time"` // 开票日期/到款月
+	SellerId    int       `json:"seller_id" gorm:"column:seller_id"`       // 销售ID
+	SellerName  string    `json:"seller_name" gorm:"column:seller_name"`   // 销售名称
+	NewCompany  int       `json:"new_company" gorm:"column:new_company"`   // 是否为新客户:0-否;1-是
+	CompanyName string    `json:"company_name" gorm:"column:company_name"` // 客户名称
+}
+
+func (c *ContractIncomeHistory) List(condition string, pars []interface{}) (list []*ContractIncomeHistory, err error) {
+	list = make([]*ContractIncomeHistory, 0)
+	err = global.DEFAULT_MYSQL.Model(c).
+		Where(condition, pars...).
+		Find(&list).Error
+	return
+}
+
+func (c *ContractIncomeHistory) TableName() string {
+	return "contract_income_history"
+}
+
+// GetInvoicePaymentSummaryByRegisterIdAndInvoiceId 根据合同登记ID和开票ID获取汇总数据
+func GetIncomeHistory(condition string, pars []interface{}) (results []*IncomeSummaryItem, err error) {
+	sql := `SELECT amount,seller_name,new_company,company_name,invoice_time AS invoice_date FROM contract_income_history WHERE  `
+	sql += condition
+	sql += ` ORDER BY invoice_date `
+	err = global.DEFAULT_MYSQL.Raw(sql, pars...).Find(&results).Error
+	return
+}
+
+// GetInvoicePaymentSummaryByRegisterIdAndInvoiceId 根据合同登记ID和开票ID获取汇总数据
+func GetIncomeHistoryList() (results []*ContractIncomeHistory, err error) {
+	sql := `SELECT * FROM contract_income_history `
+	err = global.DEFAULT_MYSQL.Raw(sql).Find(&results).Error
+	return
+}
+
+func (c *ContractIncomeHistory) Update(updateCols []string) (err error) {
+	err = global.DEFAULT_MYSQL.Model(c).Select(updateCols).Updates(c).Error
+	return
+}

+ 25 - 1
models/fms/contract_invoice.go

@@ -430,7 +430,7 @@ func GetCensusSellerGroupInvoicePageList(page base.IPage, condition, outCond str
 			) AS b ON a.group_id = b.seller_group_id`
 	sql += ` WHERE %s ORDER BY %s LIMIT %d,%d`
 	sql = fmt.Sprintf(sql, tableName, amountSum, condition, outCond, page.GetOrderItemsString(), page.Offset(), page.GetPageSize())
-	err = global.DEFAULT_MYSQL.Raw(sql, pars).Scan(&results).Error
+	err = global.DEFAULT_MYSQL.Raw(sql, pars...).Scan(&results).Error
 	return
 }
 
@@ -638,4 +638,28 @@ func GetDuplicateContractInvoiceDetailItemList(companyName, startDate, endDate s
 		return
 	}
 	return
+}
+
+type IncomeListReq struct {
+	SellerIds    string `json:"seller_ids" form:"seller_ids" description:"销售ID,多个ID之间用逗号拼接"`
+	StartDate    string `json:"start_date" form:"start_date" binding:"omitempty,datetime=2006-01" description:"开始日期"`
+	EndDate      string `json:"end_date" form:"end_date" binding:"omitempty,datetime=2006-01" description:"结束日期"`
+	IsExport     int    `json:"is_export" form:"is_export" description:"是否导出: 0-否; 1-是"`
+	ListParam    string    `json:"list_param" form:"list_param" description:"套餐类型: 0-月度; 1-季度; 2-半年度;3-年度;4-月度累计"`
+	CompanyType     int    `json:"company_type" form:"company_type" description:"客户类型 0全部 1新客户 2老客户"`
+}
+
+//获取最新的开票或到款日期
+func GetLatestIncome(condition string, pars []interface{}) (result *ContractInvoice, err error) {
+	sql := `SELECT
+	a.* 
+FROM
+	contract_invoice AS a
+	INNER JOIN contract_register AS b ON a.contract_register_id = b.contract_register_id 
+WHERE
+	a.is_deleted = 0 `
+	sql += condition
+	sql += `ORDER BY a.invoice_time DESC  `
+	err = global.DEFAULT_MYSQL.Raw(sql, pars...).First(&result).Error
+	return
 }

+ 42 - 2
models/fms/contract_payment_service_amount.go

@@ -26,6 +26,7 @@ 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()
@@ -49,9 +50,10 @@ func (c *InvoicePaymentSummary) DeleteAndCreate(registerId int, summaryList []*I
 }
 
 type ContractRegisterSummary struct {
-	SummaryId       int       `json:"summary_id" description:"汇总ID"`
+	SummaryId int `json:"summary_id" description:"汇总ID"`
 	ContractRegister
 }
+
 // GetInvoicePaymentCensusPageList 获取商品到款统计列表-总数
 func GetInvoicePaymentCensusPageList(page base.IPage, condition string, pars []interface{}) (results []*ContractRegisterSummary, count int64, err error) {
 	query := global.DEFAULT_MYSQL.Table("invoice_payment_summary AS a").
@@ -179,8 +181,46 @@ func GetContractSummaryInvoicePaymentAmount(condition string, pars []interface{}
 }
 
 // GetInvoicePaymentSummaryByRegisterIdAndInvoiceId 根据合同登记ID和开票ID获取汇总数据
-func GetInvoicePaymentSummaryByRegisterIdAndInvoiceId(registerId,invocieId int) (results []*ContractRegisterSummary, err error) {
+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
+}
+
+type IncomeSummaryItem struct {
+	CompanyName string    `json:"company_name" description:"客户名称"`
+	NewCompany  int       `json:"new_company" description:"是否为新客户: 0-否; 1-是"`
+	InvoiceDate time.Time `json:"invoice_time" description:"开票日期"`
+	Amount      float64   `json:"amount" description:"金额"`
+	SellerName  string    `json:"seller_name" description:"销售名称"`
+}
+
+// GetContractSummaryIncomeAmount 获取汇总金额合计信息
+func GetContractSummaryIncomeAmount(condition string, pars []interface{}) (results []*IncomeSummaryItem, 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,b.invoice_time AS invoice_date , c.new_company,c.company_name,b.seller_name").
+		Joins(fmt.Sprintf(" JOIN contract_invoice AS b ON %s AND b.is_deleted = 0 ", joinCond)).
+		Joins("JOIN contract_register AS c ON a.register_id = c.contract_register_id AND c.is_deleted = 0").
+		Where(condition, pars...).Group("id").Order("invoice_date ")
+	//nq := global.DEFAULT_MYSQL.Table("(?) AS e", query).
+	//	Select(" IFNULL( SUM( e.amount ), 0 ) ")
+
+	err = query.Find(&results).Error
+	return
+}
+
+type IncomeSummaryItemList []*IncomeSummaryItem
+
+func (c IncomeSummaryItemList) Len() int {
+	return len(c)
+}
+
+func (c IncomeSummaryItemList) Less(i, j int) bool {
+	return c[i].InvoiceDate.Before(c[j].InvoiceDate)
+}
+
+func (c IncomeSummaryItemList) Swap(i, j int) {
+	c[i], c[j] = c[j], c[i]
 }

+ 13 - 2
models/statistic.go

@@ -2,6 +2,7 @@ package models
 
 import (
 	"hongze/fms_api/global"
+	"hongze/fms_api/models/fms"
 )
 
 // 收入统计图表数据
@@ -19,9 +20,19 @@ type IncomeItem struct {
 
 func GetIncomeListCount(cond string) (results *IncomeItem, err error) {
 	sql := `SELECT a.contract_money, b.arrival_money FROM (
-SELECT SUM(amount) contract_money  FROM contract_invoice  WHERE is_deleted = 0 AND (invoice_type = 1 OR invoice_type = 3) `+cond+` ) AS a,
-(SELECT SUM(amount) arrival_money FROM  contract_invoice  WHERE is_deleted = 0 AND (invoice_type = 2 OR invoice_type = 4) `+cond+` ) AS b WHERE 1=1 `
+SELECT SUM(amount) contract_money  FROM contract_invoice  WHERE is_deleted = 0 AND (invoice_type = 1 OR invoice_type = 3) ` + cond + ` ) AS a,
+(SELECT SUM(amount) arrival_money FROM  contract_invoice  WHERE is_deleted = 0 AND (invoice_type = 2 OR invoice_type = 4) ` + cond + ` ) AS b WHERE 1=1 `
 
 	err = global.DEFAULT_MYSQL.Raw(sql).First(&results).Error
 	return
 }
+
+// 收入统计图表数据
+type CensusIncomeChartResp struct {
+	Title          string                   `description:"图表名称"`
+	Date           []string                 `description:"月份"`
+	TotalMoney     []float64                `description:"总金额"`
+	PrevTotalMoney []float64                `description:"历史总金额"`
+	Yoy            []string                 `description:"同比值"`
+	DataList       []*fms.IncomeSummaryItem ` json:"-"`
+}

+ 1 - 0
models/system/sys_admin.go

@@ -11,6 +11,7 @@ func InitCensus(rg *gin.RouterGroup) {
 	inv := new(census.InvoicePaymentController)
 	invGroup := rg.Group("invoice_payment/").Use(middleware.Token())
 	invGroup.GET("list", inv.List)
+	invGroup.GET("income/list", inv.IncomeList)
 
 	// 销售
 	sel := new(census.SellerController)

+ 1 - 0
routers/contract.go

@@ -20,4 +20,5 @@ func InitCrm(rg *gin.RouterGroup) {
 	slGroup.GET("list", sl.List)
 	slGroup.GET("group_list", sl.GroupList)
 	slGroup.GET("all_list", sl.AllList)
+	slGroup.GET("team_list", sl.TeamList)
 }

+ 117 - 1
routers/resource.go

@@ -92,7 +92,7 @@ func GetSellerTeamGroupMap() (teamGroupMap map[int]*crm.SysGroup, err error) {
 }
 
 
-// GetSellerDepartmentList 获取销售部门列表-包含大组和小组
+// GetSellerDepartmentList 获取销售部门列表-大组
 func GetSellerDepartmentList() (resp crm.SellerAdminWithGroupList, err error) {
 	// 获取组别列表
 	departmentIds := []int{crm.SellerDepartmentId,crm.RaiSellerDepartmentId}
@@ -270,3 +270,119 @@ func GetSellerDepartmentListWithGroupAndTeamByDepartment() (ficcList []*crm.Sell
 	}
 	return
 }
+
+// GetSellerList 获取销售部门列表-大组和小组
+func GetSellerList() (resp crm.SellerAdminWithGroupList, err error) {
+	// 获取组别列表
+	departmentIds := []int{crm.SellerDepartmentId,crm.RaiSellerDepartmentId}
+	groupCond := "department_id in (?)"
+	groupPars := make([]interface{}, 0)
+	groupPars = append(groupPars, departmentIds)
+	groupOB := new(crm.SysGroup)
+	fullGroups, e := groupOB.List(groupCond, groupPars)
+	if e != nil {
+		err = errors.New("获取组别列表失败, Err: " + e.Error())
+		return
+	}
+	fullGroupMap := make(map[int]*crm.SysGroup)
+	for _, v := range fullGroups{
+		fullGroupMap[v.GroupId] = v
+	}
+	// 获取销售部门所有销售信息
+	adminCond := "department_id in (?) "
+	adminPars := make([]interface{}, 0)
+	adminPars = append(adminPars, departmentIds)
+	adminOB := new(crm.Admin)
+	adminList, e := adminOB.List(adminCond, adminPars)
+	if e != nil {
+		err = errors.New("获取销售列表失败, Err: " + e.Error())
+		return
+	}
+
+	var listGroup []crm.SellerAdminWithGroupTree
+	//var listDepartment []crm.SellerAdminWithGroupTree
+	departmentListMap := make(map[int][]crm.SellerAdminWithGroupTree)
+	groupListMap := make(map[int][]crm.SellerAdminWithGroupTree)
+	teamListMap := make(map[int][]crm.SellerAdminWithGroupTree)
+	//departmentHasMap := make(map[int]bool)
+	groupHasMap  := make(map[int]bool)
+	teamHasMap := make(map[int]bool)
+
+	for _, v := range adminList {
+		tmp := crm.SellerAdminWithGroupTree{
+			SellerId:    v.AdminId,
+			SellerName:  v.RealName,
+		}
+		if v.GroupId > 0 {
+			if groupInfo, ok := fullGroupMap[v.GroupId]; ok {
+				if groupInfo.ParentId > 0 {
+					teamListMap[v.GroupId] = append(teamListMap[v.GroupId], tmp)
+				}else{
+					groupListMap[groupInfo.GroupId] = append(groupListMap[groupInfo.GroupId], tmp)
+				}
+			}else {
+				departmentListMap[v.DepartmentId] = append(departmentListMap[v.DepartmentId], tmp)
+			}
+		}else if v.DepartmentId > 0{
+			departmentListMap[v.DepartmentId] = append(departmentListMap[v.DepartmentId], tmp)
+		}
+	}
+	for _, groupInfo := range fullGroups {
+		var team1 crm.SellerAdminWithGroupTree
+		//处理小组
+		if groupInfo.ParentId > 0 {
+			if _, ok2 :=teamHasMap[groupInfo.GroupId]; !ok2 {
+				if len(teamListMap[groupInfo.GroupId]) > 0 {
+					team1 = crm.SellerAdminWithGroupTree{
+						SellerId:    groupInfo.GroupId,
+						SellerName:  groupInfo.GroupName,
+						Child: teamListMap[groupInfo.GroupId],
+					}
+					teamHasMap[groupInfo.GroupId] = true
+					groupListMap[groupInfo.ParentId] = append(groupListMap[groupInfo.ParentId], team1)
+				}
+			}
+		}
+	}
+	for _, groupInfo := range fullGroups {
+		var group1 crm.SellerAdminWithGroupTree
+		//处理大组
+		if groupInfo.ParentId == 0 {
+			if _, ok2 :=groupHasMap[groupInfo.GroupId]; !ok2 {
+				if len(groupListMap[groupInfo.GroupId]) > 0 {
+					group1 = crm.SellerAdminWithGroupTree{
+						SellerId:    groupInfo.GroupId,
+						SellerName:  groupInfo.GroupName,
+						Child: groupListMap[groupInfo.GroupId],
+					}
+					groupHasMap[groupInfo.GroupId] = true
+					departmentListMap[groupInfo.DepartmentId] = append(departmentListMap[groupInfo.DepartmentId], group1)
+					listGroup = append(listGroup, group1)
+				}
+			}
+		}
+	}
+
+
+	//分部门
+	allTitleMap := map[int]string{
+		crm.SellerDepartmentId:"FICC销售",
+		crm.RaiSellerDepartmentId:"权益销售",
+	}
+	tmp1 := crm.SellerAdminWithGroupTree{
+		SellerId:   crm.SellerDepartmentId,
+		SellerName: allTitleMap[crm.SellerDepartmentId],
+		Child:      departmentListMap[crm.SellerDepartmentId],
+	}
+	tmp2 := crm.SellerAdminWithGroupTree{
+		SellerId:   crm.RaiSellerDepartmentId,
+		SellerName: allTitleMap[crm.RaiSellerDepartmentId],
+		Child:       departmentListMap[crm.RaiSellerDepartmentId],
+	}
+	allList := make([]crm.SellerAdminWithGroupTree, 0)
+	allList = append(allList, tmp1)
+	allList = append(allList, tmp2)
+	resp.AllList = allList
+
+	return
+}

+ 1 - 2
services/crm/contract.go

@@ -416,8 +416,7 @@ func TimeToTimestamp() {
 
 func TimeTransferString(format string, t time.Time) string {
 	str := t.Format(format)
-	var emptyT time.Time
-	if str == emptyT.Format(format) {
+	if t.IsZero() {
 		return ""
 	}
 	return str

+ 0 - 0
utils/constants.go