invoice_payment.go 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  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: "是"}
  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. newCompany := 0
  421. if v.ContractType == 1 {
  422. newCompany = 1
  423. }
  424. colC.SetString(newCompanyMap[newCompany])
  425. // 合同有效期
  426. colD := dataRow.AddCell()
  427. colD.VMerge = mergeRowNum
  428. colD.SetString(fmt.Sprint(v.StartDate, "至", v.EndDate))
  429. // 开票到款信息
  430. for k2, v2 := range v.InvoicePaymentList {
  431. rowData := []string{
  432. v2.InvoiceDate, // 开票日
  433. fmt.Sprint(v2.InvoiceAmount), // 开票金额
  434. v2.PaymentDate, // 到款日
  435. fmt.Sprint(v2.PaymentAmount), // 到款金额
  436. fms.ContractPaymentPayTypeNameMap[v2.PayType], // 付款方式
  437. v2.SellerName, // 销售
  438. v2.SellerGroupName, // 组别
  439. sellerTypeMap[v2.SellerType], // 销售类型
  440. }
  441. // 套餐金额信息
  442. serviceTempShowAmount := make(map[int]string)
  443. for i := range serviceTempShow {
  444. for s2 := range v2.ServiceAmountList {
  445. item := v2.ServiceAmountList[s2]
  446. if item.ServiceTemplateId == serviceTempShow[i].ServiceTemplateId {
  447. serviceTempShowAmount[serviceTempShow[i].ServiceTemplateId] = fmt.Sprint(item.Amount)
  448. break
  449. } else if serviceTempShow[i].Pid == item.ServiceTemplateId {
  450. serviceTempShowAmount[serviceTempShow[i].ServiceTemplateId] = fmt.Sprint(item.Amount / 2)
  451. break
  452. }
  453. }
  454. }
  455. for i := range serviceTempShow {
  456. sa := ""
  457. if am, ok := serviceTempShowAmount[serviceTempShow[i].ServiceTemplateId]; ok {
  458. sa = am
  459. }
  460. rowData = append(rowData, sa)
  461. }
  462. // 首行开票到款
  463. if k2 == 0 {
  464. for i := range rowData {
  465. dataRow.AddCell().SetString(rowData[i])
  466. }
  467. continue
  468. }
  469. // 其他行开票到款, 加四列空的单元格用于合并
  470. dataRowExtra := sheet.AddRow()
  471. for i := 0; i < 4; i++ {
  472. dataRowExtra.AddCell()
  473. }
  474. for i := range rowData {
  475. dataRowExtra.AddCell().SetString(rowData[i])
  476. }
  477. }
  478. }
  479. // 输出文件
  480. var buffer bytes.Buffer
  481. _ = xlsxFile.Write(&buffer)
  482. content := bytes.NewReader(buffer.Bytes())
  483. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  484. fileName := "商品到款统计_" + randStr + ".xlsx"
  485. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  486. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  487. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  488. }
  489. // List
  490. // @Title 商品到款统计列表
  491. // @Description 商品到款统计列表
  492. // @Param Keyword query string false "关键词"
  493. // @Param SellGroupId query int false "销售组别ID"
  494. // @Param ServiceType query int false "套餐类型"
  495. // @Param StartDate query string false "合同开始日期"
  496. // @Param EndDate query string false "合同结束日期"
  497. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  498. // @Param HasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
  499. // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
  500. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  501. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  502. // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'invoice_time':开票日 、 'payment_date':到款日"
  503. // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
  504. // @Success 200 {object} fms.ContractRegisterItem
  505. // @router /census/invoice_payment/list [get]
  506. func (ct *InvoicePaymentController) List(c *gin.Context) {
  507. var req fms.InvoicePaymentCensusListReq
  508. if e := c.BindQuery(&req); e != nil {
  509. err, ok := e.(validator.ValidationErrors)
  510. if !ok {
  511. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  512. return
  513. }
  514. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  515. return
  516. }
  517. cond := `1 = 1`
  518. pars := make([]interface{}, 0)
  519. // 客户姓名/销售
  520. if req.Keyword != "" {
  521. kw := "%" + req.Keyword + "%"
  522. cond += ` AND b.company_name LIKE ?`
  523. pars = append(pars, kw)
  524. }
  525. if req.SellerIds != "" {
  526. sellerIds := strings.Split(req.SellerIds, ",")
  527. cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  528. pars = append(pars, sellerIds, sellerIds)
  529. }
  530. // 套餐筛选
  531. if req.ServiceTypes != "" {
  532. serviceTypes := strings.Split(req.ServiceTypes, ",")
  533. tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  534. if e != nil {
  535. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  536. return
  537. }
  538. if len(tempRegisterIds) > 0 {
  539. cond += ` AND a.register_id IN ?`
  540. pars = append(pars, tempRegisterIds)
  541. } else {
  542. cond += ` AND 1 = 2`
  543. }
  544. }
  545. if req.ListParam == 1 {
  546. cond += ` AND a.service_product_id = 1 `
  547. } else if req.ListParam == 2 {
  548. cond += ` AND a.service_product_id = 2 `
  549. }
  550. // 开票到款日期
  551. if req.TimeType != 0 {
  552. if req.TimeType == 1 && req.StartDate != "" && req.EndDate != "" {
  553. st := fmt.Sprint(req.StartDate, " 00:00:00")
  554. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  555. cond += ` AND (c.invoice_time BETWEEN ? AND ?) `
  556. pars = append(pars, st, ed)
  557. } else if req.TimeType == 2 && req.StartDate != "" && req.EndDate != "" {
  558. st := fmt.Sprint(req.StartDate, " 00:00:00")
  559. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  560. cond += ` AND (d.invoice_time BETWEEN ? AND ?) `
  561. pars = append(pars, st, ed)
  562. } else if req.TimeType == 3 && req.StartDate != "" && req.EndDate != "" {
  563. st := fmt.Sprint(req.StartDate, " 00:00:00")
  564. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  565. cond += ` AND (c.invoice_time BETWEEN ? AND ?) AND (d.invoice_time BETWEEN ? AND ?) `
  566. pars = append(pars, st, ed, st, ed)
  567. }
  568. } else if req.StartDate != "" && req.EndDate != "" {
  569. st := fmt.Sprint(req.StartDate, " 00:00:00")
  570. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  571. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  572. pars = append(pars, st, ed, st, ed)
  573. }
  574. if req.HasInvoice == "1" {
  575. cond += ` AND a.invoice_id > 0 `
  576. } else if req.HasInvoice == "0" {
  577. cond += ` AND a.invoice_id = 0 `
  578. }
  579. if req.HasPayment == "1" {
  580. cond += ` AND a.payment_id > 0 `
  581. } else if req.HasPayment == "0" {
  582. cond += ` AND a.payment_id = 0 `
  583. }
  584. page := new(base.Page)
  585. page.SetPageSize(req.PageSize)
  586. page.SetCurrent(req.Current)
  587. //排序
  588. if req.SortType == "" {
  589. req.SortType = "desc"
  590. }
  591. if req.SortType != "desc" && req.SortType != "asc" {
  592. resp.Fail("排序类型不正确", c)
  593. return
  594. }
  595. if req.SortParam == "" {
  596. page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: true})
  597. page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: false})
  598. page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: false})
  599. page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: false})
  600. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  601. } else if req.SortParam == "invoice_time" {
  602. if req.SortType == "asc" {
  603. page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: false})
  604. page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: true})
  605. page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: true})
  606. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: true})
  607. } else {
  608. page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: true})
  609. page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: false})
  610. page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: false})
  611. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  612. }
  613. } else if req.SortParam == "payment_date" {
  614. if req.SortType == "asc" {
  615. page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: false})
  616. page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: true})
  617. page.AddOrderItem(base.OrderItem{Column: "d.amount", Asc: true})
  618. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: true})
  619. } else {
  620. page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: true})
  621. page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: false})
  622. page.AddOrderItem(base.OrderItem{Column: "d.amount", Asc: false})
  623. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  624. }
  625. } else {
  626. resp.Fail("排序字段不正确", c)
  627. return
  628. }
  629. if req.IsExport == 1 {
  630. page.SetPageSize(10000)
  631. page.SetCurrent(1)
  632. }
  633. registerList, total, e := fms.GetInvoicePaymentCensusPageList(page, cond, pars)
  634. if e != nil {
  635. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  636. return
  637. }
  638. queryRegisterIds := make([]int, 0)
  639. for i := range registerList {
  640. queryRegisterIds = append(queryRegisterIds, registerList[i].ContractRegisterId)
  641. }
  642. //fmt.Println("queryRegisterIds:",queryRegisterIds)
  643. results := new(fms.InvoicePaymentCensusResp)
  644. if len(queryRegisterIds) > 0 {
  645. // 获取汇总数据IDs, 用于查询合计数据
  646. summaryIdsCond := cond
  647. summaryIdsPars := pars
  648. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(summaryIdsCond, summaryIdsPars)
  649. if e != nil {
  650. resp.FailMsg("获取失败", "获取商品到款汇总IDs失败, Err: "+e.Error(), c)
  651. return
  652. }
  653. //fmt.Println("summaryIds:",summaryIds)
  654. var listErr, totalErr, totalGroupErr error
  655. wg := sync.WaitGroup{}
  656. // 响应列表
  657. respList := make([]*fms.InvoicePaymentCensusItem, 0)
  658. summaryList := make([]*fms.InvoicePaymentSummaryItem, 0)
  659. wg.Add(1)
  660. go func() {
  661. defer wg.Done()
  662. // 获取汇总数据
  663. summaryCond := cond
  664. summaryCond += ` AND a.register_id IN ?`
  665. summaryPars := pars
  666. summaryPars = append(summaryPars, queryRegisterIds)
  667. summaryData, e := fms.GetInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  668. if e != nil {
  669. resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
  670. return
  671. }
  672. summaryList = summaryData
  673. //summaryIds := make([]int, 0)
  674. paymentIds := make([]int, 0)
  675. for i := range summaryList {
  676. //summaryIds = append(summaryIds, summaryList[i].SummaryId)
  677. if summaryList[i].PaymentId > 0 {
  678. paymentIds = append(paymentIds, summaryList[i].PaymentId)
  679. }
  680. }
  681. // 合同套餐
  682. /*contractServiceCond := `contract_register_id IN ?`
  683. contractServicePars := make([]interface{}, 0)
  684. contractServicePars = append(contractServicePars, queryRegisterIds)
  685. contractServiceOB := new(fms.ContractService)
  686. contractServiceList, e := contractServiceOB.List(contractServiceCond, contractServicePars)
  687. if e != nil {
  688. listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
  689. return
  690. }
  691. contractServiceMap := make(map[int][]*fms.ContractService, 0)
  692. servicesNameMap := make(map[int][]string, 0)
  693. for i := range contractServiceList {
  694. if contractServiceMap[contractServiceList[i].ContractRegisterId] == nil {
  695. contractServiceMap[contractServiceList[i].ContractRegisterId] = make([]*fms.ContractService, 0)
  696. }
  697. contractServiceMap[contractServiceList[i].ContractRegisterId] = append(contractServiceMap[contractServiceList[i].ContractRegisterId], contractServiceList[i])
  698. servicesNameMap[contractServiceList[i].ContractRegisterId] = append(servicesNameMap[contractServiceList[i].ContractRegisterId], contractServiceList[i].Title)
  699. }
  700. */
  701. servicesNameMap, serviceFormatMap, e := fmsService.GetContractServiceNameFormat(queryRegisterIds)
  702. if e != nil {
  703. listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
  704. return
  705. }
  706. // 到款套餐分配
  707. serviceAmountMap := make(map[int][]*fms.ContractPaymentServiceAmount, 0)
  708. if len(paymentIds) > 0 {
  709. serviceAmountCond := `contract_payment_id IN ?`
  710. serviceAmountPars := make([]interface{}, 0)
  711. serviceAmountPars = append(serviceAmountPars, paymentIds)
  712. serviceAmountOB := new(fms.ContractPaymentServiceAmount)
  713. serviceAmountList, e := serviceAmountOB.List(serviceAmountCond, serviceAmountPars)
  714. if e != nil {
  715. listErr = fmt.Errorf("获取到款套餐分配列表失败, Err: %s", e.Error())
  716. return
  717. }
  718. for i := range serviceAmountList {
  719. if serviceAmountMap[serviceAmountList[i].ContractPaymentId] == nil {
  720. serviceAmountMap[serviceAmountList[i].ContractPaymentId] = make([]*fms.ContractPaymentServiceAmount, 0)
  721. }
  722. serviceAmountMap[serviceAmountList[i].ContractPaymentId] = append(serviceAmountMap[serviceAmountList[i].ContractPaymentId], serviceAmountList[i])
  723. }
  724. }
  725. // 重组汇总数据
  726. summaryMap := make(map[int][]*fms.InvoicePaymentCensusInfo)
  727. amountMap := make(map[string]*fms.ContractPaymentServiceAmount)
  728. for i := range summaryList {
  729. v := new(fms.InvoicePaymentCensusInfo)
  730. v.InvoiceId = summaryList[i].InvoiceId
  731. v.InvoiceDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].InvoiceDate)
  732. v.InvoiceAmount = summaryList[i].InvoiceAmount
  733. v.SellerId = summaryList[i].SellerId
  734. v.SellerName = summaryList[i].SellerName
  735. v.SellerGroupId = summaryList[i].SellerGroupId
  736. v.SellerGroupName = summaryList[i].SellerGroupName
  737. v.SellerType = summaryList[i].ServiceProductId
  738. v.PaymentId = summaryList[i].PaymentId
  739. v.PaymentDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].PaymentDate)
  740. v.PaymentAmount = summaryList[i].PaymentAmount
  741. v.PayType = summaryList[i].PayType
  742. // 套餐到款分配
  743. svaList := make([]*fms.ContractPaymentServiceAmountItem, 0)
  744. amountList := serviceAmountMap[summaryList[i].PaymentId]
  745. if amountList != nil {
  746. for i := range amountList {
  747. k := fmt.Sprintf("%d-%d", amountList[i].ContractPaymentId, amountList[i].ServiceTemplateId)
  748. amountMap[k] = amountList[i]
  749. }
  750. }
  751. // 合同对应的所有套餐
  752. svList := serviceFormatMap[summaryList[i].RegisterId]
  753. if svList != nil {
  754. for ii := range svList {
  755. vv := new(fms.ContractPaymentServiceAmountItem)
  756. vv.ServiceTemplateId = svList[ii].ServiceTemplateId
  757. vv.ServiceTemplateName = svList[ii].FormatTitle
  758. vv.ServiceTemplatePid = svList[ii].ServiceTemplatePid
  759. vv.ServiceProductId = svList[ii].ServiceProductId
  760. k2 := fmt.Sprintf("%d-%d", summaryList[i].PaymentId, svList[ii].ServiceTemplateId)
  761. a := amountMap[k2]
  762. if a != nil {
  763. vv.ContractPaymentServiceAmountId = a.ContractPaymentServiceAmountId
  764. vv.ContractPaymentId = a.ContractPaymentId
  765. vv.Amount = a.Amount
  766. }
  767. svaList = append(svaList, vv)
  768. }
  769. }
  770. v.ServiceAmountList = svaList
  771. summaryMap[summaryList[i].SummaryId] = append(summaryMap[summaryList[i].SummaryId], v)
  772. }
  773. // 响应列表
  774. for i := range registerList {
  775. v := new(fms.InvoicePaymentCensusItem)
  776. v.SummaryId = registerList[i].SummaryId
  777. v.ContractRegisterId = registerList[i].ContractRegisterId
  778. v.CompanyName = registerList[i].CompanyName
  779. v.NewCompany = registerList[i].NewCompany
  780. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  781. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  782. v.ServicesName = servicesNameMap[registerList[i].ContractRegisterId]
  783. v.InvoicePaymentList = summaryMap[registerList[i].SummaryId]
  784. v.ContractType = registerList[i].ContractType
  785. respList = append(respList, v)
  786. }
  787. }()
  788. // 开票到款金额合计(换算后)
  789. var invoiceTotal, paymentTotal, amountTotal float64
  790. wg.Add(1)
  791. go func() {
  792. defer wg.Done()
  793. if len(summaryIds) == 0 {
  794. return
  795. }
  796. amountTotalCond := `a.id IN ?`
  797. amountTotalPars := make([]interface{}, 0)
  798. amountTotalPars = append(amountTotalPars, summaryIds)
  799. invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
  800. if e != nil {
  801. totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
  802. return
  803. }
  804. invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
  805. paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
  806. if e != nil {
  807. totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
  808. return
  809. }
  810. paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
  811. amountCond := `a.id IN ? AND (a.invoice_id <> 0 OR (a.payment_id <> 0 AND a.invoice_id =0))`
  812. amountPars := make([]interface{}, 0)
  813. amountPars = append(amountTotalPars, summaryIds)
  814. amountSum, e := fms.GetContractSummaryInvoicePaymentAmount(amountCond, amountPars)
  815. if e != nil {
  816. totalErr = fmt.Errorf("获取汇总金额合计失败, Err: %s", e.Error())
  817. return
  818. }
  819. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  820. }()
  821. // 分币种金额统计
  822. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  823. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  824. wg.Add(1)
  825. go func() {
  826. defer wg.Done()
  827. currencyOB := new(fms.CurrencyUnit)
  828. currencyCond := `enable = 1`
  829. currencyPars := make([]interface{}, 0)
  830. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  831. if e != nil {
  832. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  833. return
  834. }
  835. unitMap := make(map[string]string)
  836. for i := range currencyList {
  837. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  838. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  839. Name: currencyList[i].Name,
  840. UnitName: currencyList[i].UnitName,
  841. Code: currencyList[i].Code,
  842. FlagImg: currencyList[i].FlagImg,
  843. })
  844. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  845. Name: currencyList[i].Name,
  846. UnitName: currencyList[i].UnitName,
  847. Code: currencyList[i].Code,
  848. FlagImg: currencyList[i].FlagImg,
  849. })
  850. }
  851. if len(summaryIds) == 0 {
  852. return
  853. }
  854. totalGroupCond := `a.id IN ?`
  855. totalGroupPars := make([]interface{}, 0)
  856. totalGroupPars = append(totalGroupPars, summaryIds)
  857. invoiceSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 1)
  858. if e != nil {
  859. totalGroupErr = fmt.Errorf("获取汇总货币合计开票金额失败, Err: %s", e.Error())
  860. return
  861. }
  862. paymentSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 2)
  863. if e != nil {
  864. totalGroupErr = fmt.Errorf("获取汇总货币合计到款金额失败, Err: %s", e.Error())
  865. return
  866. }
  867. invoiceSumMap := make(map[string]float64)
  868. paymentSumMap := make(map[string]float64)
  869. for i := range invoiceSumGroup {
  870. invoiceSumMap[invoiceSumGroup[i].CurrencyUnit] = invoiceSumGroup[i].OriginAmountTotal
  871. continue
  872. }
  873. for i := range paymentSumGroup {
  874. paymentSumMap[paymentSumGroup[i].CurrencyUnit] = paymentSumGroup[i].OriginAmountTotal
  875. continue
  876. }
  877. for i := range invoiceCurrencyTotals {
  878. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
  879. invoiceCurrencyTotals[i].Amount = a
  880. }
  881. for i := range paymentCurrencyTotals {
  882. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  883. paymentCurrencyTotals[i].Amount = a
  884. }
  885. }()
  886. wg.Wait()
  887. if listErr != nil {
  888. resp.FailMsg("获取失败", listErr.Error(), c)
  889. return
  890. }
  891. if totalErr != nil {
  892. resp.FailMsg("获取失败", totalErr.Error(), c)
  893. return
  894. }
  895. if totalGroupErr != nil {
  896. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  897. return
  898. }
  899. results.DataList = respList
  900. results.InvoiceTotal = invoiceTotal
  901. results.PaymentTotal = paymentTotal
  902. results.AmountTotal = amountTotal
  903. results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  904. results.PaymentCurrencyTotal = paymentCurrencyTotals
  905. }
  906. // 是否导出
  907. if req.IsExport == 1 {
  908. ExportInvoicePaymentCensusList(c, results)
  909. return
  910. }
  911. page.SetTotal(total)
  912. baseData := new(base.BaseData)
  913. baseData.SetPage(page)
  914. baseData.SetList(results)
  915. resp.OkData("获取成功", baseData, c)
  916. }
  917. // IncomeList
  918. // @Title 业务收入统计表
  919. // @Description 获取业务收入统计表接口
  920. // @Param ListParam query int false "套餐类型: 0-月度; 1-季度; 2-半年度;3-年度;4-月度累计"
  921. // @Success 200 {object} fms.CensusIncomeChartResp
  922. // @router /census/income/list [get]
  923. func (this *InvoicePaymentController) IncomeList(c *gin.Context) {
  924. var req fms.IncomeListReq
  925. if e := c.BindQuery(&req); e != nil {
  926. err, ok := e.(validator.ValidationErrors)
  927. if !ok {
  928. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  929. return
  930. }
  931. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  932. return
  933. }
  934. //收入统计
  935. var incomeList models.CensusIncomeChartResp
  936. ch := make(chan models.CensusIncomeChartResp, 1)
  937. go getCensusIncomeListV2(ch, req)
  938. for v := range ch {
  939. incomeList = v
  940. close(ch)
  941. }
  942. // 是否导出
  943. if req.IsExport == 1 {
  944. ExportIncomeList(c, incomeList.DataList)
  945. return
  946. }
  947. resp.OkData("获取成功", incomeList, c)
  948. }
  949. func getCensusIncomeListV2(ch chan models.CensusIncomeChartResp, req fms.IncomeListReq) (incomeChart models.CensusIncomeChartResp, err error) {
  950. defer func() {
  951. if err != nil {
  952. global.LOG.Error(err)
  953. go alarm_msg.SendAlarmMsg("获取近两年的收入统计数据异常,Err:"+err.Error(), 3)
  954. //go utils.SendEmail(utils.APPNAME+"获取近12个月的收入统计数据异常:"+time.Now().Format("2006-01-02 15:04:05"), err.Error(), utils.EmailSendToUsers)
  955. }
  956. ch <- incomeChart
  957. }()
  958. //todayStr := utils.GetToday("20060102")
  959. //key := "admin:home:fmsIncomeList:" + todayStr
  960. //
  961. //redisJsonData, redisErr := global.Redis.Get(context.TODO(), key).Result()
  962. //if redisErr != nil {
  963. //获取最新的开票到款日期
  964. cond := ``
  965. pars := make([]interface{}, 0)
  966. if req.SellerIds != "" {
  967. sellerIds := strings.Split(req.SellerIds, ",")
  968. cond += ` AND (a.seller_id in ? )`
  969. pars = append(pars, sellerIds, sellerIds)
  970. }
  971. if req.CompanyType == 1 {
  972. cond += ` AND b.new_company = 1 `
  973. } else if req.CompanyType == 2 {
  974. cond += ` AND b.new_company = 0 `
  975. }
  976. invoiceItem, err := fms.GetLatestIncome(cond, pars)
  977. if err != nil {
  978. err = fmt.Errorf("获取最新的开票或到款日期, Err: %s", err.Error())
  979. return
  980. }
  981. invoiceItem.InvoiceDate = invoiceItem.InvoiceDate.AddDate(0,0,-invoiceItem.InvoiceDate.Day()+1)
  982. var dateSlice []string
  983. var totalMoneySlice, prevTotalMoneySlice []float64
  984. var yoySlice []string
  985. var yearNum, monthNum int
  986. var reqStartDate, reqEndDate time.Time
  987. historyTime, _ := time.Parse(utils.FormatDate, "2023-04-01")
  988. if req.StartDate != "" && req.EndDate != "" {
  989. st := fmt.Sprint(req.StartDate, "-01 00:00:00")
  990. ed := fmt.Sprint(req.EndDate, "-01 23:59:59")
  991. reqStartDate, _ = time.Parse(utils.FormatDateTime, st)
  992. reqEndDate, _ = time.Parse(utils.FormatDateTime, ed)
  993. if reqEndDate.After(invoiceItem.InvoiceDate) {
  994. yearNum = invoiceItem.InvoiceDate.Year() - reqStartDate.Year()
  995. monthNum = int(invoiceItem.InvoiceDate.Month() - reqStartDate.Month())
  996. } else {
  997. yearNum = reqEndDate.Year() - reqStartDate.Year()
  998. monthNum = int(reqEndDate.Month() - reqStartDate.Month())
  999. }
  1000. } else {
  1001. yearNum = invoiceItem.InvoiceDate.Year() - 2020
  1002. monthNum = int(invoiceItem.InvoiceDate.Month() - 1)
  1003. }
  1004. if yearNum < 0 {
  1005. yearNum = -yearNum
  1006. }
  1007. if monthNum < 0 {
  1008. monthNum = -monthNum
  1009. }
  1010. numMonth := yearNum*12 + monthNum //共存在多少个月
  1011. //if req.ListParam == "1" {
  1012. // numMonth = numMonth / 3
  1013. //} else if req.ListParam == "2" {
  1014. // numMonth = numMonth / 6
  1015. //} else if req.ListParam == "3" {
  1016. // numMonth = numMonth / 12
  1017. //}
  1018. // 累计值
  1019. var accumulate float64
  1020. var partAccumulate float64
  1021. var historyAccumulate float64
  1022. var partHistoryAccumulate float64
  1023. //dataList := make([]*fms.IncomeSummaryItem, 0)
  1024. //historydataList := make([]*fms.IncomeSummaryItem, 0)
  1025. fmt.Println("numMonth:", numMonth)
  1026. fmt.Println("InvoiceDate:", invoiceItem.InvoiceDate)
  1027. var j int
  1028. for i := 0; i <= numMonth; i++ {
  1029. //timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
  1030. var endDateTime time.Time
  1031. var prevEndDateTime time.Time
  1032. var prevStartDate, prevEndDate string
  1033. var startDate, endDate string
  1034. //开始日期
  1035. if req.StartDate != "" && req.EndDate != "" {
  1036. startDate = reqStartDate.AddDate(0, i, 0).Format("2006-01")
  1037. prevStartDate = reqStartDate.AddDate(-1, i, 0).Format("2006-01")
  1038. } else {
  1039. startDate = invoiceItem.InvoiceDate.AddDate(0, i-numMonth, 0).Format("2006-01")
  1040. prevStartDate = invoiceItem.InvoiceDate.AddDate(-1, i-numMonth, 0).Format("2006-01")
  1041. }
  1042. startDate = fmt.Sprint(startDate, "-01")
  1043. prevStartDate = fmt.Sprint(prevStartDate, "-01")
  1044. startDateTime, _ := time.Parse(utils.FormatDate, startDate)
  1045. prevStartDateTime, _ := time.Parse(utils.FormatDate, prevStartDate)
  1046. //结束日期
  1047. if req.StartDate != "" && req.EndDate != "" {
  1048. endDateTime = reqStartDate.AddDate(0, i+1, -1)
  1049. prevEndDateTime = reqStartDate.AddDate(-1, i+1, -1)
  1050. if reqEndDate.After(invoiceItem.InvoiceDate) {
  1051. endDateTime = invoiceItem.InvoiceDate.AddDate(0, i-numMonth+1, -1)
  1052. prevEndDateTime = invoiceItem.InvoiceDate.AddDate(-1, i-numMonth+1, -1)
  1053. }
  1054. } else {
  1055. endDateTime = invoiceItem.InvoiceDate.AddDate(0, i-numMonth+1, -1)
  1056. prevEndDateTime = invoiceItem.InvoiceDate.AddDate(-1, i-numMonth+1, -1)
  1057. }
  1058. endDate = endDateTime.Format(utils.FormatDate)
  1059. prevEndDate = prevEndDateTime.Format(utils.FormatDate)
  1060. cond := `1 = 1`
  1061. histrtyCond := `1 = 1`
  1062. pars := make([]interface{}, 0)
  1063. historyPars := make([]interface{}, 0)
  1064. prevCond := `1 = 1`
  1065. prevHistoryCond := `1 = 1`
  1066. prevPars := make([]interface{}, 0)
  1067. prevHistoryPars := make([]interface{}, 0)
  1068. if req.CompanyType == 1 {
  1069. cond += ` AND b.new_company = 1 `
  1070. prevCond += ` AND b.new_company = 1 `
  1071. histrtyCond += ` AND new_company = 1 `
  1072. prevHistoryCond += ` AND new_company = 1 `
  1073. } else if req.CompanyType == 2 {
  1074. cond += ` AND b.new_company = 0 `
  1075. prevCond += ` AND b.new_company = 0 `
  1076. histrtyCond += ` AND new_company = 0 `
  1077. prevHistoryCond += ` AND new_company = 0 `
  1078. }
  1079. if req.SellerIds != "" {
  1080. sellerIds := strings.Split(req.SellerIds, ",")
  1081. cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  1082. pars = append(pars, sellerIds, sellerIds)
  1083. prevCond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  1084. prevPars = append(prevPars, sellerIds, sellerIds)
  1085. histrtyCond += ` AND seller_id in ? `
  1086. prevHistoryCond += ` AND seller_id in ? `
  1087. historyPars = append(historyPars, sellerIds)
  1088. prevHistoryPars = append(prevHistoryPars, sellerIds)
  1089. }
  1090. //fmt.Println("i:",i)
  1091. //fmt.Println("j:",j)
  1092. {
  1093. //本期
  1094. st := fmt.Sprint(startDate, " 00:00:00")
  1095. ed := fmt.Sprint(endDate, " 23:59:59")
  1096. //校验日期,分段查询
  1097. if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
  1098. //全部走新查询
  1099. //fmt.Println("新查询")
  1100. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1101. pars = append(pars, st, ed, st, ed)
  1102. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1103. if e != nil {
  1104. return
  1105. }
  1106. // 开票到款金额合计(换算后)
  1107. var amountTotal float64
  1108. if len(summaryIds) > 0 {
  1109. amountCond := `a.id IN ? AND (a.invoice_id <> 0 OR (a.payment_id <> 0 AND a.invoice_id =0))`
  1110. amountPars := make([]interface{}, 0)
  1111. amountPars = append(amountPars, summaryIds)
  1112. amountCond += ` AND (b.invoice_time BETWEEN ? AND ?)`
  1113. amountPars = append(amountPars, st, ed)
  1114. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1115. if e != nil {
  1116. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1117. return
  1118. }
  1119. //dataList = append(dataList, results...)
  1120. var amountSum float64
  1121. for _, result := range results {
  1122. incomeChart.DataList = append(incomeChart.DataList, result)
  1123. amountSum += result.Amount
  1124. }
  1125. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1126. accumulate += amountTotal
  1127. partAccumulate += amountTotal
  1128. }
  1129. if i == j || i == numMonth {
  1130. if req.ListParam == "4" {
  1131. totalMoneySlice = append(totalMoneySlice, accumulate)
  1132. } else if req.ListParam == "0" {
  1133. totalMoneySlice = append(totalMoneySlice, amountTotal)
  1134. } else if i > 0 || i == numMonth {
  1135. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  1136. fmt.Println("partAccumulate:",partAccumulate)
  1137. partAccumulate = 0.0
  1138. }
  1139. }
  1140. } else if endDateTime.Before(historyTime) || endDateTime.Equal(historyTime) {
  1141. //全部走旧查询
  1142. //fmt.Println("旧查询")
  1143. fmt.Println("st:",st)
  1144. fmt.Println("ed:",ed)
  1145. histrtyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1146. historyPars = append(historyPars, st, ed)
  1147. //fmt.Println("st:",st)
  1148. //fmt.Println("ed:",ed)
  1149. // 开票到款金额合计(换算后)
  1150. var amountTotal float64
  1151. results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
  1152. if e != nil {
  1153. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1154. return
  1155. }
  1156. var amountSum float64
  1157. //dataList = append(dataList, results...)
  1158. for _, result := range results {
  1159. incomeChart.DataList = append(incomeChart.DataList, result)
  1160. amountSum += result.Amount
  1161. }
  1162. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1163. accumulate += amountTotal
  1164. partAccumulate += amountTotal
  1165. if i == j || i == numMonth {
  1166. if req.ListParam == "4" {
  1167. totalMoneySlice = append(totalMoneySlice, accumulate)
  1168. } else if req.ListParam == "0" {
  1169. totalMoneySlice = append(totalMoneySlice, amountTotal)
  1170. } else if i > 0 || i == numMonth {
  1171. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  1172. partAccumulate = 0.0
  1173. }
  1174. }
  1175. //fmt.Println("partAccumulate:",partAccumulate)
  1176. }
  1177. //else {
  1178. // //刚好跨过20230301的,各查一部分
  1179. // //fmt.Println("查询3")
  1180. // var historyAmountTotal float64
  1181. // histrtyCond += ` AND (invoice_time BETWEEN ? AND '2023-03-01 23:59:59' ) `
  1182. // historyPars = append(historyPars, st)
  1183. // //// 开票到款金额合计(换算后)
  1184. // var amountTotal float64
  1185. // results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
  1186. // if e != nil {
  1187. // err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1188. // return
  1189. // }
  1190. // var amountSum float64
  1191. // for _, result := range results {
  1192. // incomeChart.DataList = append(incomeChart.DataList, result)
  1193. // amountSum += result.Amount
  1194. // }
  1195. // amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1196. // accumulate += amountTotal
  1197. // historyAmountTotal = amountTotal
  1198. //
  1199. // cond += ` AND ((c.invoice_time BETWEEN '2023-03-02 00:00:00' AND ?) or (d.invoice_time BETWEEN '2023-03-02 00:00:00' AND ?))`
  1200. // pars = append(pars, ed, ed)
  1201. // summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1202. // if e != nil {
  1203. // return
  1204. // }
  1205. //
  1206. // if len(summaryIds) > 0 {
  1207. // amountCond := `a.id IN ? AND (a.invoice_id <> 0 OR (a.payment_id <> 0 AND a.invoice_id =0))`
  1208. // amountPars := make([]interface{}, 0)
  1209. // amountPars = append(amountPars, summaryIds)
  1210. // results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1211. // if e != nil {
  1212. // err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1213. // return
  1214. // }
  1215. // var amountSum float64
  1216. // for _, result := range results {
  1217. // incomeChart.DataList = append(incomeChart.DataList, result)
  1218. // amountSum += result.Amount
  1219. // }
  1220. // amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1221. // accumulate += amountTotal
  1222. // }
  1223. // if req.ListParam == "4" {
  1224. // totalMoneySlice = append(totalMoneySlice, accumulate)
  1225. // } else {
  1226. // totalMoneySlice = append(totalMoneySlice, amountTotal+historyAmountTotal)
  1227. // }
  1228. //
  1229. //}
  1230. }
  1231. { //去年同期,用于计算同比值
  1232. prevSt := fmt.Sprint(prevStartDate, " 00:00:00")
  1233. prevEd := fmt.Sprint(prevEndDate, " 23:59:59")
  1234. //校验日期,分段查询
  1235. if prevStartDateTime.After(historyTime) || prevStartDateTime.Equal(historyTime) {
  1236. //全部走新查询
  1237. prevCond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1238. prevPars = append(prevPars, prevSt, prevEd, prevSt, prevEd)
  1239. prevSummaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(prevCond, prevPars)
  1240. if e != nil {
  1241. return
  1242. }
  1243. // 开票到款金额合计(换算后)
  1244. var prevAmountTotal float64
  1245. if len(prevSummaryIds) > 0 {
  1246. amountCond := `a.id IN ? AND (a.invoice_id <> 0 OR (a.payment_id <> 0 AND a.invoice_id =0))`
  1247. amountPars := make([]interface{}, 0)
  1248. amountPars = append(amountPars, prevSummaryIds)
  1249. amountCond += ` AND (b.invoice_time BETWEEN ? AND ?)`
  1250. amountPars = append(amountPars, prevSt, prevEd)
  1251. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1252. if e != nil {
  1253. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1254. return
  1255. }
  1256. var amountSum float64
  1257. //historydataList = append(historydataList, results...)
  1258. for _, result := range results {
  1259. amountSum += result.Amount
  1260. }
  1261. prevAmountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1262. historyAccumulate += prevAmountTotal
  1263. partHistoryAccumulate += prevAmountTotal
  1264. }
  1265. if i == j || i == numMonth {
  1266. if req.ListParam == "4" {
  1267. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate)
  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. } else if req.ListParam == "0" {
  1301. prevTotalMoneySlice = append(prevTotalMoneySlice, amountTotal)
  1302. } else if i > 0 || i == numMonth {
  1303. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate)
  1304. fmt.Println("partHistoryAccumulate:",partHistoryAccumulate)
  1305. partHistoryAccumulate = 0.0
  1306. }
  1307. }
  1308. //fmt.Println("partHistoryAccumulate:",partHistoryAccumulate)
  1309. }
  1310. //else {
  1311. // //刚好跨过20230301的,各查一部分
  1312. // var historyAmountTotal float64
  1313. // prevHistoryCond += ` AND (invoice_time BETWEEN ? AND '2023-03-01 23:59:59' ) `
  1314. // prevHistoryPars = append(prevHistoryPars, prevSt)
  1315. // // 开票到款金额合计(换算后)
  1316. // var amountTotal float64
  1317. // results, e := fms.GetIncomeHistory(prevHistoryCond, prevHistoryPars)
  1318. // if e != nil {
  1319. // err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1320. // return
  1321. // }
  1322. // var amountSum float64
  1323. // for _, result := range results {
  1324. // amountSum += result.Amount
  1325. // }
  1326. // amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1327. // historyAccumulate += amountTotal
  1328. //
  1329. //
  1330. // prevCond += ` AND ((c.invoice_time BETWEEN '2023-03-02 00:00:00' AND ?) or (d.invoice_time BETWEEN '2023-03-02 00:00:00' AND ?))`
  1331. // prevPars = append(prevPars, prevEd, prevEd)
  1332. // prevSummaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(prevCond, prevPars)
  1333. // if e != nil {
  1334. // return
  1335. // }
  1336. //
  1337. // // 开票到款金额合计(换算后)
  1338. // var prevAmountTotal float64
  1339. //
  1340. // if len(prevSummaryIds) > 0 {
  1341. // amountCond := `a.id IN ? AND (a.invoice_id <> 0 OR (a.payment_id <> 0 AND a.invoice_id =0))`
  1342. // amountPars := make([]interface{}, 0)
  1343. // amountPars = append(amountPars, prevSummaryIds)
  1344. // results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1345. // if e != nil {
  1346. // err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1347. // return
  1348. // }
  1349. // var amountSum float64
  1350. // for _, result := range results {
  1351. // amountSum += result.Amount
  1352. // }
  1353. // prevAmountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1354. // historyAccumulate += prevAmountTotal
  1355. // }
  1356. // if req.ListParam == "4" {
  1357. // prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate)
  1358. // } else {
  1359. // prevTotalMoneySlice = append(prevTotalMoneySlice, prevAmountTotal+historyAmountTotal)
  1360. // }
  1361. //}
  1362. if req.ListParam == "1" && i == j {
  1363. if i == 0{
  1364. dateSlice = append(dateSlice, startDateTime.AddDate(0, 2, 0).Format("06/01"))
  1365. j = j + 2
  1366. } else {
  1367. dateSlice = append(dateSlice, startDateTime.AddDate(0, 3, 0).Format("06/01"))
  1368. j = j + 3
  1369. }
  1370. } else if req.ListParam == "2" && i == j {
  1371. if i == 0{
  1372. dateSlice = append(dateSlice, startDateTime.AddDate(0, 5, 0).Format("06/01"))
  1373. j = j + 5
  1374. } else {
  1375. dateSlice = append(dateSlice, startDateTime.AddDate(0, 6, 0).Format("06/01"))
  1376. j = j + 6
  1377. }
  1378. } else if req.ListParam == "3" && i == j {
  1379. if i == 0{
  1380. dateSlice = append(dateSlice, startDateTime.AddDate(0, 11, 0).Format("06/01"))
  1381. j = j + 11
  1382. } else {
  1383. dateSlice = append(dateSlice, startDateTime.AddDate(0, 12, 0).Format("06/01"))
  1384. j = j + 12
  1385. }
  1386. } else if i == j {
  1387. dateSlice = append(dateSlice, startDateTime.Format("06/01"))
  1388. j++
  1389. }
  1390. }
  1391. }
  1392. //for i, v := range dataList {
  1393. // amountTotal, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", v.Amount), 64)
  1394. // accumulate += amountTotal
  1395. //
  1396. // if req.ListParam == "4" {
  1397. // totalMoneySlice = append(totalMoneySlice, accumulate)
  1398. // } else {
  1399. // totalMoneySlice = append(totalMoneySlice, amountTotal)
  1400. // }
  1401. // if req.ListParam == "1" {
  1402. // i = i + 2
  1403. // } else if req.ListParam == "2" {
  1404. // i = i + 5
  1405. // } else if req.ListParam == "3" {
  1406. // i = i + 11
  1407. // }
  1408. //}
  1409. //
  1410. //for i, v := range historydataList {
  1411. // historyAmountTotal, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", v.Amount), 64)
  1412. // historyAccumulate += historyAmountTotal
  1413. //
  1414. // if req.ListParam == "4" {
  1415. // prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate)
  1416. // } else {
  1417. // prevTotalMoneySlice = append(prevTotalMoneySlice, historyAmountTotal)
  1418. // }
  1419. // if req.ListParam == "1" {
  1420. // i = i + 2
  1421. // } else if req.ListParam == "2" {
  1422. // i = i + 5
  1423. // } else if req.ListParam == "3" {
  1424. // i = i + 11
  1425. // }
  1426. //}
  1427. fmt.Println("prevTotalMoneySlice:", len(prevTotalMoneySlice))
  1428. fmt.Println("totalMoneySlice:", len(totalMoneySlice))
  1429. //计算同比值
  1430. for i := range prevTotalMoneySlice {
  1431. var yoy float64
  1432. var yoyStr string
  1433. //fmt.Println("1:", prevTotalMoneySlice[i])
  1434. //fmt.Println("2:", totalMoneySlice[i])
  1435. //fmt.Println("3:", totalMoneySlice[i]-prevTotalMoneySlice[i])
  1436. if prevTotalMoneySlice[i] != 0 && totalMoneySlice[i] != 0 {
  1437. yoy = (totalMoneySlice[i] - prevTotalMoneySlice[i]) / prevTotalMoneySlice[i]
  1438. yoyStr = fmt.Sprintf("%.4f", yoy)
  1439. if i == len(prevTotalMoneySlice)-1 && i > 0 && req.ListParam == "3"{
  1440. fmt.Println("totalMoneySlice[i-1]:",totalMoneySlice[i-1])
  1441. yoy = (totalMoneySlice[i] - totalMoneySlice[i-1]) / totalMoneySlice[i-1]
  1442. yoyStr = fmt.Sprintf("%.4f", yoy)
  1443. }
  1444. }
  1445. yoySlice = append(yoySlice, yoyStr)
  1446. }
  1447. incomeChart.Title = "开票到款统计图"
  1448. incomeChart.Date = dateSlice
  1449. incomeChart.TotalMoney = totalMoneySlice
  1450. incomeChart.PrevTotalMoney = prevTotalMoneySlice
  1451. incomeChart.Yoy = yoySlice
  1452. //redisJsonData, err := json.Marshal(incomeChart)
  1453. //if err == nil {
  1454. // global.Redis.SetEX(context.TODO(), key, string(redisJsonData), time.Minute*30)
  1455. //}
  1456. //} else {
  1457. // err = json.Unmarshal([]byte(redisJsonData), &incomeChart)
  1458. // if err != nil {
  1459. // fmt.Println("近两年的收入统计数据,json转换失败")
  1460. // }
  1461. //}
  1462. return
  1463. }
  1464. // ExportIncomeList 导出业务收入统计列表
  1465. func ExportIncomeList(c *gin.Context, list []*fms.IncomeSummaryItem) {
  1466. // 生成Excel文件
  1467. xlsxFile := xlsx.NewFile()
  1468. style := xlsx.NewStyle()
  1469. alignment := xlsx.Alignment{
  1470. Horizontal: "center",
  1471. Vertical: "center",
  1472. WrapText: true,
  1473. }
  1474. style.Alignment = alignment
  1475. style.ApplyAlignment = true
  1476. sheetName := "业务收入统计表"
  1477. sheet, err := xlsxFile.AddSheet(sheetName)
  1478. if err != nil {
  1479. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1480. return
  1481. }
  1482. // 数据表头
  1483. rowTitle := []string{"开票日期", "新客户(1)", "客户名称", "金额", "销售"}
  1484. titleRow := sheet.AddRow()
  1485. for i := range rowTitle {
  1486. v := titleRow.AddCell()
  1487. v.SetString(rowTitle[i])
  1488. v.SetStyle(style)
  1489. }
  1490. incomeSummaryItemList := make(fms.IncomeSummaryItemList, 0)
  1491. incomeSummaryItemList = list
  1492. sort.Sort(incomeSummaryItemList)
  1493. // 填充数据
  1494. for _, v := range incomeSummaryItemList {
  1495. dataRow := sheet.AddRow()
  1496. dataRow.AddCell().SetString(v.InvoiceDate.Format(utils.FormatDate)) // 开票日期
  1497. newCompany := 0
  1498. if v.ContractType == 1 {
  1499. newCompany = 1
  1500. }
  1501. dataRow.AddCell().SetString(strconv.Itoa(newCompany)) // 新客户
  1502. dataRow.AddCell().SetString(v.CompanyName) // 客户名称
  1503. dataRow.AddCell().SetString(fmt.Sprint(v.Amount)) // 金额
  1504. dataRow.AddCell().SetString(v.SellerName) // 销售员
  1505. }
  1506. // 输出文件
  1507. var buffer bytes.Buffer
  1508. _ = xlsxFile.Write(&buffer)
  1509. content := bytes.NewReader(buffer.Bytes())
  1510. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1511. fileName := sheetName + randStr + ".xlsx"
  1512. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1513. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1514. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1515. }