invoice_payment.go 57 KB

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