invoice_payment.go 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  1. package census
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "github.com/go-playground/validator/v10"
  7. "github.com/tealeg/xlsx"
  8. "hongze/fms_api/controller/resp"
  9. "hongze/fms_api/global"
  10. "hongze/fms_api/models"
  11. "hongze/fms_api/models/base"
  12. "hongze/fms_api/models/fms"
  13. "hongze/fms_api/services/alarm_msg"
  14. fmsService "hongze/fms_api/services/fms"
  15. "hongze/fms_api/utils"
  16. "net/http"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. )
  23. // InvoicePaymentController 商品到款统计
  24. type InvoicePaymentController struct{}
  25. // List2 原版(已废弃)
  26. //func (ct *InvoicePaymentController) List2(c *gin.Context) {
  27. // var req fms.InvoicePaymentCensusListReq
  28. // if e := c.BindQuery(&req); e != nil {
  29. // err, ok := e.(validator.ValidationErrors)
  30. // if !ok {
  31. // resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  32. // return
  33. // }
  34. // resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  35. // return
  36. // }
  37. //
  38. // cond := `1 = 1`
  39. // pars := make([]interface{}, 0)
  40. // // 合同编号/客户姓名/销售
  41. // if req.Keyword != "" {
  42. // kw := "%" + req.Keyword + "%"
  43. // cond += ` AND b.company_name LIKE ? OR a.seller_name LIKE ?`
  44. // pars = append(pars, kw, kw)
  45. // }
  46. // if req.SellGroupId > 0 {
  47. // cond += ` AND a.seller_group_id = ?`
  48. // pars = append(pars, req.SellGroupId)
  49. // }
  50. // // 套餐筛选
  51. // if req.ServiceType != 0 {
  52. // registerIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
  53. // if e != nil {
  54. // resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  55. // return
  56. // }
  57. // if len(registerIds) > 0 {
  58. // cond += ` AND b.contract_register_id IN ?`
  59. // pars = append(pars, registerIds)
  60. // } else {
  61. // cond += ` AND 1 = 2`
  62. // }
  63. // }
  64. // // 开票到款日期
  65. // if req.TimeType > 0 && req.StartDate != "" && req.EndDate != "" {
  66. // st := fmt.Sprint(req.StartDate, " 00:00:00")
  67. // ed := fmt.Sprint(req.EndDate, " 23:59:59")
  68. // cond += ` AND a.invoice_type = ? AND (a.invoice_time BETWEEN ? AND ?)`
  69. // pars = append(pars, req.TimeType, st, ed)
  70. // }
  71. // // 已开票
  72. // if req.HasInvoice == 1 && req.HasPayment == 0 {
  73. // cond += ` AND a.invoice_type = 1`
  74. // }
  75. // // 已到款
  76. // if req.HasInvoice == 0 && req.HasPayment == 1 {
  77. // cond += ` AND a.invoice_type = 2`
  78. // }
  79. //
  80. // page := new(base.Page)
  81. // page.SetPageSize(req.PageSize)
  82. // page.SetCurrent(req.Current)
  83. // page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  84. // page.AddOrderItem(base.OrderItem{Column: "b.contract_register_id", Asc: true})
  85. // if req.IsExport == 1 {
  86. // page.SetPageSize(10000)
  87. // page.SetCurrent(1)
  88. // }
  89. //
  90. // list, allRegisterIds, e := fms.GetInvoicePaymentCensusPageList(page, cond, pars)
  91. // if e != nil {
  92. // resp.FailMsg("获取失败", "获取商品到款统计列表失败, Err: "+e.Error(), c)
  93. // return
  94. // }
  95. // total := int64(len(allRegisterIds))
  96. // registerIds := make([]int, 0)
  97. // for i := range list {
  98. // registerIds = append(registerIds, list[i].ContractRegisterId)
  99. // }
  100. //
  101. // results := new(fms.InvoicePaymentCensusResp)
  102. // if len(registerIds) > 0 {
  103. // // 获取开票到款列表
  104. // ivCond := `contract_register_id IN ?`
  105. // ivPars := make([]interface{}, 0)
  106. // ivPars = append(ivPars, registerIds)
  107. // iv := new(fms.ContractInvoice)
  108. // invoiceList, e := iv.List(ivCond, ivPars, "")
  109. // if e != nil {
  110. // resp.FailMsg("获取失败", "获取开票到款列表失败, Err: "+e.Error(), c)
  111. // return
  112. // }
  113. // // 取出开票、到款
  114. // invoiceMap := make(map[int][]*fms.ContractInvoice, 0)
  115. // paymentMap := make(map[int][]*fms.ContractInvoice, 0)
  116. // paymentIds := make([]int, 0)
  117. // for i := range invoiceList {
  118. // if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
  119. // invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoice, 0)
  120. // }
  121. // if paymentMap[invoiceList[i].ContractRegisterId] == nil {
  122. // paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoice, 0)
  123. // }
  124. // if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  125. // invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  126. // }
  127. // if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  128. // paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  129. // paymentIds = append(paymentIds, invoiceList[i].ContractInvoiceId)
  130. // }
  131. // }
  132. //
  133. // // 合同套餐
  134. // contractServiceCond := `contract_register_id IN ?`
  135. // contractServicePars := make([]interface{}, 0)
  136. // contractServicePars = append(contractServicePars, registerIds)
  137. // contractServiceOB := new(fms.ContractService)
  138. // contractServiceList, e := contractServiceOB.List(contractServiceCond, contractServicePars)
  139. // if e != nil {
  140. // resp.FailMsg("获取失败", "获取合同套餐列表失败, Err:"+e.Error(), c)
  141. // return
  142. // }
  143. // contractServiceMap := make(map[int][]*fms.ContractService, 0)
  144. // servicesNameMap := make(map[int][]string, 0)
  145. // for i := range contractServiceList {
  146. // if contractServiceMap[contractServiceList[i].ContractRegisterId] == nil {
  147. // contractServiceMap[contractServiceList[i].ContractRegisterId] = make([]*fms.ContractService, 0)
  148. // }
  149. // contractServiceMap[contractServiceList[i].ContractRegisterId] = append(contractServiceMap[contractServiceList[i].ContractRegisterId], contractServiceList[i])
  150. // servicesNameMap[contractServiceList[i].ContractRegisterId] = append(servicesNameMap[contractServiceList[i].ContractRegisterId], contractServiceList[i].Title)
  151. // }
  152. //
  153. // // 到款套餐分配
  154. // serviceAmountMap := make(map[int][]*fms.ContractPaymentServiceAmount, 0)
  155. // if len(paymentIds) > 0 {
  156. // serviceAmountCond := `contract_payment_id IN ?`
  157. // serviceAmountPars := make([]interface{}, 0)
  158. // serviceAmountPars = append(serviceAmountPars, paymentIds)
  159. // serviceAmountOB := new(fms.ContractPaymentServiceAmount)
  160. // serviceAmountList, e := serviceAmountOB.List(serviceAmountCond, serviceAmountPars)
  161. // if e != nil {
  162. // resp.FailMsg("获取失败", "获取到款套餐分配列表失败, Err:"+e.Error(), c)
  163. // return
  164. // }
  165. // for i := range serviceAmountList {
  166. // if serviceAmountMap[serviceAmountList[i].ContractRegisterId] == nil {
  167. // serviceAmountMap[serviceAmountList[i].ContractRegisterId] = make([]*fms.ContractPaymentServiceAmount, 0)
  168. // }
  169. // serviceAmountMap[serviceAmountList[i].ContractRegisterId] = append(serviceAmountMap[serviceAmountList[i].ContractRegisterId], serviceAmountList[i])
  170. // }
  171. // }
  172. //
  173. // // 整合响应数据
  174. // respList := make([]*fms.InvoicePaymentCensusItem, 0)
  175. // for i := range list {
  176. // v := new(fms.InvoicePaymentCensusItem)
  177. // v.ContractRegisterId = list[i].ContractRegisterId
  178. // v.CompanyName = list[i].CompanyName
  179. // v.NewCompany = list[i].NewCompany
  180. // v.StartDate = list[i].StartDate.Format(utils.FormatDate)
  181. // v.EndDate = list[i].EndDate.Format(utils.FormatDate)
  182. // svList := servicesNameMap[list[i].ContractRegisterId]
  183. // v.ServicesName = strings.Join(svList, ",")
  184. // // 格式化(合并)开票到款数据
  185. // v.InvoicePaymentList = fmsService.MergeInvoiceList2InvoicePaymentCensusInfo(invoiceMap[list[i].ContractRegisterId], paymentMap[list[i].ContractRegisterId],
  186. // contractServiceMap[list[i].ContractRegisterId], serviceAmountMap[list[i].ContractRegisterId])
  187. // respList = append(respList, v)
  188. // }
  189. //
  190. // // 开票到款金额合计(换算后)
  191. // amountTotalCond := `contract_register_id IN ?`
  192. // amountTotalPars := make([]interface{}, 0)
  193. // amountTotalPars = append(amountTotalPars, allRegisterIds)
  194. // amountTotalList, e := fms.GetContractInvoiceAmountTotal(amountTotalCond, amountTotalPars)
  195. // if e != nil {
  196. // resp.FailMsg("获取失败", "获取开票到款金额合计失败, Err:"+e.Error(), c)
  197. // return
  198. // }
  199. // amountTotalMap := make(map[int]float64)
  200. // for i := range amountTotalList {
  201. // amountTotalMap[amountTotalList[i].InvoiceType] = amountTotalList[i].TotalAmount
  202. // }
  203. // invoiceTotal, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amountTotalMap[fms.ContractInvoiceTypeMake]), 64)
  204. // paymentTotal, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amountTotalMap[fms.ContractInvoiceTypePay]), 64)
  205. //
  206. // // 分币种金额统计
  207. // currencyOB := new(fms.CurrencyUnit)
  208. // currencyCond := `enable = 1`
  209. // currencyPars := make([]interface{}, 0)
  210. // currencyList, e := currencyOB.List(currencyCond, currencyPars)
  211. // if e != nil {
  212. // resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  213. // return
  214. // }
  215. // unitMap := make(map[string]string)
  216. // invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  217. // paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  218. // for i := range currencyList {
  219. // unitMap[currencyList[i].Code] = currencyList[i].UnitName
  220. // invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  221. // Name: currencyList[i].Name,
  222. // UnitName: currencyList[i].UnitName,
  223. // Code: currencyList[i].Code,
  224. // FlagImg: currencyList[i].FlagImg,
  225. // })
  226. // paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  227. // Name: currencyList[i].Name,
  228. // UnitName: currencyList[i].UnitName,
  229. // Code: currencyList[i].Code,
  230. // FlagImg: currencyList[i].FlagImg,
  231. // })
  232. // }
  233. // sumList, e := fms.GetInvoiceListCurrencySum(amountTotalCond, amountTotalPars, "currency_unit, invoice_type")
  234. // if e != nil {
  235. // resp.FailMsg("获取失败", "获取商品到款统计货币合计金额失败, Err: "+e.Error(), c)
  236. // return
  237. // }
  238. // invoiceSumMap := make(map[string]float64)
  239. // paymentSumMap := make(map[string]float64)
  240. // for i := range sumList {
  241. // if sumList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  242. // invoiceSumMap[sumList[i].CurrencyUnit] = sumList[i].OriginAmountTotal
  243. // continue
  244. // }
  245. // if sumList[i].InvoiceType == fms.ContractInvoiceTypePay {
  246. // paymentSumMap[sumList[i].CurrencyUnit] = sumList[i].OriginAmountTotal
  247. // }
  248. // }
  249. // for i := range invoiceCurrencyTotals {
  250. // a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
  251. // invoiceCurrencyTotals[i].Amount = a
  252. // }
  253. // for i := range paymentCurrencyTotals {
  254. // a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  255. // paymentCurrencyTotals[i].Amount = a
  256. // }
  257. //
  258. // results.DataList = respList
  259. // results.InvoiceTotal = invoiceTotal
  260. // results.PaymentTotal = paymentTotal
  261. // results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  262. // results.PaymentCurrencyTotal = paymentCurrencyTotals
  263. // }
  264. //
  265. // // 是否导出
  266. // if req.IsExport == 1 {
  267. // ExportInvoicePaymentCensusList(c, results)
  268. // return
  269. // }
  270. // page.SetTotal(total)
  271. // baseData := new(base.BaseData)
  272. // baseData.SetPage(page)
  273. // baseData.SetList(results)
  274. // resp.OkData("获取成功", baseData, c)
  275. //}
  276. // ExportInvoicePaymentCensusList 导出商品到款统计列表
  277. func ExportInvoicePaymentCensusList(c *gin.Context, results *fms.InvoicePaymentCensusResp) {
  278. list := results.DataList
  279. if len(list) == 0 {
  280. resp.Fail("列表数据为空", c)
  281. return
  282. }
  283. // 生成Excel文件
  284. xlsxFile := xlsx.NewFile()
  285. style := xlsx.NewStyle()
  286. alignment := xlsx.Alignment{
  287. Horizontal: "center",
  288. Vertical: "center",
  289. WrapText: true,
  290. }
  291. style.Alignment = alignment
  292. style.ApplyAlignment = true
  293. sheet, err := xlsxFile.AddSheet("商品到款统计")
  294. if err != nil {
  295. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  296. return
  297. }
  298. _ = sheet.SetColWidth(1, 1, 30)
  299. _ = sheet.SetColWidth(3, 3, 30)
  300. // 前三行-开票金额合计
  301. rowA := sheet.AddRow()
  302. cellAA := rowA.AddCell()
  303. cellAA.SetString(fmt.Sprintf("已开票合计金额(换算后):%.2f(元)", results.InvoiceTotal))
  304. rowBData := "已开票金额:"
  305. for _, v := range results.InvoiceCurrencyTotal {
  306. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  307. }
  308. rowB := sheet.AddRow()
  309. rowB.AddCell().SetString(rowBData)
  310. sheet.AddRow()
  311. // 四至六-到款金额合计
  312. rowD := sheet.AddRow()
  313. cellDA := rowD.AddCell()
  314. cellDA.SetString(fmt.Sprintf("已到款合计金额(换算后):%.2f(元)", results.PaymentTotal))
  315. rowEData := "已到款金额:"
  316. for _, v := range results.PaymentCurrencyTotal {
  317. rowEData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  318. }
  319. rowE := sheet.AddRow()
  320. rowE.AddCell().SetString(rowEData)
  321. sheet.AddRow()
  322. // 表头, 套餐动态获取
  323. rowTitle := []string{"序号", "客户名称", "是否新客户", "合同有效期", "开票日", "开票金额", "到款日", "到款金额", "付款方式", "销售",
  324. "销售组别", "销售类型"}
  325. serviceTempCond := ``
  326. serviceTempPars := make([]interface{}, 0)
  327. serviceTempOB := new(fms.ContractServiceTemplate)
  328. serviceTempList, e := serviceTempOB.List(serviceTempCond, serviceTempPars)
  329. if e != nil {
  330. resp.FailData("获取套餐模板列表失败", "Err:"+e.Error(), c)
  331. return
  332. }
  333. serviceTempListMap := make(map[int]*fms.ContractServiceTemplate)
  334. var serviceTempShow []*fms.ContractServiceTemplate
  335. for i := range serviceTempList {
  336. serviceTempListMap[serviceTempList[i].ServiceTemplateId] = serviceTempList[i]
  337. }
  338. for i := range serviceTempList {
  339. if serviceTempList[i].ProductId == 1 {
  340. rowTitle = append(rowTitle, serviceTempList[i].Title)
  341. serviceTempShow = append(serviceTempShow, serviceTempList[i])
  342. } else if serviceTempList[i].ProductId == 2 {
  343. if serviceTempList[i].Title == "行业套餐" || serviceTempList[i].Title == "权益大套餐" || (serviceTempList[i].Title == "策略" && serviceTempListMap[serviceTempList[i].Pid].Pid == 0) {
  344. } else if serviceTempList[i].Title == "医药" || serviceTempList[i].Title == "消费" || serviceTempList[i].Title == "科技" || serviceTempList[i].Title == "智造" {
  345. } else {
  346. serviceTempShow = append(serviceTempShow, serviceTempList[i])
  347. }
  348. if serviceTempList[i].Title == "行业套餐" || serviceTempList[i].Title == "45万" || serviceTempList[i].Title == "70万" {
  349. continue
  350. }
  351. if serviceTempList[i].Pid > 0 && serviceTempListMap[serviceTempList[i].Pid].Pid > 0 {
  352. continue
  353. }
  354. rowTitle = append(rowTitle, serviceTempList[i].Title)
  355. }
  356. }
  357. hi := 0
  358. insertHi := 0
  359. titleRow := sheet.AddRow()
  360. for i := range rowTitle {
  361. v := titleRow.AddCell()
  362. v.SetString(rowTitle[i])
  363. v.SetStyle(style)
  364. if rowTitle[i] != "权益大套餐" && rowTitle[i] != "医药" && rowTitle[i] != "消费" && rowTitle[i] != "科技" && rowTitle[i] != "智造" {
  365. v.VMerge = 1
  366. hi++
  367. } else {
  368. if insertHi == 0 {
  369. insertHi = hi
  370. }
  371. v.HMerge = 1
  372. titleRow.AddCell().SetString("")
  373. }
  374. }
  375. // 新增一行放主观和客观
  376. specialRow := sheet.AddRow()
  377. for i := 0; i < hi; i++ {
  378. if i == insertHi {
  379. v1 := specialRow.AddCell()
  380. v1.SetString("45万")
  381. v1.SetStyle(style)
  382. v1 = specialRow.AddCell()
  383. v1.SetString("70万")
  384. v1.SetStyle(style)
  385. for j := 0; j < 8; j++ {
  386. if j%2 == 0 {
  387. v1 = specialRow.AddCell()
  388. v1.SetString("主观")
  389. v1.SetStyle(style)
  390. } else {
  391. v1 = specialRow.AddCell()
  392. v1.SetString("客观")
  393. v1.SetStyle(style)
  394. }
  395. }
  396. } else {
  397. v := specialRow.AddCell()
  398. v.SetString("")
  399. }
  400. }
  401. newCompanyMap := map[int]string{0: "/", 1: "是" , 2: "否"}
  402. sellerTypeMap := map[int]string{1: "FICC销售", 2: "权益销售"}
  403. for k, v := range list {
  404. dataRow := sheet.AddRow()
  405. // 前四个单元格根据每行开票到款条数向下合并
  406. l := len(v.InvoicePaymentList)
  407. mergeRowNum := l - 1
  408. // 序号
  409. sortNum := k + 1
  410. colA := dataRow.AddCell()
  411. colA.VMerge = mergeRowNum
  412. colA.SetString(fmt.Sprint(sortNum))
  413. // 客户名称
  414. colB := dataRow.AddCell()
  415. colB.VMerge = mergeRowNum
  416. colB.SetString(v.CompanyName)
  417. // 是否新客户
  418. colC := dataRow.AddCell()
  419. colC.VMerge = mergeRowNum
  420. colC.SetString(newCompanyMap[v.ContractType])
  421. // 合同有效期
  422. colD := dataRow.AddCell()
  423. colD.VMerge = mergeRowNum
  424. colD.SetString(fmt.Sprint(v.StartDate, "至", v.EndDate))
  425. // 开票到款信息
  426. for k2, v2 := range v.InvoicePaymentList {
  427. rowData := []string{
  428. v2.InvoiceDate, // 开票日
  429. fmt.Sprint(v2.InvoiceAmount), // 开票金额
  430. v2.PaymentDate, // 到款日
  431. fmt.Sprint(v2.PaymentAmount), // 到款金额
  432. fms.ContractPaymentPayTypeNameMap[v2.PayType], // 付款方式
  433. v2.SellerName, // 销售
  434. v2.SellerGroupName, // 组别
  435. sellerTypeMap[v2.SellerType], // 销售类型
  436. }
  437. // 套餐金额信息
  438. serviceTempShowAmount := make(map[int]string)
  439. for i := range serviceTempShow {
  440. for s2 := range v2.ServiceAmountList {
  441. item := v2.ServiceAmountList[s2]
  442. if item.ServiceTemplateId == serviceTempShow[i].ServiceTemplateId {
  443. serviceTempShowAmount[serviceTempShow[i].ServiceTemplateId] = fmt.Sprint(item.Amount)
  444. break
  445. } else if serviceTempShow[i].Pid == item.ServiceTemplateId {
  446. serviceTempShowAmount[serviceTempShow[i].ServiceTemplateId] = fmt.Sprint(item.Amount / 2)
  447. break
  448. }
  449. }
  450. }
  451. for i := range serviceTempShow {
  452. sa := ""
  453. if am, ok := serviceTempShowAmount[serviceTempShow[i].ServiceTemplateId]; ok {
  454. sa = am
  455. }
  456. rowData = append(rowData, sa)
  457. }
  458. // 首行开票到款
  459. if k2 == 0 {
  460. for i := range rowData {
  461. dataRow.AddCell().SetString(rowData[i])
  462. }
  463. continue
  464. }
  465. // 其他行开票到款, 加四列空的单元格用于合并
  466. dataRowExtra := sheet.AddRow()
  467. for i := 0; i < 4; i++ {
  468. dataRowExtra.AddCell()
  469. }
  470. for i := range rowData {
  471. dataRowExtra.AddCell().SetString(rowData[i])
  472. }
  473. }
  474. }
  475. // 输出文件
  476. var buffer bytes.Buffer
  477. _ = xlsxFile.Write(&buffer)
  478. content := bytes.NewReader(buffer.Bytes())
  479. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  480. fileName := "商品到款统计_" + randStr + ".xlsx"
  481. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  482. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  483. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  484. }
  485. // List
  486. // @Title 商品到款统计列表
  487. // @Description 商品到款统计列表
  488. // @Param Keyword query string false "关键词"
  489. // @Param SellGroupId query int false "销售组别ID"
  490. // @Param ServiceType query int false "套餐类型"
  491. // @Param StartDate query string false "合同开始日期"
  492. // @Param EndDate query string false "合同结束日期"
  493. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  494. // @Param HasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
  495. // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
  496. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  497. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  498. // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'invoice_time':开票日 、 'payment_date':到款日"
  499. // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
  500. // @Success 200 {object} fms.ContractRegisterItem
  501. // @router /census/invoice_payment/list [get]
  502. func (ct *InvoicePaymentController) List(c *gin.Context) {
  503. var req fms.InvoicePaymentCensusListReq
  504. if e := c.BindQuery(&req); e != nil {
  505. err, ok := e.(validator.ValidationErrors)
  506. if !ok {
  507. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  508. return
  509. }
  510. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  511. return
  512. }
  513. cond := `1 = 1`
  514. pars := make([]interface{}, 0)
  515. // 客户姓名/销售
  516. if req.Keyword != "" {
  517. kw := "%" + req.Keyword + "%"
  518. cond += ` AND b.company_name LIKE ?`
  519. pars = append(pars, kw)
  520. }
  521. if req.SellerIds != "" {
  522. sellerIds := strings.Split(req.SellerIds, ",")
  523. cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  524. pars = append(pars, sellerIds, sellerIds)
  525. }
  526. // 套餐筛选
  527. if req.ServiceTypes != "" {
  528. serviceTypes := strings.Split(req.ServiceTypes, ",")
  529. tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  530. if e != nil {
  531. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  532. return
  533. }
  534. if len(tempRegisterIds) > 0 {
  535. cond += ` AND a.register_id IN ?`
  536. pars = append(pars, tempRegisterIds)
  537. } else {
  538. cond += ` AND 1 = 2`
  539. }
  540. }
  541. if req.ListParam == 1 {
  542. cond += ` AND a.service_product_id = 1 `
  543. } else if req.ListParam == 2 {
  544. cond += ` AND a.service_product_id = 2 `
  545. }
  546. // 开票到款日期
  547. if req.TimeType != 0 {
  548. if req.TimeType == 1 && req.StartDate != "" && req.EndDate != "" {
  549. st := fmt.Sprint(req.StartDate, " 00:00:00")
  550. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  551. cond += ` AND (c.invoice_time BETWEEN ? AND ?) `
  552. pars = append(pars, st, ed)
  553. } else if req.TimeType == 2 && req.StartDate != "" && req.EndDate != "" {
  554. st := fmt.Sprint(req.StartDate, " 00:00:00")
  555. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  556. cond += ` AND (d.invoice_time BETWEEN ? AND ?) `
  557. pars = append(pars, st, ed)
  558. } else if req.TimeType == 3 && req.StartDate != "" && req.EndDate != "" {
  559. st := fmt.Sprint(req.StartDate, " 00:00:00")
  560. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  561. cond += ` AND (c.invoice_time BETWEEN ? AND ?) AND (d.invoice_time BETWEEN ? AND ?) `
  562. pars = append(pars, st, ed, st, ed)
  563. }
  564. } else if req.StartDate != "" && req.EndDate != "" {
  565. st := fmt.Sprint(req.StartDate, " 00:00:00")
  566. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  567. if req.SellerIds != "" {
  568. sellerIds := strings.Split(req.SellerIds, ",")
  569. cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  570. pars = append(pars, sellerIds, sellerIds)
  571. cond += ` AND ((c.seller_id in ? AND a.invoice_id <> 0 AND c.invoice_time BETWEEN ? AND ?)`
  572. cond += `OR (d.seller_id in ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  573. pars = append(pars, sellerIds, st, ed, sellerIds, st, ed)
  574. } else {
  575. cond += ` AND ((a.invoice_id <> 0 AND c.invoice_time BETWEEN ? AND ?)`
  576. cond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  577. pars = append(pars, st, ed, st, ed)
  578. }
  579. }
  580. if req.HasInvoice == "1" {
  581. cond += ` AND a.invoice_id > 0 `
  582. } else if req.HasInvoice == "0" {
  583. cond += ` AND a.invoice_id = 0 `
  584. }
  585. if req.HasPayment == "1" {
  586. cond += ` AND a.payment_id > 0 `
  587. } else if req.HasPayment == "0" {
  588. cond += ` AND a.payment_id = 0 `
  589. }
  590. page := new(base.Page)
  591. page.SetPageSize(req.PageSize)
  592. page.SetCurrent(req.Current)
  593. //排序
  594. if req.SortType == "" {
  595. req.SortType = "desc"
  596. }
  597. if req.SortType != "desc" && req.SortType != "asc" {
  598. resp.Fail("排序类型不正确", c)
  599. return
  600. }
  601. if req.SortParam == "" {
  602. page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: true})
  603. page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: false})
  604. page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: false})
  605. page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: false})
  606. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  607. } else if req.SortParam == "invoice_time" {
  608. if req.SortType == "asc" {
  609. page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: false})
  610. page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: true})
  611. page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: true})
  612. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: true})
  613. } else {
  614. page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: true})
  615. page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: false})
  616. page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: false})
  617. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  618. }
  619. } else if req.SortParam == "payment_date" {
  620. if req.SortType == "asc" {
  621. page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: false})
  622. page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: true})
  623. page.AddOrderItem(base.OrderItem{Column: "d.amount", Asc: true})
  624. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: true})
  625. } else {
  626. page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: true})
  627. page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: false})
  628. page.AddOrderItem(base.OrderItem{Column: "d.amount", Asc: false})
  629. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  630. }
  631. } else {
  632. resp.Fail("排序字段不正确", c)
  633. return
  634. }
  635. if req.IsExport == 1 {
  636. page.SetPageSize(10000)
  637. page.SetCurrent(1)
  638. }
  639. registerList, total, e := fms.GetInvoicePaymentCensusPageList(page, cond, pars)
  640. if e != nil {
  641. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  642. return
  643. }
  644. queryRegisterIds := make([]int, 0)
  645. for i := range registerList {
  646. queryRegisterIds = append(queryRegisterIds, registerList[i].ContractRegisterId)
  647. }
  648. //fmt.Println("queryRegisterIds:",queryRegisterIds)
  649. results := new(fms.InvoicePaymentCensusResp)
  650. if len(queryRegisterIds) > 0 {
  651. // 获取汇总数据IDs, 用于查询合计数据
  652. summaryIdsCond := cond
  653. summaryIdsPars := pars
  654. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(summaryIdsCond, summaryIdsPars)
  655. if e != nil {
  656. resp.FailMsg("获取失败", "获取商品到款汇总IDs失败, Err: "+e.Error(), c)
  657. return
  658. }
  659. //fmt.Println("summaryIds:",summaryIds)
  660. var listErr, totalErr, totalGroupErr error
  661. wg := sync.WaitGroup{}
  662. // 响应列表
  663. respList := make([]*fms.InvoicePaymentCensusItem, 0)
  664. summaryList := make([]*fms.InvoicePaymentSummaryItem, 0)
  665. wg.Add(1)
  666. go func() {
  667. defer wg.Done()
  668. // 获取汇总数据
  669. summaryCond := cond
  670. summaryCond += ` AND a.register_id IN ?`
  671. summaryPars := pars
  672. summaryPars = append(summaryPars, queryRegisterIds)
  673. summaryData, e := fms.GetInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  674. if e != nil {
  675. resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
  676. return
  677. }
  678. summaryList = summaryData
  679. //summaryIds := make([]int, 0)
  680. paymentIds := make([]int, 0)
  681. for i := range summaryList {
  682. //summaryIds = append(summaryIds, summaryList[i].SummaryId)
  683. if summaryList[i].PaymentId > 0 {
  684. paymentIds = append(paymentIds, summaryList[i].PaymentId)
  685. }
  686. }
  687. // 合同套餐
  688. /*contractServiceCond := `contract_register_id IN ?`
  689. contractServicePars := make([]interface{}, 0)
  690. contractServicePars = append(contractServicePars, queryRegisterIds)
  691. contractServiceOB := new(fms.ContractService)
  692. contractServiceList, e := contractServiceOB.List(contractServiceCond, contractServicePars)
  693. if e != nil {
  694. listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
  695. return
  696. }
  697. contractServiceMap := make(map[int][]*fms.ContractService, 0)
  698. servicesNameMap := make(map[int][]string, 0)
  699. for i := range contractServiceList {
  700. if contractServiceMap[contractServiceList[i].ContractRegisterId] == nil {
  701. contractServiceMap[contractServiceList[i].ContractRegisterId] = make([]*fms.ContractService, 0)
  702. }
  703. contractServiceMap[contractServiceList[i].ContractRegisterId] = append(contractServiceMap[contractServiceList[i].ContractRegisterId], contractServiceList[i])
  704. servicesNameMap[contractServiceList[i].ContractRegisterId] = append(servicesNameMap[contractServiceList[i].ContractRegisterId], contractServiceList[i].Title)
  705. }
  706. */
  707. servicesNameMap, serviceFormatMap, e := fmsService.GetContractServiceNameFormat(queryRegisterIds)
  708. if e != nil {
  709. listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
  710. return
  711. }
  712. // 到款套餐分配
  713. serviceAmountMap := make(map[int][]*fms.ContractPaymentServiceAmount, 0)
  714. if len(paymentIds) > 0 {
  715. serviceAmountCond := `contract_payment_id IN ?`
  716. serviceAmountPars := make([]interface{}, 0)
  717. serviceAmountPars = append(serviceAmountPars, paymentIds)
  718. serviceAmountOB := new(fms.ContractPaymentServiceAmount)
  719. serviceAmountList, e := serviceAmountOB.List(serviceAmountCond, serviceAmountPars)
  720. if e != nil {
  721. listErr = fmt.Errorf("获取到款套餐分配列表失败, Err: %s", e.Error())
  722. return
  723. }
  724. for i := range serviceAmountList {
  725. if serviceAmountMap[serviceAmountList[i].ContractPaymentId] == nil {
  726. serviceAmountMap[serviceAmountList[i].ContractPaymentId] = make([]*fms.ContractPaymentServiceAmount, 0)
  727. }
  728. serviceAmountMap[serviceAmountList[i].ContractPaymentId] = append(serviceAmountMap[serviceAmountList[i].ContractPaymentId], serviceAmountList[i])
  729. }
  730. }
  731. // 重组汇总数据
  732. summaryMap := make(map[int][]*fms.InvoicePaymentCensusInfo)
  733. amountMap := make(map[string]*fms.ContractPaymentServiceAmount)
  734. for i := range summaryList {
  735. v := new(fms.InvoicePaymentCensusInfo)
  736. v.InvoiceId = summaryList[i].InvoiceId
  737. v.InvoiceDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].InvoiceDate)
  738. v.InvoiceAmount = summaryList[i].InvoiceAmount
  739. v.SellerId = summaryList[i].SellerId
  740. v.SellerName = summaryList[i].SellerName
  741. v.SellerGroupId = summaryList[i].SellerGroupId
  742. v.SellerGroupName = summaryList[i].SellerGroupName
  743. v.SellerType = summaryList[i].ServiceProductId
  744. v.PaymentId = summaryList[i].PaymentId
  745. v.PaymentDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].PaymentDate)
  746. v.PaymentAmount = summaryList[i].PaymentAmount
  747. v.PayType = summaryList[i].PayType
  748. // 套餐到款分配
  749. svaList := make([]*fms.ContractPaymentServiceAmountItem, 0)
  750. amountList := serviceAmountMap[summaryList[i].PaymentId]
  751. if amountList != nil {
  752. for i := range amountList {
  753. k := fmt.Sprintf("%d-%d", amountList[i].ContractPaymentId, amountList[i].ServiceTemplateId)
  754. amountMap[k] = amountList[i]
  755. }
  756. }
  757. // 合同对应的所有套餐
  758. svList := serviceFormatMap[summaryList[i].RegisterId]
  759. if svList != nil {
  760. for ii := range svList {
  761. vv := new(fms.ContractPaymentServiceAmountItem)
  762. vv.ServiceTemplateId = svList[ii].ServiceTemplateId
  763. vv.ServiceTemplateName = svList[ii].FormatTitle
  764. vv.ServiceTemplatePid = svList[ii].ServiceTemplatePid
  765. vv.ServiceProductId = svList[ii].ServiceProductId
  766. k2 := fmt.Sprintf("%d-%d", summaryList[i].PaymentId, svList[ii].ServiceTemplateId)
  767. a := amountMap[k2]
  768. if a != nil {
  769. vv.ContractPaymentServiceAmountId = a.ContractPaymentServiceAmountId
  770. vv.ContractPaymentId = a.ContractPaymentId
  771. vv.Amount = a.Amount
  772. }
  773. svaList = append(svaList, vv)
  774. }
  775. }
  776. v.ServiceAmountList = svaList
  777. summaryMap[summaryList[i].SummaryId] = append(summaryMap[summaryList[i].SummaryId], v)
  778. }
  779. // 响应列表
  780. for i := range registerList {
  781. v := new(fms.InvoicePaymentCensusItem)
  782. v.SummaryId = registerList[i].SummaryId
  783. v.ContractRegisterId = registerList[i].ContractRegisterId
  784. v.CompanyName = registerList[i].CompanyName
  785. v.NewCompany = registerList[i].NewCompany
  786. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  787. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  788. v.ServicesName = servicesNameMap[registerList[i].ContractRegisterId]
  789. v.InvoicePaymentList = summaryMap[registerList[i].SummaryId]
  790. v.ContractType = registerList[i].ContractType
  791. v.ActualPayCompanies = registerList[i].ActualPayCompanies
  792. respList = append(respList, v)
  793. }
  794. }()
  795. // 开票到款金额合计(换算后)
  796. var invoiceTotal, paymentTotal, amountTotal float64
  797. wg.Add(1)
  798. go func() {
  799. defer wg.Done()
  800. if len(summaryIds) == 0 {
  801. return
  802. }
  803. amountTotalCond := `a.id IN ?`
  804. amountTotalPars := make([]interface{}, 0)
  805. amountTotalPars = append(amountTotalPars, summaryIds)
  806. invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
  807. if e != nil {
  808. totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
  809. return
  810. }
  811. invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
  812. paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
  813. if e != nil {
  814. totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
  815. return
  816. }
  817. paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
  818. amountCond := `a.id IN ? AND (a.invoice_id <> 0 OR (a.payment_id <> 0 AND a.invoice_id =0))`
  819. amountPars := make([]interface{}, 0)
  820. amountPars = append(amountPars, summaryIds)
  821. amountSum, e := fms.GetContractSummaryInvoicePaymentAmount(amountCond, amountPars)
  822. if e != nil {
  823. totalErr = fmt.Errorf("获取汇总金额合计失败, Err: %s", e.Error())
  824. return
  825. }
  826. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  827. }()
  828. // 分币种金额统计
  829. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  830. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  831. wg.Add(1)
  832. go func() {
  833. defer wg.Done()
  834. currencyOB := new(fms.CurrencyUnit)
  835. currencyCond := `enable = 1`
  836. currencyPars := make([]interface{}, 0)
  837. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  838. if e != nil {
  839. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  840. return
  841. }
  842. unitMap := make(map[string]string)
  843. for i := range currencyList {
  844. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  845. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  846. Name: currencyList[i].Name,
  847. UnitName: currencyList[i].UnitName,
  848. Code: currencyList[i].Code,
  849. FlagImg: currencyList[i].FlagImg,
  850. })
  851. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  852. Name: currencyList[i].Name,
  853. UnitName: currencyList[i].UnitName,
  854. Code: currencyList[i].Code,
  855. FlagImg: currencyList[i].FlagImg,
  856. })
  857. }
  858. if len(summaryIds) == 0 {
  859. return
  860. }
  861. totalGroupCond := `a.id IN ?`
  862. totalGroupPars := make([]interface{}, 0)
  863. totalGroupPars = append(totalGroupPars, summaryIds)
  864. invoiceSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 1)
  865. if e != nil {
  866. totalGroupErr = fmt.Errorf("获取汇总货币合计开票金额失败, Err: %s", e.Error())
  867. return
  868. }
  869. paymentSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 2)
  870. if e != nil {
  871. totalGroupErr = fmt.Errorf("获取汇总货币合计到款金额失败, Err: %s", e.Error())
  872. return
  873. }
  874. invoiceSumMap := make(map[string]float64)
  875. paymentSumMap := make(map[string]float64)
  876. for i := range invoiceSumGroup {
  877. invoiceSumMap[invoiceSumGroup[i].CurrencyUnit] = invoiceSumGroup[i].OriginAmountTotal
  878. continue
  879. }
  880. for i := range paymentSumGroup {
  881. paymentSumMap[paymentSumGroup[i].CurrencyUnit] = paymentSumGroup[i].OriginAmountTotal
  882. continue
  883. }
  884. for i := range invoiceCurrencyTotals {
  885. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
  886. invoiceCurrencyTotals[i].Amount = a
  887. }
  888. for i := range paymentCurrencyTotals {
  889. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  890. paymentCurrencyTotals[i].Amount = a
  891. }
  892. }()
  893. wg.Wait()
  894. if listErr != nil {
  895. resp.FailMsg("获取失败", listErr.Error(), c)
  896. return
  897. }
  898. if totalErr != nil {
  899. resp.FailMsg("获取失败", totalErr.Error(), c)
  900. return
  901. }
  902. if totalGroupErr != nil {
  903. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  904. return
  905. }
  906. results.DataList = respList
  907. results.InvoiceTotal = invoiceTotal
  908. results.PaymentTotal = paymentTotal
  909. results.AmountTotal = amountTotal
  910. results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  911. results.PaymentCurrencyTotal = paymentCurrencyTotals
  912. }
  913. // 是否导出
  914. if req.IsExport == 1 {
  915. ExportInvoicePaymentCensusList(c, results)
  916. return
  917. }
  918. page.SetTotal(total)
  919. baseData := new(base.BaseData)
  920. baseData.SetPage(page)
  921. baseData.SetList(results)
  922. resp.OkData("获取成功", baseData, c)
  923. }
  924. // IncomeList
  925. // @Title 业务收入统计表
  926. // @Description 获取业务收入统计表接口
  927. // @Param ListParam query int false "套餐类型: 0-月度; 1-季度; 2-半年度;3-年度;4-月度累计"
  928. // @Success 200 {object} fms.CensusIncomeChartResp
  929. // @router /census/income/list [get]
  930. func (this *InvoicePaymentController) IncomeList(c *gin.Context) {
  931. var req fms.IncomeListReq
  932. if e := c.BindQuery(&req); e != nil {
  933. err, ok := e.(validator.ValidationErrors)
  934. if !ok {
  935. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  936. return
  937. }
  938. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  939. return
  940. }
  941. //收入统计
  942. var incomeList models.CensusIncomeChartResp
  943. ch := make(chan models.CensusIncomeChartResp, 1)
  944. go getCensusIncomeListV2(ch, req)
  945. for v := range ch {
  946. incomeList = v
  947. close(ch)
  948. }
  949. // 是否导出
  950. if req.IsExport == 1 {
  951. ExportIncomeList(c, incomeList.DataList)
  952. return
  953. }
  954. resp.OkData("获取成功", incomeList, c)
  955. }
  956. func getCensusIncomeListV2(ch chan models.CensusIncomeChartResp, req fms.IncomeListReq) (incomeChart models.CensusIncomeChartResp, err error) {
  957. defer func() {
  958. if err != nil {
  959. global.LOG.Error(err)
  960. if err != utils.ErrNoRow{
  961. go alarm_msg.SendAlarmMsg("获取业务收入金额统计数据异常,Err:"+err.Error(), 3)
  962. }
  963. }
  964. ch <- incomeChart
  965. }()
  966. //todayStr := utils.GetToday("20060102")
  967. //key := "admin:home:fmsIncomeList:" + todayStr
  968. //
  969. //redisJsonData, redisErr := global.Redis.Get(context.TODO(), key).Result()
  970. //if redisErr != nil {
  971. //获取最新的开票到款日期
  972. cond := ``
  973. historyCond := ``
  974. pars := make([]interface{}, 0)
  975. historyPars := make([]interface{}, 0)
  976. if req.SellerIds != "" {
  977. sellerIds := strings.Split(req.SellerIds, ",")
  978. cond += ` AND (a.seller_id in ? )`
  979. historyCond += ` AND (seller_id in ? )`
  980. pars = append(pars, sellerIds)
  981. historyPars = append(historyPars, sellerIds)
  982. }
  983. if req.CompanyType == 1 {
  984. cond += ` AND b.contract_type = 1 `
  985. historyCond += ` AND new_company = 1`
  986. } else if req.CompanyType == 2 {
  987. cond += ` AND b.contract_type IN (2,3,4) `
  988. historyCond += ` AND new_company = 0`
  989. }
  990. var latestTime time.Time
  991. invoiceItem, err := fms.GetLatestIncome(cond, pars)
  992. if err != nil && err != utils.ErrNoRow {
  993. err = fmt.Errorf("获取最新的开票或到款日期, Err: %s", err.Error())
  994. return
  995. }
  996. latestTime = invoiceItem.InvoiceDate
  997. if err == utils.ErrNoRow {
  998. historyItem, e := fms.GetLatestHistoryIncome(historyCond, historyPars)
  999. if e != nil && e != utils.ErrNoRow {
  1000. err = fmt.Errorf("获取最新的历史开票或到款日期, Err: %s", err.Error())
  1001. return
  1002. }
  1003. latestTime = historyItem.InvoiceDate
  1004. }
  1005. if latestTime.IsZero() {
  1006. latestTime = time.Now()
  1007. }
  1008. latestTime = latestTime.AddDate(0, 0, -latestTime.Day()+1)
  1009. var dateSlice []string
  1010. var totalMoneySlice, prevTotalMoneySlice []float64
  1011. var yoySlice []string
  1012. var yearNum, monthNum int
  1013. var reqStartDate, reqEndDate time.Time
  1014. historyTime, _ := time.Parse(utils.FormatDate, "2023-04-01")
  1015. if req.StartDate != "" && req.EndDate != "" {
  1016. st := fmt.Sprint(req.StartDate, "-01 00:00:00")
  1017. ed := fmt.Sprint(req.EndDate, "-01 23:59:59")
  1018. reqStartDate, _ = time.Parse(utils.FormatDateTime, st)
  1019. reqEndDate, _ = time.Parse(utils.FormatDateTime, ed)
  1020. if reqEndDate.After(latestTime) {
  1021. yearNum = latestTime.Year() - reqStartDate.Year()
  1022. monthNum = int(latestTime.Month() - reqStartDate.Month())
  1023. } else {
  1024. yearNum = reqEndDate.Year() - reqStartDate.Year()
  1025. monthNum = int(reqEndDate.Month() - reqStartDate.Month())
  1026. }
  1027. } else {
  1028. yearNum = latestTime.Year() - 2020
  1029. monthNum = int(latestTime.Month() - 1)
  1030. }
  1031. if yearNum < 0 {
  1032. yearNum = -yearNum
  1033. }
  1034. if monthNum < 0 {
  1035. monthNum = -monthNum
  1036. }
  1037. numMonth := yearNum*12 + monthNum //共存在多少个月
  1038. //if req.ListParam == "1" {
  1039. // numMonth = numMonth / 3
  1040. //} else if req.ListParam == "2" {
  1041. // numMonth = numMonth / 6
  1042. //} else if req.ListParam == "3" {
  1043. // numMonth = numMonth / 12
  1044. //}
  1045. // 累计值
  1046. var accumulate float64
  1047. var partAccumulate float64
  1048. var historyAccumulate float64
  1049. var partHistoryAccumulate float64
  1050. //dataList := make([]*fms.IncomeSummaryItem, 0)
  1051. //historydataList := make([]*fms.IncomeSummaryItem, 0)
  1052. fmt.Println("numMonth:", numMonth)
  1053. fmt.Println("InvoiceDate:", latestTime)
  1054. var j int
  1055. for i := 0; i <= numMonth; i++ {
  1056. //timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
  1057. var endDateTime time.Time
  1058. var prevEndDateTime time.Time
  1059. var prevStartDate, prevEndDate string
  1060. var startDate, endDate string
  1061. //开始日期
  1062. if req.StartDate != "" && req.EndDate != "" {
  1063. startDate = reqStartDate.AddDate(0, i, 0).Format("2006-01")
  1064. prevStartDate = reqStartDate.AddDate(-1, i, 0).Format("2006-01")
  1065. } else {
  1066. startDate = latestTime.AddDate(0, i-numMonth, 0).Format("2006-01")
  1067. prevStartDate = latestTime.AddDate(-1, i-numMonth, 0).Format("2006-01")
  1068. }
  1069. startDate = fmt.Sprint(startDate, "-01")
  1070. prevStartDate = fmt.Sprint(prevStartDate, "-01")
  1071. startDateTime, _ := time.Parse(utils.FormatDate, startDate)
  1072. prevStartDateTime, _ := time.Parse(utils.FormatDate, prevStartDate)
  1073. //结束日期
  1074. if req.StartDate != "" && req.EndDate != "" {
  1075. endDateTime = reqStartDate.AddDate(0, i+1, -1)
  1076. prevEndDateTime = reqStartDate.AddDate(-1, i+1, -1)
  1077. if reqEndDate.After(latestTime) {
  1078. endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
  1079. prevEndDateTime = latestTime.AddDate(-1, i-numMonth+1, -1)
  1080. }
  1081. } else {
  1082. endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
  1083. prevEndDateTime = latestTime.AddDate(-1, i-numMonth+1, -1)
  1084. }
  1085. endDate = endDateTime.Format(utils.FormatDate)
  1086. prevEndDate = prevEndDateTime.Format(utils.FormatDate)
  1087. cond := `1 = 1`
  1088. histrtyCond := `1 = 1`
  1089. pars := make([]interface{}, 0)
  1090. historyPars := make([]interface{}, 0)
  1091. prevCond := `1 = 1`
  1092. prevHistoryCond := `1 = 1`
  1093. prevPars := make([]interface{}, 0)
  1094. prevHistoryPars := make([]interface{}, 0)
  1095. if req.CompanyType == 1 {
  1096. cond += ` AND b.contract_type = 1 `
  1097. prevCond += ` AND b.contract_type = 1 `
  1098. histrtyCond += ` AND new_company = 1 `
  1099. prevHistoryCond += ` AND new_company = 1 `
  1100. } else if req.CompanyType == 2 {
  1101. cond += ` AND b.contract_type IN (2,3,4) `
  1102. prevCond += ` AND b.contract_type IN (2,3,4) `
  1103. histrtyCond += ` AND new_company = 0 `
  1104. prevHistoryCond += ` AND new_company = 0 `
  1105. }
  1106. if req.SellerIds != "" {
  1107. sellerIds := strings.Split(req.SellerIds, ",")
  1108. cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  1109. pars = append(pars, sellerIds, sellerIds)
  1110. prevCond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  1111. prevPars = append(prevPars, sellerIds, sellerIds)
  1112. histrtyCond += ` AND seller_id in ? `
  1113. prevHistoryCond += ` AND seller_id in ? `
  1114. historyPars = append(historyPars, sellerIds)
  1115. prevHistoryPars = append(prevHistoryPars, sellerIds)
  1116. }
  1117. //fmt.Println("i:",i)
  1118. //fmt.Println("j:",j)
  1119. {
  1120. //本期
  1121. st := fmt.Sprint(startDate, " 00:00:00")
  1122. ed := fmt.Sprint(endDate, " 23:59:59")
  1123. //校验日期,分段查询
  1124. if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
  1125. //全部走新查询
  1126. //fmt.Println("新查询")
  1127. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1128. pars = append(pars, st, ed, st, ed)
  1129. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1130. if e != nil {
  1131. return
  1132. }
  1133. // 开票到款金额合计(换算后)
  1134. var amountTotal float64
  1135. if len(summaryIds) > 0 {
  1136. amountCond := `a.id IN ? `
  1137. amountPars := make([]interface{}, 0)
  1138. amountPars = append(amountPars, summaryIds)
  1139. if req.SellerIds != "" {
  1140. sellerIds := strings.Split(req.SellerIds, ",")
  1141. amountCond += ` AND (( b.seller_id = ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1142. amountCond += `OR ( d.seller_id = ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1143. amountPars = append(amountPars, sellerIds,st, ed, sellerIds,st, ed)
  1144. } else {
  1145. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1146. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1147. amountPars = append(amountPars, st, ed, st, ed)
  1148. }
  1149. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1150. if e != nil {
  1151. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1152. return
  1153. }
  1154. //dataList = append(dataList, results...)
  1155. var amountSum float64
  1156. for _, result := range results {
  1157. incomeChart.DataList = append(incomeChart.DataList, result)
  1158. amountSum += result.Amount
  1159. fmt.Println("result.Amount:", result.Amount)
  1160. }
  1161. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1162. accumulate += amountTotal
  1163. partAccumulate += amountTotal
  1164. }
  1165. if i == j || i == numMonth {
  1166. if req.ListParam == "4" {
  1167. totalMoneySlice = append(totalMoneySlice, accumulate)
  1168. if startDateTime.Month() == 12 {
  1169. accumulate = 0
  1170. }
  1171. } else if req.ListParam == "0" {
  1172. totalMoneySlice = append(totalMoneySlice, amountTotal)
  1173. } else if i > 0 || i == numMonth {
  1174. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  1175. fmt.Println("partAccumulate:", partAccumulate)
  1176. partAccumulate = 0.0
  1177. }
  1178. }
  1179. } else if endDateTime.Before(historyTime) || endDateTime.Equal(historyTime) {
  1180. //全部走旧查询
  1181. //fmt.Println("旧查询")
  1182. //fmt.Println("st:",st)
  1183. //fmt.Println("ed:",ed)
  1184. histrtyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1185. historyPars = append(historyPars, st, ed)
  1186. //fmt.Println("st:",st)
  1187. //fmt.Println("ed:",ed)
  1188. // 开票到款金额合计(换算后)
  1189. var amountTotal float64
  1190. results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
  1191. if e != nil {
  1192. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1193. return
  1194. }
  1195. var amountSum float64
  1196. //dataList = append(dataList, results...)
  1197. for _, result := range results {
  1198. incomeChart.DataList = append(incomeChart.DataList, result)
  1199. amountSum += result.Amount
  1200. }
  1201. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1202. accumulate += amountTotal
  1203. partAccumulate += amountTotal
  1204. if i == j || i == numMonth {
  1205. if req.ListParam == "4" {
  1206. totalMoneySlice = append(totalMoneySlice, accumulate)
  1207. if startDateTime.Month() == 12 {
  1208. accumulate = 0
  1209. }
  1210. } else if req.ListParam == "0" {
  1211. totalMoneySlice = append(totalMoneySlice, amountTotal)
  1212. } else if i > 0 || i == numMonth {
  1213. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  1214. partAccumulate = 0.0
  1215. }
  1216. }
  1217. //fmt.Println("partAccumulate:",partAccumulate)
  1218. }
  1219. }
  1220. { //去年同期,用于计算同比值
  1221. prevSt := fmt.Sprint(prevStartDate, " 00:00:00")
  1222. prevEd := fmt.Sprint(prevEndDate, " 23:59:59")
  1223. //校验日期,分段查询
  1224. if prevStartDateTime.After(historyTime) || prevStartDateTime.Equal(historyTime) {
  1225. //全部走新查询
  1226. prevCond += ` AND ((b.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1227. prevPars = append(prevPars, prevSt, prevEd, prevSt, prevEd)
  1228. prevSummaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(prevCond, prevPars)
  1229. if e != nil {
  1230. return
  1231. }
  1232. // 开票到款金额合计(换算后)
  1233. var prevAmountTotal float64
  1234. if len(prevSummaryIds) > 0 {
  1235. amountCond := `a.id IN ? `
  1236. amountPars := make([]interface{}, 0)
  1237. amountPars = append(amountPars, prevSummaryIds)
  1238. if req.SellerIds != "" {
  1239. sellerIds := strings.Split(req.SellerIds, ",")
  1240. amountCond += ` AND (( b.seller_id = ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1241. amountCond += `OR ( d.seller_id = ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1242. amountPars = append(amountPars, sellerIds,prevSt, prevEd, sellerIds,prevSt, prevEd)
  1243. } else {
  1244. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1245. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1246. amountPars = append(amountPars, prevSt, prevEd)
  1247. }
  1248. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1249. if e != nil {
  1250. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1251. return
  1252. }
  1253. var amountSum float64
  1254. //historydataList = append(historydataList, results...)
  1255. for _, result := range results {
  1256. amountSum += result.Amount
  1257. }
  1258. prevAmountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1259. historyAccumulate += prevAmountTotal
  1260. partHistoryAccumulate += prevAmountTotal
  1261. }
  1262. if i == j || i == numMonth {
  1263. if req.ListParam == "4" {
  1264. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate)
  1265. if prevStartDateTime.Month() == 12 {
  1266. historyAccumulate = 0
  1267. }
  1268. } else if req.ListParam == "0" {
  1269. prevTotalMoneySlice = append(prevTotalMoneySlice, prevAmountTotal)
  1270. } else if i > 0 || i == numMonth {
  1271. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate)
  1272. fmt.Println("partHistoryAccumulate:", partHistoryAccumulate)
  1273. partHistoryAccumulate = 0.0
  1274. }
  1275. }
  1276. } else if prevEndDateTime.Before(historyTime) || prevEndDateTime.Equal(historyTime) {
  1277. //全部走旧查询
  1278. fmt.Println("prevSt:", prevSt)
  1279. fmt.Println("prevEd:", prevEd)
  1280. prevHistoryCond += ` AND (invoice_time BETWEEN ? AND ?)`
  1281. prevHistoryPars = append(prevHistoryPars, prevSt, prevEd)
  1282. // 开票到款金额合计(换算后)
  1283. var amountTotal float64
  1284. results, e := fms.GetIncomeHistory(prevHistoryCond, prevHistoryPars)
  1285. if e != nil {
  1286. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1287. return
  1288. }
  1289. //historydataList = append(historydataList, results...)
  1290. var amountSum float64
  1291. for _, result := range results {
  1292. amountSum += result.Amount
  1293. }
  1294. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1295. historyAccumulate += amountTotal
  1296. partHistoryAccumulate += amountTotal
  1297. if i == j || i == numMonth {
  1298. if req.ListParam == "4" {
  1299. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate)
  1300. if prevStartDateTime.Month() == 12 {
  1301. historyAccumulate = 0
  1302. }
  1303. } else if req.ListParam == "0" {
  1304. prevTotalMoneySlice = append(prevTotalMoneySlice, amountTotal)
  1305. } else if i > 0 || i == numMonth {
  1306. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate)
  1307. fmt.Println("partHistoryAccumulate:", partHistoryAccumulate)
  1308. partHistoryAccumulate = 0.0
  1309. }
  1310. }
  1311. //fmt.Println("partHistoryAccumulate:",partHistoryAccumulate)
  1312. }
  1313. if req.ListParam == "1" && i == j {
  1314. if i == 0 {
  1315. dateSlice = append(dateSlice, startDateTime.AddDate(0, 2, 0).Format("06/01"))
  1316. j = j + 2
  1317. } else {
  1318. dateSlice = append(dateSlice, startDateTime.AddDate(0, 3, 0).Format("06/01"))
  1319. j = j + 3
  1320. }
  1321. } else if req.ListParam == "2" && i == j {
  1322. if i == 0 {
  1323. dateSlice = append(dateSlice, startDateTime.AddDate(0, 5, 0).Format("06/01"))
  1324. j = j + 5
  1325. } else {
  1326. dateSlice = append(dateSlice, startDateTime.AddDate(0, 6, 0).Format("06/01"))
  1327. j = j + 6
  1328. }
  1329. } else if req.ListParam == "3" && i == j {
  1330. if i == 0 {
  1331. dateSlice = append(dateSlice, startDateTime.AddDate(0, 11, 0).Format("06/01"))
  1332. j = j + 11
  1333. } else {
  1334. dateSlice = append(dateSlice, startDateTime.AddDate(0, 12, 0).Format("06/01"))
  1335. j = j + 12
  1336. }
  1337. } else if i == j {
  1338. dateSlice = append(dateSlice, startDateTime.Format("06/01"))
  1339. j++
  1340. }
  1341. }
  1342. }
  1343. fmt.Println("prevTotalMoneySlice:", len(prevTotalMoneySlice))
  1344. fmt.Println("totalMoneySlice:", len(totalMoneySlice))
  1345. //计算同比值
  1346. for i := range prevTotalMoneySlice {
  1347. var yoy float64
  1348. var yoyStr string
  1349. //fmt.Println("1:", prevTotalMoneySlice[i])
  1350. //fmt.Println("2:", totalMoneySlice[i])
  1351. //fmt.Println("3:", totalMoneySlice[i]-prevTotalMoneySlice[i])
  1352. totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", totalMoneySlice[i]), 64)
  1353. if prevTotalMoneySlice[i] != 0 && totalMoneySlice[i] != 0 {
  1354. yoy = (totalMoneySlice[i] - prevTotalMoneySlice[i]) / prevTotalMoneySlice[i]
  1355. yoyStr = fmt.Sprintf("%.4f", yoy)
  1356. if i == len(prevTotalMoneySlice)-1 && i > 0 && req.ListParam == "3" {
  1357. fmt.Println("totalMoneySlice[i-1]:", totalMoneySlice[i-1])
  1358. yoy = (totalMoneySlice[i] - totalMoneySlice[i-1]) / totalMoneySlice[i-1]
  1359. yoyStr = fmt.Sprintf("%.4f", yoy)
  1360. }
  1361. }
  1362. yoySlice = append(yoySlice, yoyStr)
  1363. }
  1364. incomeChart.Title = "开票到款统计图"
  1365. incomeChart.Date = dateSlice
  1366. incomeChart.TotalMoney = totalMoneySlice
  1367. incomeChart.PrevTotalMoney = prevTotalMoneySlice
  1368. incomeChart.Yoy = yoySlice
  1369. //redisJsonData, err := json.Marshal(incomeChart)
  1370. //if err == nil {
  1371. // global.Redis.SetEX(context.TODO(), key, string(redisJsonData), time.Minute*30)
  1372. //}
  1373. //} else {
  1374. // err = json.Unmarshal([]byte(redisJsonData), &incomeChart)
  1375. // if err != nil {
  1376. // fmt.Println("近两年的收入统计数据,json转换失败")
  1377. // }
  1378. //}
  1379. return
  1380. }
  1381. // ExportIncomeList 导出业务收入统计列表
  1382. func ExportIncomeList(c *gin.Context, list []*fms.IncomeSummaryItem) {
  1383. // 生成Excel文件
  1384. xlsxFile := xlsx.NewFile()
  1385. style := xlsx.NewStyle()
  1386. alignment := xlsx.Alignment{
  1387. Horizontal: "center",
  1388. Vertical: "center",
  1389. WrapText: true,
  1390. }
  1391. style.Alignment = alignment
  1392. style.ApplyAlignment = true
  1393. sheetName := "业务收入统计表"
  1394. sheet, err := xlsxFile.AddSheet(sheetName)
  1395. if err != nil {
  1396. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1397. return
  1398. }
  1399. // 数据表头
  1400. rowTitle := []string{"开票日期", "新客户(1)", "客户名称", "金额", "销售"}
  1401. titleRow := sheet.AddRow()
  1402. for i := range rowTitle {
  1403. v := titleRow.AddCell()
  1404. v.SetString(rowTitle[i])
  1405. v.SetStyle(style)
  1406. }
  1407. incomeSummaryItemList := make(fms.IncomeSummaryItemList, 0)
  1408. incomeSummaryItemList = list
  1409. sort.Sort(incomeSummaryItemList)
  1410. // 填充数据
  1411. for _, v := range incomeSummaryItemList {
  1412. dataRow := sheet.AddRow()
  1413. dataRow.AddCell().SetString(v.InvoiceDate.Format(utils.FormatDate)) // 开票日期
  1414. newCompany := 0
  1415. if v.ContractType == 1 {
  1416. newCompany = 1
  1417. }
  1418. dataRow.AddCell().SetString(strconv.Itoa(newCompany)) // 新客户
  1419. dataRow.AddCell().SetString(v.CompanyName) // 客户名称
  1420. dataRow.AddCell().SetString(fmt.Sprint(v.Amount)) // 金额
  1421. dataRow.AddCell().SetString(v.SellerName) // 销售员
  1422. }
  1423. // 输出文件
  1424. var buffer bytes.Buffer
  1425. _ = xlsxFile.Write(&buffer)
  1426. content := bytes.NewReader(buffer.Bytes())
  1427. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1428. fileName := sheetName + randStr + ".xlsx"
  1429. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1430. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1431. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1432. }