1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771 |
- package census
- import (
- "bytes"
- "fmt"
- "github.com/gin-gonic/gin"
- "github.com/go-playground/validator/v10"
- "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"
- "hongze/fms_api/utils"
- "net/http"
- "sort"
- "strconv"
- "strings"
- "time"
- )
- // IncomeList
- // @Title 业务收入统计表
- // @Description 获取业务收入统计表接口
- // @Param ListParam query int false "套餐类型: 0-月度; 1-季度; 2-半年度;3-年度;4-月度累计"
- // @Success 200 {object} fms.CensusIncomeChartResp
- // @router /census/income/chart_list [get]
- func (this *InvoicePaymentController) IncomeChartList(c *gin.Context) {
- var req fms.IncomeChartListReq
- 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)
- if req.IncomeType == 0 {
- go getCensusIncomeChartList(ch, req)
- } else {
- go getPaymentIncomeChartList(ch, req)
- }
- for v := range ch {
- incomeList = v
- close(ch)
- }
- resp.OkData("获取成功", incomeList, c)
- }
- func getCensusIncomeChartList(ch chan models.CensusIncomeChartResp, req fms.IncomeChartListReq) (incomeChart models.CensusIncomeChartResp, err error) {
- defer func() {
- if err != nil {
- global.LOG.Error(err)
- if err != utils.ErrNoRow {
- go alarm_msg.SendAlarmMsg("获取业务收入金额统计数据异常,Err:"+err.Error(), 3)
- }
- }
- ch <- incomeChart
- }()
- //todayStr := utils.GetToday("20060102")
- //key := "admin:home:fmsIncomeList:" + todayStr
- //
- //redisJsonData, redisErr := global.Redis.Get(context.TODO(), key).Result()
- //if redisErr != nil {
- //获取最新的开票到款日期
- cond := ``
- historyCond := ``
- pars := make([]interface{}, 0)
- historyPars := make([]interface{}, 0)
- if req.SellerIds != "" {
- sellerIds := strings.Split(req.SellerIds, ",")
- cond += ` AND (a.seller_id in ? ) `
- historyCond += ` AND (seller_id in ? ) `
- pars = append(pars, sellerIds)
- historyPars = append(historyPars, sellerIds)
- }
- if req.CompanyType == 1 {
- cond += ` AND b.contract_type = 1 `
- historyCond += ` AND new_company = 1 `
- } else if req.CompanyType == 2 {
- cond += ` AND b.contract_type IN (2,3,4) `
- historyCond += ` AND new_company = 0 `
- }
- var latestTime time.Time
- invoiceItem, err := fms.GetLatestIncome(cond, pars)
- if err != nil && err != utils.ErrNoRow {
- err = fmt.Errorf("获取最新的开票或到款日期, Err: %s", err.Error())
- return
- }
- latestTime = invoiceItem.InvoiceDate
- if err == utils.ErrNoRow {
- historyItem, e := fms.GetLatestHistoryIncome(historyCond, historyPars)
- if e != nil && e != utils.ErrNoRow {
- err = fmt.Errorf("获取最新的历史开票或到款日期, Err: %s", e.Error())
- return
- }
- latestTime = historyItem.InvoiceDate
- }
- if latestTime.IsZero() {
- latestTime = time.Now()
- }
- if req.CompanyType == 3 {
- cond += ` AND b.contract_type IN (2,3,4) `
- historyCond += ` AND new_company = 0 `
- }
- latestTime = latestTime.AddDate(0, 0, -latestTime.Day()+1)
- addMonth := 0
- if req.ListParam == "1" {
- addMonth = int(3 - latestTime.Month()%3)
- }
- if req.ListParam == "2" {
- addMonth = int(6 - latestTime.Month()%6)
- }
- if req.ListParam == "3" {
- addMonth = int(12 - latestTime.Month()%12)
- }
- latestTime = latestTime.AddDate(0, addMonth, 0)
- 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.ServiceTypes != "" {
- serviceTypes := strings.Split(req.ServiceTypes, ",")
- registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
- if e != nil {
- err = fmt.Errorf("获取合同登记IDs失败, Err: %s", e.Error())
- return
- }
- if len(registerIds) > 0 {
- cond += ` AND b.contract_register_id IN ?`
- pars = append(pars, registerIds)
- } else {
- cond += ` AND 1 = 2`
- }
- }
- 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(latestTime) {
- yearNum = latestTime.Year() - reqStartDate.Year()
- monthNum = int(latestTime.Month() - reqStartDate.Month())
- } else {
- yearNum = reqEndDate.Year() - reqStartDate.Year()
- monthNum = int(reqEndDate.Month() - reqStartDate.Month())
- }
- } else {
- yearNum = latestTime.Year() - 2020
- monthNum = int(latestTime.Month() - 1)
- }
- //if yearNum < 0 {
- // yearNum = -yearNum
- //}
- //if monthNum < 0 {
- // monthNum = -monthNum
- //}
- numMonth := yearNum*12 + monthNum //共存在多少个月
- if numMonth < 0 {
- numMonth = -numMonth
- }
- //if req.ListParam == "1" {
- // numMonth = numMonth / 3
- //} else if req.ListParam == "2" {
- // numMonth = numMonth / 6
- //} else if req.ListParam == "3" {
- // numMonth = numMonth / 12
- //}
- // 勾选套餐筛选时忽略导入的历史数据
- //if req.StartDate == "" {
- // req.StartDate = "2023-04"
- // req.EndDate = "3023-04"
- //} else {
- // startDateTime, _ := time.Parse(utils.FormatMonth, req.StartDate)
- // if startDateTime.Before(historyTime) {
- // req.StartDate = "2023-04"
- // }
- //}
- // 累计值
- 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:", latestTime)
- 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 = latestTime.AddDate(0, i-numMonth, 0).Format("2006-01")
- prevStartDate = latestTime.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(latestTime) {
- endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
- prevEndDateTime = latestTime.AddDate(-1, i-numMonth+1, -1)
- }
- } else {
- endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
- prevEndDateTime = latestTime.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.contract_type = 1 `
- prevCond += ` AND b.contract_type = 1 `
- histrtyCond += ` AND new_company = 1 `
- prevHistoryCond += ` AND new_company = 1 `
- } else if req.CompanyType == 2 {
- cond += ` AND b.contract_type IN (2,3,4) `
- prevCond += ` AND b.contract_type IN (2,3,4) `
- histrtyCond += ` AND new_company = 0 `
- prevHistoryCond += ` AND new_company = 0 `
- } else if req.CompanyType == 3 {
- //未续约收入金额=去年同期总收入金额(新客户+老客户)-当期老客户收入金额
- cond += ` AND b.contract_type IN (2,3,4) `
- //prevCond += ` AND b.contract_type IN (2,3,4) `
- 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)
- }
- // 套餐筛选
- if req.ServiceTypes != "" {
- serviceTypes := strings.Split(req.ServiceTypes, ",")
- registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
- if e != nil {
- err = fmt.Errorf("获取合同登记IDs失败, Err: %s", e.Error())
- return
- }
- if len(registerIds) > 0 {
- cond += ` AND a.register_id IN ?`
- prevCond += ` AND a.register_id IN ?`
- pars = append(pars, registerIds)
- prevPars = append(prevPars, registerIds)
- } else {
- cond += ` AND 1 = 2`
- prevCond += ` AND 1 = 2`
- }
- }
- //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) {
- //全部走新查询
- 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 ? `
- amountPars := make([]interface{}, 0)
- amountPars = append(amountPars, summaryIds)
- if req.SellerIds != "" {
- sellerIds := strings.Split(req.SellerIds, ",")
- amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
- amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
- amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
- } else {
- amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
- amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
- amountPars = append(amountPars, st, ed, 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
- fmt.Println("result.Amount:", 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)
- if startDateTime.Month() == 12 {
- accumulate = 0
- }
- } 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)
- if req.ServiceTypes != "" {
- // 勾选套餐筛选时忽略导入的历史数据
- histrtyCond += ` AND 1=2 `
- }
- 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)
- if startDateTime.Month() == 12 {
- accumulate = 0
- }
- } 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)
- }
- }
- { // 去年同期,用于计算同比值
- 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) // 获取摘要ID列表
- if e != nil {
- return
- }
- // 开票到款金额合计(换算后)
- var prevAmountTotal float64
- if len(prevSummaryIds) > 0 {
- amountCond := `a.id IN ? ` // 查询条件为ID在给定的摘要ID列表中
- amountPars := make([]interface{}, 0)
- amountPars = append(amountPars, prevSummaryIds) // 将摘要ID列表添加到参数列表
- if req.SellerIds != "" {
- sellerIds := strings.Split(req.SellerIds, ",")
- amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
- amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) ` // 根据卖家ID和发票/支付状态筛选时间范围
- amountPars = append(amountPars, sellerIds, prevSt, prevEd, sellerIds, prevSt, prevEd) // 将卖家ID列表添加到参数列表
- } else {
- amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
- amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))` // 根据发票/支付状态筛选时间范围
- amountPars = append(amountPars, prevSt, prevEd, 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) // 将累计金额添加到总金额切片中
- if prevStartDateTime.Month() == 12 {
- historyAccumulate = 0 // 如果是去年的12月份,则将历史金额清零
- }
- } 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)
- if req.ServiceTypes != "" {
- // 勾选套餐筛选时忽略导入的历史数据
- prevHistoryCond += ` AND 1=2 `
- }
- 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) // 将累计金额添加到总金额切片中
- if prevStartDateTime.Month() == 12 {
- historyAccumulate = 0 // 如果是去年的12月份,则将历史金额清零
- }
- } 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 // 清零部分历史金额
- }
- }
- 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++
- }
- }
- 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++
- }
- }
- }
- fmt.Println("prevTotalMoneySlice:", len(prevTotalMoneySlice))
- fmt.Println("totalMoneySlice:", len(totalMoneySlice))
- if req.CompanyType != 3 {
- //计算同比值
- 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])
- totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", totalMoneySlice[i]), 64)
- if prevTotalMoneySlice[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)
- }
- } else {
- // 当筛选条件是”月度“时,并且客户是”未续约“客户,展示柱形图和曲线图
- // 当筛选条件是”季度“、”半年度“、”年度“、”月度统计“时,并且客户是”未续约“时,仅展示柱形图,无曲线图
- // 未续约收入金额=去年同期总收入金额(新客户+老客户)-当期老客户收入金额
- // 移动平均值:若是10月份,计算8月,9月,10月,这三个月的收入金额平均值
- for i := range prevTotalMoneySlice {
- totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", prevTotalMoneySlice[i]-totalMoneySlice[i]), 64)
- var yoy float64
- var yoyStr string
- if i > 1 && req.ListParam == "0" {
- // 前俩月没有
- yoy = (totalMoneySlice[i] + totalMoneySlice[i-1] + totalMoneySlice[i-2]) / 3
- yoyStr = fmt.Sprintf("%.4f", yoy)
- yoySlice = append(yoySlice, yoyStr)
- } else {
- yoySlice = append(yoySlice, "")
- }
- }
- }
- incomeChart.Title = "开票到款统计图"
- incomeChart.Date = dateSlice[:len(totalMoneySlice)]
- 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
- }
- func getPaymentIncomeChartList(ch chan models.CensusIncomeChartResp, req fms.IncomeChartListReq) (incomeChart models.CensusIncomeChartResp, err error) {
- defer func() {
- if err != nil {
- global.LOG.Error(err)
- if err != utils.ErrNoRow {
- go alarm_msg.SendAlarmMsg("获取业务收入金额统计数据异常,Err:"+err.Error(), 3)
- }
- }
- ch <- incomeChart
- }()
- //todayStr := utils.GetToday("20060102")
- //key := "admin:home:fmsIncomeList:" + todayStr
- //
- //redisJsonData, redisErr := global.Redis.Get(context.TODO(), key).Result()
- //if redisErr != nil {
- //获取最新的开票到款日期
- cond := ``
- historyCond := ``
- pars := make([]interface{}, 0)
- historyPars := make([]interface{}, 0)
- if req.SellerIds != "" {
- sellerIds := strings.Split(req.SellerIds, ",")
- cond += ` AND (a.seller_id in ? ) `
- historyCond += ` AND (seller_id in ? ) `
- pars = append(pars, sellerIds)
- historyPars = append(historyPars, sellerIds)
- }
- if req.CompanyType == 1 {
- cond += ` AND b.contract_type = 1 `
- historyCond += ` AND new_company = 1 `
- } else if req.CompanyType == 2 {
- cond += ` AND b.contract_type IN (2,3,4) `
- historyCond += ` AND new_company = 0 `
- }
- var earliestTime time.Time
- EarliestinvoiceItem, err := fms.GetEarliestPaymentIncome(cond, pars)
- if err != nil && err != utils.ErrNoRow {
- err = fmt.Errorf("获取最新的开票或到款日期, Err: %s", err.Error())
- return
- }
- earliestTime = EarliestinvoiceItem.InvoiceDate
- var latestTime time.Time
- invoiceItem, err := fms.GetLatestPaymentIncome(cond, pars)
- if err != nil && err != utils.ErrNoRow {
- err = fmt.Errorf("获取最新的开票或到款日期, Err: %s", err.Error())
- return
- }
- latestTime = invoiceItem.InvoiceDate
- if latestTime.IsZero() {
- latestTime = time.Now()
- }
- if req.CompanyType == 3 {
- cond += ` AND b.contract_type IN (2,3,4) `
- historyCond += ` AND new_company = 0 `
- }
- latestTime = latestTime.AddDate(0, 0, -latestTime.Day()+1)
- addMonth := 0
- if req.ListParam == "1" {
- addMonth = int(3 - latestTime.Month()%3)
- }
- if req.ListParam == "2" {
- addMonth = int(6 - latestTime.Month()%6)
- }
- if req.ListParam == "3" {
- addMonth = int(12 - latestTime.Month()%12)
- }
- latestTime = latestTime.AddDate(0, addMonth, 0)
- var dateSlice []string
- var totalMoneySlice, prevTotalMoneySlice []float64
- var yoySlice []string
- var yearNum, monthNum int
- var reqStartDate, reqEndDate time.Time
- // 套餐筛选
- if req.ServiceTypes != "" {
- serviceTypes := strings.Split(req.ServiceTypes, ",")
- registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
- if e != nil {
- err = fmt.Errorf("获取合同登记IDs失败, Err: %s", e.Error())
- return
- }
- if len(registerIds) > 0 {
- cond += ` AND b.contract_register_id IN ?`
- pars = append(pars, registerIds)
- } else {
- cond += ` AND 1 = 2`
- }
- }
- 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(latestTime) {
- yearNum = latestTime.Year() - reqStartDate.Year()
- monthNum = int(latestTime.Month() - reqStartDate.Month())
- } else {
- yearNum = reqEndDate.Year() - reqStartDate.Year()
- monthNum = int(reqEndDate.Month() - reqStartDate.Month())
- }
- } else {
- yearNum = latestTime.Year() - earliestTime.Year()
- monthNum = int(latestTime.Month() - 1)
- }
- numMonth := yearNum*12 + monthNum //共存在多少个月
- if numMonth < 0 {
- numMonth = -numMonth
- }
- // 累计值
- 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:", latestTime)
- 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 = latestTime.AddDate(0, i-numMonth, 0).Format("2006-01")
- prevStartDate = latestTime.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(latestTime) {
- endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
- prevEndDateTime = latestTime.AddDate(-1, i-numMonth+1, -1)
- }
- } else {
- endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
- prevEndDateTime = latestTime.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.contract_type = 1 `
- prevCond += ` AND b.contract_type = 1 `
- histrtyCond += ` AND new_company = 1 `
- prevHistoryCond += ` AND new_company = 1 `
- } else if req.CompanyType == 2 {
- cond += ` AND b.contract_type IN (2,3,4) `
- prevCond += ` AND b.contract_type IN (2,3,4) `
- histrtyCond += ` AND new_company = 0 `
- prevHistoryCond += ` AND new_company = 0 `
- } else if req.CompanyType == 3 {
- //未续约收入金额=去年同期总收入金额(新客户+老客户)-当期老客户收入金额
- cond += ` AND b.contract_type IN (2,3,4) `
- //prevCond += ` AND b.contract_type IN (2,3,4) `
- histrtyCond += ` AND new_company = 0 `
- //prevHistoryCond += ` AND new_company = 0 `
- }
- if req.SellerIds != "" {
- sellerIds := strings.Split(req.SellerIds, ",")
- cond += ` AND d.seller_id in ? `
- pars = append(pars, sellerIds)
- prevCond += ` AND d.seller_id in ?`
- prevPars = append(prevPars, sellerIds)
- histrtyCond += ` AND seller_id in ? `
- prevHistoryCond += ` AND seller_id in ? `
- historyPars = append(historyPars, sellerIds)
- prevHistoryPars = append(prevHistoryPars, sellerIds)
- }
- // 套餐筛选
- if req.ServiceTypes != "" {
- serviceTypes := strings.Split(req.ServiceTypes, ",")
- registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
- if e != nil {
- err = fmt.Errorf("获取合同登记IDs失败, Err: %s", e.Error())
- return
- }
- if len(registerIds) > 0 {
- cond += ` AND a.register_id IN ?`
- prevCond += ` AND a.register_id IN ?`
- pars = append(pars, registerIds)
- prevPars = append(prevPars, registerIds)
- } else {
- cond += ` AND 1 = 2`
- prevCond += ` AND 1 = 2`
- }
- }
- //fmt.Println("i:",i)
- //fmt.Println("j:",j)
- {
- //本期
- st := fmt.Sprint(startDate, " 00:00:00")
- ed := fmt.Sprint(endDate, " 23:59:59")
- //校验日期
- //全部走新查询
- cond += ` AND (d.invoice_time BETWEEN ? AND ?)`
- pars = append(pars, st, ed, st, ed)
- summaryIds, e := fms.GetPaymentCensusSummaryDataIds(cond, pars)
- if e != nil {
- return
- }
- // 开票到款金额合计(换算后)
- var amountTotal float64
- if len(summaryIds) > 0 {
- amountCond := `a.id IN ? `
- amountPars := make([]interface{}, 0)
- amountPars = append(amountPars, summaryIds)
- if req.SellerIds != "" {
- sellerIds := strings.Split(req.SellerIds, ",")
- amountCond += `AND ( d.seller_id IN ? AND a.payment_id <> 0 AND d.invoice_time BETWEEN ? AND ?) `
- amountPars = append(amountPars, sellerIds, st, ed)
- } else {
- amountCond += `AND (a.payment_id <> 0 AND d.invoice_time BETWEEN ? AND ?)`
- amountPars = append(amountPars, st, ed, st, ed)
- }
- results, e := fms.GetContractSummaryPaymentIncomeAmount(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
- fmt.Println("result.Amount:", 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)
- if startDateTime.Month() == 12 {
- accumulate = 0
- }
- } 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
- }
- }
- }
- { // 去年同期,用于计算同比值
- prevSt := fmt.Sprint(prevStartDate, " 00:00:00") // 格式化上一年同一天的开始时间
- prevEd := fmt.Sprint(prevEndDate, " 23:59:59") // 格式化上一年同一天的结束时间
- // 校验日期,分段查询
- // 全部走新查询
- prevCond += ` AND (d.invoice_time BETWEEN ? AND ?)` // 查询条件加入新的时间范围
- prevPars = append(prevPars, prevSt, prevEd, prevSt, prevEd) // 添加时间参数到参数列表
- prevSummaryIds, e := fms.GetPaymentCensusSummaryDataIds(prevCond, prevPars) // 获取摘要ID列表
- if e != nil {
- return
- }
- // 开票到款金额合计(换算后)
- var prevAmountTotal float64
- if len(prevSummaryIds) > 0 {
- amountCond := `a.id IN ? ` // 查询条件为ID在给定的摘要ID列表中
- amountPars := make([]interface{}, 0)
- amountPars = append(amountPars, prevSummaryIds) // 将摘要ID列表添加到参数列表
- if req.SellerIds != "" {
- sellerIds := strings.Split(req.SellerIds, ",")
- amountCond += `AND ( d.seller_id IN ? AND a.payment_id <> 0 AND d.invoice_time BETWEEN ? AND ?) ` // 根据卖家ID和发票/支付状态筛选时间范围
- amountPars = append(amountPars, sellerIds, prevSt, prevEd, sellerIds, prevSt, prevEd) // 将卖家ID列表添加到参数列表
- } else {
- amountCond += `AND (a.payment_id <> 0 AND d.invoice_time BETWEEN ? AND ?)` // 根据发票/支付状态筛选时间范围
- amountPars = append(amountPars, prevSt, prevEd, prevSt, prevEd)
- }
- results, e := fms.GetContractSummaryPaymentIncomeAmount(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) // 将累计金额添加到总金额切片中
- if prevStartDateTime.Month() == 12 {
- historyAccumulate = 0 // 如果是去年的12月份,则将历史金额清零
- }
- } 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 // 清零部分历史金额
- }
- }
- 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++
- }
- }
- }
- fmt.Println("prevTotalMoneySlice:", len(prevTotalMoneySlice))
- fmt.Println("totalMoneySlice:", len(totalMoneySlice))
- if req.CompanyType != 3 {
- //计算同比值
- 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])
- totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", totalMoneySlice[i]), 64)
- if prevTotalMoneySlice[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)
- }
- } else {
- // 当筛选条件是”月度“时,并且客户是”未续约“客户,展示柱形图和曲线图
- // 当筛选条件是”季度“、”半年度“、”年度“、”月度统计“时,并且客户是”未续约“时,仅展示柱形图,无曲线图
- // 未续约收入金额=去年同期总收入金额(新客户+老客户)-当期老客户收入金额
- // 移动平均值:若是10月份,计算8月,9月,10月,这三个月的收入金额平均值
- for i := range prevTotalMoneySlice {
- totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", prevTotalMoneySlice[i]-totalMoneySlice[i]), 64)
- var yoy float64
- var yoyStr string
- if i > 1 && req.ListParam == "0" {
- // 前俩月没有
- yoy = (totalMoneySlice[i] + totalMoneySlice[i-1] + totalMoneySlice[i-2]) / 3
- yoyStr = fmt.Sprintf("%.4f", yoy)
- yoySlice = append(yoySlice, yoyStr)
- } else {
- yoySlice = append(yoySlice, "")
- }
- }
- }
- incomeChart.Title = "开票到款统计图"
- incomeChart.Date = dateSlice[:len(totalMoneySlice)]
- 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
- }
- // 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 base.BaseData
- ch := make(chan base.BaseData, 1)
- if req.IncomeType == 0 {
- go getCensusIncomeList(ch, req)
- } else {
- go getPaymentIncomeList(ch, req)
- }
- for v := range ch {
- incomeList = v
- close(ch)
- }
- // 是否导出
- if req.IsExport == 1 {
- ExportIncomeList(c, incomeList.List, req.IncomeType)
- return
- }
- resp.OkData("获取成功", incomeList, c)
- }
- func getPaymentIncomeList(ch chan base.BaseData, req fms.IncomeListReq) (baseData base.BaseData, err error) {
- defer func() {
- if err != nil {
- global.LOG.Error(err)
- if err != utils.ErrNoRow {
- go alarm_msg.SendAlarmMsg("获取业务收入金额统计数据异常,Err:"+err.Error(), 3)
- }
- }
- ch <- baseData
- }()
- var reqStartDate, reqEndDate time.Time
- var startDate, endDate string
- //开始日期
- 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)
- startDate = reqStartDate.Format(utils.FormatDate)
- endDate = reqEndDate.AddDate(0, 1, -1).Format(utils.FormatDate)
- }
- cond := `1 = 1`
- pars := make([]interface{}, 0)
- if req.CompanyType == 1 {
- cond += ` AND b.contract_type = 1 `
- } else if req.CompanyType == 2 {
- cond += ` AND b.contract_type IN (2,3,4) `
- } else if req.CompanyType == 3 {
- //未续约收入金额=去年同期总收入金额(新客户+老客户)-当期老客户收入金额
- cond += ` AND b.contract_type IN (2,3,4) `
- }
- if req.SellerIds != "" {
- sellerIds := strings.Split(req.SellerIds, ",")
- cond += ` AND d.seller_id in ?`
- pars = append(pars, sellerIds)
- }
- // 套餐筛选
- if req.ServiceTypes != "" {
- serviceTypes := strings.Split(req.ServiceTypes, ",")
- registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
- if e != nil {
- err = fmt.Errorf("获取合同登记IDs失败, Err: %s", e.Error())
- return
- }
- if len(registerIds) > 0 {
- cond += ` AND a.register_id IN ?`
- pars = append(pars, registerIds)
- } else {
- cond += ` AND 1 = 2`
- }
- }
- {
- if startDate != "" && endDate != "" {
- st := fmt.Sprint(startDate, " 00:00:00")
- ed := fmt.Sprint(endDate, " 23:59:59")
- cond += ` AND (d.invoice_time BETWEEN ? AND ?)`
- pars = append(pars, st, ed)
- }
- if req.Keyword != "" {
- cond += ` AND b.company_name LIKE ?`
- pars = append(pars, "%"+req.Keyword+"%")
- }
- summaryIds, e := fms.GetPaymentCensusSummaryDataIds(cond, pars)
- if e != nil {
- return
- }
- if len(summaryIds) > 0 {
- amountCond := `a.id IN ? `
- amountPars := make([]interface{}, 0)
- amountPars = append(amountPars, summaryIds)
- if req.SellerIds != "" {
- sellerIds := strings.Split(req.SellerIds, ",")
- amountCond += `AND ( d.seller_id IN ? AND a.payment_id <> 0 ) `
- amountPars = append(amountPars, sellerIds)
- } else {
- amountCond += `AND (a.payment_id <> 0)`
- }
- page := new(base.Page)
- page.SetPageSize(req.PageSize)
- page.SetCurrent(req.Current)
- if req.IsExport == 1 {
- page.SetPageSize(10000)
- page.SetCurrent(1)
- }
- if req.SortType == "asc" {
- page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: true})
- } else {
- page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: false})
- }
- results, total, e := fms.GetContractSummaryPaymentIncomeAmountPage(amountCond, amountPars, page)
- if e != nil {
- err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
- return
- }
- // 货币列表
- currencyOB := new(fms.CurrencyUnit)
- currencyCond := `enable = 1`
- currencyPars := make([]interface{}, 0)
- currencyList, e := currencyOB.List(currencyCond, currencyPars)
- if e != nil {
- err = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
- return
- }
- unitMap := make(map[string]string)
- for i := range currencyList {
- unitMap[currencyList[i].Code] = currencyList[i].UnitName
- }
- respItems := make([]*fms.IncomeSummaryRespItem, 0)
- for _, v := range results {
- respItem := &fms.IncomeSummaryRespItem{
- CompanyName: v.CompanyName,
- ContractType: v.ContractType,
- InvoiceDate: v.InvoiceDate.Format(utils.FormatDate),
- Amount: v.Amount,
- SellerName: v.SellerName,
- FinalSellerId: v.FinalSellerId,
- OriginAmount: v.OriginAmount,
- UnitName: unitMap[v.CurrencyUnit],
- ServicesName: v.ServicesName,
- }
- respItems = append(respItems, respItem)
- }
- page.SetTotal(total)
- baseData.SetPage(page)
- baseData.SetList(respItems)
- }
- }
- return
- }
- func getCensusIncomeList(ch chan base.BaseData, req fms.IncomeListReq) (baseData base.BaseData, err error) {
- defer func() {
- if err != nil {
- global.LOG.Error(err)
- if err != utils.ErrNoRow {
- go alarm_msg.SendAlarmMsg("获取业务收入金额统计数据异常,Err:"+err.Error(), 3)
- }
- }
- ch <- baseData
- }()
- var reqStartDate, reqEndDate time.Time
- historyTime, _ := time.Parse(utils.FormatDate, "2023-04-01")
- // 套餐筛选
- if req.ServiceTypes != "" {
- // 勾选套餐筛选时忽略导入的历史数据
- if req.StartDate == "" {
- req.StartDate = "2023-04"
- req.EndDate = "3023-04"
- } else {
- startDateTime, _ := time.Parse(utils.FormatMonth, req.StartDate)
- if startDateTime.Before(historyTime) {
- req.StartDate = "2023-04"
- }
- }
- }
- 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)
- }
- //timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
- var startDate, endDate string
- //开始日期
- if req.StartDate != "" && req.EndDate != "" {
- startDate = reqStartDate.Format("2006-01")
- startDate = fmt.Sprint(startDate, "-01")
- }
- startDateTime, _ := time.Parse(utils.FormatDate, startDate)
- //结束日期
- if req.StartDate != "" && req.EndDate != "" {
- endDate = reqEndDate.AddDate(0, 1, -1).Format(utils.FormatDate)
- }
- cond := `1 = 1`
- histrtyCond := `1 = 1`
- pars := make([]interface{}, 0)
- historyPars := make([]interface{}, 0)
- if req.CompanyType == 1 {
- cond += ` AND b.contract_type = 1 `
- histrtyCond += ` AND new_company = 1 `
- } else if req.CompanyType == 2 {
- cond += ` AND b.contract_type IN (2,3,4) `
- histrtyCond += ` AND new_company = 0 `
- } else if req.CompanyType == 3 {
- //未续约收入金额=去年同期总收入金额(新客户+老客户)-当期老客户收入金额
- cond += ` AND b.contract_type IN (2,3,4) `
- histrtyCond += ` 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)
- histrtyCond += ` AND seller_id in ? `
- historyPars = append(historyPars, sellerIds)
- }
- // 套餐筛选
- if req.ServiceTypes != "" {
- serviceTypes := strings.Split(req.ServiceTypes, ",")
- registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
- if e != nil {
- err = fmt.Errorf("获取合同登记IDs失败, Err: %s", e.Error())
- return
- }
- if len(registerIds) > 0 {
- cond += ` AND a.register_id IN ?`
- pars = append(pars, registerIds)
- } else {
- cond += ` AND 1 = 2`
- }
- }
- {
- page := new(base.Page)
- page.SetPageSize(req.PageSize)
- page.SetCurrent(req.Current)
- if req.IsExport == 1 {
- page.SetPageSize(10000)
- page.SetCurrent(1)
- }
- //校验日期,分段查询
- st := fmt.Sprint(startDate, " 00:00:00")
- ed := fmt.Sprint(endDate, " 23:59:59")
- if req.StartDate != "" && req.EndDate != "" {
- if reqEndDate.Before(historyTime) || reqEndDate.Equal(historyTime) {
- //旧查询
- histrtyCond += ` AND (invoice_time BETWEEN ? AND ? )`
- historyPars = append(historyPars, st, ed)
- if req.SortType == "asc" {
- page.AddOrderItem(base.OrderItem{Column: "invoice_time", Asc: true})
- } else {
- page.AddOrderItem(base.OrderItem{Column: "invoice_time", Asc: false})
- }
- if req.Keyword != "" {
- histrtyCond += ` AND company_name LIKE ? `
- historyPars = append(historyPars, "%"+req.Keyword+"%")
- }
- results, total, e := fms.GetIncomeHistoryPage(histrtyCond, historyPars, page)
- if e != nil {
- err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
- return
- }
- // 货币列表
- currencyOB := new(fms.CurrencyUnit)
- currencyCond := `enable = 1`
- currencyPars := make([]interface{}, 0)
- currencyList, e := currencyOB.List(currencyCond, currencyPars)
- if e != nil {
- err = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
- return
- }
- unitMap := make(map[string]string)
- for i := range currencyList {
- unitMap[currencyList[i].Code] = currencyList[i].UnitName
- }
- respItems := make([]*fms.IncomeSummaryRespItem, 0)
- for _, v := range results {
- respItem := &fms.IncomeSummaryRespItem{
- CompanyName: v.CompanyName,
- ContractType: v.ContractType,
- InvoiceDate: v.InvoiceDate.Format(utils.FormatDate),
- Amount: v.Amount,
- SellerName: v.SellerName,
- FinalSellerId: v.FinalSellerId,
- OriginAmount: v.OriginAmount,
- UnitName: unitMap[v.CurrencyUnit],
- ServicesName: v.ServicesName,
- }
- respItems = append(respItems, respItem)
- }
- page.SetTotal(total)
- baseData.SetPage(page)
- baseData.SetList(respItems)
- return
- } else if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
- //全部走新查询
- 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
- }
- if len(summaryIds) > 0 {
- amountCond := `a.id IN ? `
- amountPars := make([]interface{}, 0)
- amountPars = append(amountPars, summaryIds)
- if req.SellerIds != "" {
- sellerIds := strings.Split(req.SellerIds, ",")
- amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
- amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
- amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
- } else {
- amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
- amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
- amountPars = append(amountPars, st, ed, st, ed)
- }
- if req.SortType == "asc" {
- page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: true})
- } else {
- page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: false})
- }
- if req.Keyword != "" {
- amountCond += ` AND c.company_name LIKE ?`
- amountPars = append(amountPars, "%"+req.Keyword+"%")
- }
- results, total, e := fms.GetContractSummaryIncomeAmountPage(amountCond, amountPars, page)
- if e != nil {
- err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
- return
- }
- // 货币列表
- currencyOB := new(fms.CurrencyUnit)
- currencyCond := `enable = 1`
- currencyPars := make([]interface{}, 0)
- currencyList, e := currencyOB.List(currencyCond, currencyPars)
- if e != nil {
- err = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
- return
- }
- unitMap := make(map[string]string)
- for i := range currencyList {
- unitMap[currencyList[i].Code] = currencyList[i].UnitName
- }
- respItems := make([]*fms.IncomeSummaryRespItem, 0)
- for _, v := range results {
- respItem := &fms.IncomeSummaryRespItem{
- CompanyName: v.CompanyName,
- ContractType: v.ContractType,
- InvoiceDate: v.InvoiceDate.Format(utils.FormatDate),
- Amount: v.Amount,
- SellerName: v.SellerName,
- FinalSellerId: v.FinalSellerId,
- OriginAmount: v.OriginAmount,
- UnitName: unitMap[v.CurrencyUnit],
- ServicesName: v.ServicesName,
- }
- respItems = append(respItems, respItem)
- }
- page.SetTotal(total)
- baseData.SetPage(page)
- baseData.SetList(respItems[:])
- return
- }
- } else {
- resultList := make([]*fms.IncomeSummaryItem, 0)
- //旧查询
- histrtyCond += ` AND (invoice_time BETWEEN ? AND ? )`
- historyPars = append(historyPars, st, ed)
- if req.Keyword != "" {
- histrtyCond += ` AND company_name LIKE ?`
- historyPars = append(historyPars, "%"+req.Keyword+"%")
- }
- results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
- if e != nil {
- err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
- return
- }
- resultList = append(resultList, results...)
- //新查询
- cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
- pars = append(pars, "2023-04-01 00:00:00", ed, "2023-04-01 00:00:00", ed)
- summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
- if e != nil {
- return
- }
- if len(summaryIds) > 0 {
- amountCond := `a.id IN ? `
- amountPars := make([]interface{}, 0)
- amountPars = append(amountPars, summaryIds)
- if req.SellerIds != "" {
- sellerIds := strings.Split(req.SellerIds, ",")
- amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
- amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
- amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
- } else {
- amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
- amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
- amountPars = append(amountPars, st, ed, st, ed)
- }
- if req.Keyword != "" {
- amountCond += ` AND c.company_name LIKE ?`
- amountPars = append(amountPars, "%"+req.Keyword+"%")
- }
- results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
- if e != nil {
- err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
- return
- }
- resultList = append(resultList, results...)
- }
- // 货币列表
- currencyOB := new(fms.CurrencyUnit)
- currencyCond := `enable = 1`
- currencyPars := make([]interface{}, 0)
- currencyList, e := currencyOB.List(currencyCond, currencyPars)
- if e != nil {
- err = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
- return
- }
- unitMap := make(map[string]string)
- for i := range currencyList {
- unitMap[currencyList[i].Code] = currencyList[i].UnitName
- }
- respItems := make([]*fms.IncomeSummaryRespItem, 0)
- for _, v := range resultList {
- respItem := &fms.IncomeSummaryRespItem{
- CompanyName: v.CompanyName,
- ContractType: v.ContractType,
- InvoiceDate: v.InvoiceDate.Format(utils.FormatDate),
- Amount: v.Amount,
- SellerName: v.SellerName,
- FinalSellerId: v.FinalSellerId,
- OriginAmount: v.OriginAmount,
- UnitName: unitMap[v.CurrencyUnit],
- ServicesName: v.ServicesName,
- }
- respItems = append(respItems, respItem)
- }
- page.SetTotal(int64(len(respItems)))
- baseData.SetPage(page)
- start := (page.GetCurrent() - 1) * page.PageSize
- end := start + page.PageSize
- if end > int64(len(respItems)) {
- end = int64(len(respItems))
- }
- baseData.SetList(respItems[start:end])
- }
- } else {
- resultList := make(fms.IncomeSummaryItemList, 0)
- //旧查询
- if req.Keyword != "" {
- histrtyCond += ` AND company_name LIKE ?`
- historyPars = append(pars, "%"+req.Keyword+"%")
- }
- results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
- if e != nil {
- err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
- return
- }
- resultList = append(resultList, results...)
- //新查询
- st = "2023-04-01 00:00:00"
- cond += ` AND ((c.invoice_time > ?) or (d.invoice_time > ?))`
- pars = append(pars, st, st)
- summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
- if e != nil {
- err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
- return
- }
- if len(summaryIds) > 0 {
- amountCond := `a.id IN ? `
- amountPars := make([]interface{}, 0)
- amountPars = append(amountPars, summaryIds)
- if req.SellerIds != "" {
- sellerIds := strings.Split(req.SellerIds, ",")
- amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time > ?)`
- amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time > ? )) `
- amountPars = append(amountPars, sellerIds, st, sellerIds, st)
- } else {
- amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time > ?)`
- amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time > ?))`
- amountPars = append(amountPars, st, st)
- }
- if req.Keyword != "" {
- amountCond += ` AND c.company_name LIKE ?`
- amountPars = append(amountPars, "%"+req.Keyword+"%")
- }
- results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
- if e != nil {
- err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
- return
- }
- resultList = append(resultList, results...)
- }
- if req.SortType == "asc" {
- sort.Sort(resultList)
- } else {
- sort.Sort(sort.Reverse(resultList))
- }
- // 货币列表
- currencyOB := new(fms.CurrencyUnit)
- currencyCond := `enable = 1`
- currencyPars := make([]interface{}, 0)
- currencyList, e := currencyOB.List(currencyCond, currencyPars)
- if e != nil {
- err = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
- return
- }
- unitMap := make(map[string]string)
- for i := range currencyList {
- unitMap[currencyList[i].Code] = currencyList[i].UnitName
- }
- respItems := make([]*fms.IncomeSummaryRespItem, 0)
- for _, v := range resultList {
- respItem := &fms.IncomeSummaryRespItem{
- CompanyName: v.CompanyName,
- ContractType: v.ContractType,
- InvoiceDate: v.InvoiceDate.Format(utils.FormatDate),
- Amount: v.Amount,
- SellerName: v.SellerName,
- FinalSellerId: v.FinalSellerId,
- OriginAmount: v.OriginAmount,
- UnitName: unitMap[v.CurrencyUnit],
- ServicesName: v.ServicesName,
- }
- respItems = append(respItems, respItem)
- }
- page.SetTotal(int64(len(respItems)))
- baseData.SetPage(page)
- start := (page.GetCurrent() - 1) * page.PageSize
- end := start + page.PageSize
- if end > int64(len(respItems)) {
- end = int64(len(respItems))
- }
- baseData.SetList(respItems[start:end])
- }
- }
- return
- }
- // ExportIncomeList 导出业务收入统计列表
- func ExportIncomeList(c *gin.Context, results interface{}, incomeType int) {
- list := results.([]*fms.IncomeSummaryRespItem)
- // 生成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 := make([]string, 0)
- if incomeType == 0 {
- rowTitle = []string{"客户名称", "新客户(1)", "开票日期", "开票金额", "金额单位", "开票金额(换算后)", "销售名称", "套餐名称"}
- } else {
- rowTitle = []string{"客户名称", "新客户(1)", "到款日期", "到款金额", "金额单位", "到款金额(换算后)", "销售名称", "套餐名称"}
- }
- titleRow := sheet.AddRow()
- for i := range rowTitle {
- v := titleRow.AddCell()
- v.SetString(rowTitle[i])
- v.SetStyle(style)
- }
- incomeSummaryItemList := make([]*fms.IncomeSummaryRespItem, 0)
- incomeSummaryItemList = list
- //sort.Sort(incomeSummaryItemList)
- // 填充数据
- for _, v := range incomeSummaryItemList {
- dataRow := sheet.AddRow()
- dataRow.AddCell().SetString(v.CompanyName) // 客户名称
- newCompany := 0
- if v.ContractType == 1 {
- newCompany = 1
- }
- dataRow.AddCell().SetString(strconv.Itoa(newCompany)) // 新客户
- dataRow.AddCell().SetString(v.InvoiceDate) // 开票到款日期
- dataRow.AddCell().SetString(fmt.Sprintf("%.2f", v.OriginAmount)) // 开票到款金额
- dataRow.AddCell().SetString(v.UnitName) // 金额单位
- dataRow.AddCell().SetString(fmt.Sprintf("%.2f", v.Amount)) // 开票到款金额 换算后
- dataRow.AddCell().SetString(v.SellerName) // 销售员
- dataRow.AddCell().SetString(v.ServicesName) // 套餐名称
- }
- // 输出文件
- 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)
- }
|