invoice_payment.go 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  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(amountPars, 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 ? `
  1110. amountPars := make([]interface{}, 0)
  1111. amountPars = append(amountPars, summaryIds)
  1112. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1113. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1114. amountPars = append(amountPars, st, ed, st, ed)
  1115. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1116. if e != nil {
  1117. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1118. return
  1119. }
  1120. //dataList = append(dataList, results...)
  1121. var amountSum float64
  1122. for _, result := range results {
  1123. incomeChart.DataList = append(incomeChart.DataList, result)
  1124. amountSum += result.Amount
  1125. fmt.Println("result.Amount:",result.Amount)
  1126. }
  1127. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1128. accumulate += amountTotal
  1129. partAccumulate += amountTotal
  1130. }
  1131. if i == j || i == numMonth {
  1132. if req.ListParam == "4" {
  1133. totalMoneySlice = append(totalMoneySlice, accumulate)
  1134. } else if req.ListParam == "0" {
  1135. totalMoneySlice = append(totalMoneySlice, amountTotal)
  1136. } else if i > 0 || i == numMonth {
  1137. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  1138. fmt.Println("partAccumulate:",partAccumulate)
  1139. partAccumulate = 0.0
  1140. }
  1141. }
  1142. } else if endDateTime.Before(historyTime) || endDateTime.Equal(historyTime) {
  1143. //全部走旧查询
  1144. //fmt.Println("旧查询")
  1145. fmt.Println("st:",st)
  1146. fmt.Println("ed:",ed)
  1147. histrtyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1148. historyPars = append(historyPars, st, ed)
  1149. //fmt.Println("st:",st)
  1150. //fmt.Println("ed:",ed)
  1151. // 开票到款金额合计(换算后)
  1152. var amountTotal float64
  1153. results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
  1154. if e != nil {
  1155. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1156. return
  1157. }
  1158. var amountSum float64
  1159. //dataList = append(dataList, results...)
  1160. for _, result := range results {
  1161. incomeChart.DataList = append(incomeChart.DataList, result)
  1162. amountSum += result.Amount
  1163. }
  1164. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1165. accumulate += amountTotal
  1166. partAccumulate += amountTotal
  1167. if i == j || i == numMonth {
  1168. if req.ListParam == "4" {
  1169. totalMoneySlice = append(totalMoneySlice, accumulate)
  1170. } else if req.ListParam == "0" {
  1171. totalMoneySlice = append(totalMoneySlice, amountTotal)
  1172. } else if i > 0 || i == numMonth {
  1173. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  1174. partAccumulate = 0.0
  1175. }
  1176. }
  1177. //fmt.Println("partAccumulate:",partAccumulate)
  1178. }
  1179. }
  1180. { //去年同期,用于计算同比值
  1181. prevSt := fmt.Sprint(prevStartDate, " 00:00:00")
  1182. prevEd := fmt.Sprint(prevEndDate, " 23:59:59")
  1183. //校验日期,分段查询
  1184. if prevStartDateTime.After(historyTime) || prevStartDateTime.Equal(historyTime) {
  1185. //全部走新查询
  1186. prevCond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1187. prevPars = append(prevPars, prevSt, prevEd, prevSt, prevEd)
  1188. prevSummaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(prevCond, prevPars)
  1189. if e != nil {
  1190. return
  1191. }
  1192. // 开票到款金额合计(换算后)
  1193. var prevAmountTotal float64
  1194. if len(prevSummaryIds) > 0 {
  1195. amountCond := `a.id IN ? `
  1196. amountPars := make([]interface{}, 0)
  1197. amountPars = append(amountPars, prevSummaryIds)
  1198. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1199. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1200. amountPars = append(amountPars, prevSt, prevEd)
  1201. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1202. if e != nil {
  1203. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1204. return
  1205. }
  1206. var amountSum float64
  1207. //historydataList = append(historydataList, results...)
  1208. for _, result := range results {
  1209. amountSum += result.Amount
  1210. }
  1211. prevAmountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1212. historyAccumulate += prevAmountTotal
  1213. partHistoryAccumulate += prevAmountTotal
  1214. }
  1215. if i == j || i == numMonth {
  1216. if req.ListParam == "4" {
  1217. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate)
  1218. } else if req.ListParam == "0" {
  1219. prevTotalMoneySlice = append(prevTotalMoneySlice, prevAmountTotal)
  1220. } else if i > 0 || i == numMonth {
  1221. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate)
  1222. fmt.Println("partHistoryAccumulate:",partHistoryAccumulate)
  1223. partHistoryAccumulate = 0.0
  1224. }
  1225. }
  1226. } else if prevEndDateTime.Before(historyTime) || prevEndDateTime.Equal(historyTime) {
  1227. //全部走旧查询
  1228. fmt.Println("prevSt:",prevSt)
  1229. fmt.Println("prevEd:",prevEd)
  1230. prevHistoryCond += ` AND (invoice_time BETWEEN ? AND ?)`
  1231. prevHistoryPars = append(prevHistoryPars, prevSt, prevEd)
  1232. // 开票到款金额合计(换算后)
  1233. var amountTotal float64
  1234. results, e := fms.GetIncomeHistory(prevHistoryCond, prevHistoryPars)
  1235. if e != nil {
  1236. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1237. return
  1238. }
  1239. //historydataList = append(historydataList, results...)
  1240. var amountSum float64
  1241. for _, result := range results {
  1242. amountSum += result.Amount
  1243. }
  1244. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1245. historyAccumulate += amountTotal
  1246. partHistoryAccumulate += amountTotal
  1247. if i == j || i == numMonth {
  1248. if req.ListParam == "4" {
  1249. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate)
  1250. } else if req.ListParam == "0" {
  1251. prevTotalMoneySlice = append(prevTotalMoneySlice, amountTotal)
  1252. } else if i > 0 || i == numMonth {
  1253. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate)
  1254. fmt.Println("partHistoryAccumulate:",partHistoryAccumulate)
  1255. partHistoryAccumulate = 0.0
  1256. }
  1257. }
  1258. //fmt.Println("partHistoryAccumulate:",partHistoryAccumulate)
  1259. }
  1260. if req.ListParam == "1" && i == j {
  1261. if i == 0{
  1262. dateSlice = append(dateSlice, startDateTime.AddDate(0, 2, 0).Format("06/01"))
  1263. j = j + 2
  1264. } else {
  1265. dateSlice = append(dateSlice, startDateTime.AddDate(0, 3, 0).Format("06/01"))
  1266. j = j + 3
  1267. }
  1268. } else if req.ListParam == "2" && i == j {
  1269. if i == 0{
  1270. dateSlice = append(dateSlice, startDateTime.AddDate(0, 5, 0).Format("06/01"))
  1271. j = j + 5
  1272. } else {
  1273. dateSlice = append(dateSlice, startDateTime.AddDate(0, 6, 0).Format("06/01"))
  1274. j = j + 6
  1275. }
  1276. } else if req.ListParam == "3" && i == j {
  1277. if i == 0{
  1278. dateSlice = append(dateSlice, startDateTime.AddDate(0, 11, 0).Format("06/01"))
  1279. j = j + 11
  1280. } else {
  1281. dateSlice = append(dateSlice, startDateTime.AddDate(0, 12, 0).Format("06/01"))
  1282. j = j + 12
  1283. }
  1284. } else if i == j {
  1285. dateSlice = append(dateSlice, startDateTime.Format("06/01"))
  1286. j++
  1287. }
  1288. }
  1289. }
  1290. fmt.Println("prevTotalMoneySlice:", len(prevTotalMoneySlice))
  1291. fmt.Println("totalMoneySlice:", len(totalMoneySlice))
  1292. //计算同比值
  1293. for i := range prevTotalMoneySlice {
  1294. var yoy float64
  1295. var yoyStr string
  1296. //fmt.Println("1:", prevTotalMoneySlice[i])
  1297. //fmt.Println("2:", totalMoneySlice[i])
  1298. //fmt.Println("3:", totalMoneySlice[i]-prevTotalMoneySlice[i])
  1299. if prevTotalMoneySlice[i] != 0 && totalMoneySlice[i] != 0 {
  1300. yoy = (totalMoneySlice[i] - prevTotalMoneySlice[i]) / prevTotalMoneySlice[i]
  1301. yoyStr = fmt.Sprintf("%.4f", yoy)
  1302. if i == len(prevTotalMoneySlice)-1 && i > 0 && req.ListParam == "3"{
  1303. fmt.Println("totalMoneySlice[i-1]:",totalMoneySlice[i-1])
  1304. yoy = (totalMoneySlice[i] - totalMoneySlice[i-1]) / totalMoneySlice[i-1]
  1305. yoyStr = fmt.Sprintf("%.4f", yoy)
  1306. }
  1307. }
  1308. yoySlice = append(yoySlice, yoyStr)
  1309. }
  1310. incomeChart.Title = "开票到款统计图"
  1311. incomeChart.Date = dateSlice
  1312. incomeChart.TotalMoney = totalMoneySlice
  1313. incomeChart.PrevTotalMoney = prevTotalMoneySlice
  1314. incomeChart.Yoy = yoySlice
  1315. //redisJsonData, err := json.Marshal(incomeChart)
  1316. //if err == nil {
  1317. // global.Redis.SetEX(context.TODO(), key, string(redisJsonData), time.Minute*30)
  1318. //}
  1319. //} else {
  1320. // err = json.Unmarshal([]byte(redisJsonData), &incomeChart)
  1321. // if err != nil {
  1322. // fmt.Println("近两年的收入统计数据,json转换失败")
  1323. // }
  1324. //}
  1325. return
  1326. }
  1327. // ExportIncomeList 导出业务收入统计列表
  1328. func ExportIncomeList(c *gin.Context, list []*fms.IncomeSummaryItem) {
  1329. // 生成Excel文件
  1330. xlsxFile := xlsx.NewFile()
  1331. style := xlsx.NewStyle()
  1332. alignment := xlsx.Alignment{
  1333. Horizontal: "center",
  1334. Vertical: "center",
  1335. WrapText: true,
  1336. }
  1337. style.Alignment = alignment
  1338. style.ApplyAlignment = true
  1339. sheetName := "业务收入统计表"
  1340. sheet, err := xlsxFile.AddSheet(sheetName)
  1341. if err != nil {
  1342. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1343. return
  1344. }
  1345. // 数据表头
  1346. rowTitle := []string{"开票日期", "新客户(1)", "客户名称", "金额", "销售"}
  1347. titleRow := sheet.AddRow()
  1348. for i := range rowTitle {
  1349. v := titleRow.AddCell()
  1350. v.SetString(rowTitle[i])
  1351. v.SetStyle(style)
  1352. }
  1353. incomeSummaryItemList := make(fms.IncomeSummaryItemList, 0)
  1354. incomeSummaryItemList = list
  1355. sort.Sort(incomeSummaryItemList)
  1356. // 填充数据
  1357. for _, v := range incomeSummaryItemList {
  1358. dataRow := sheet.AddRow()
  1359. dataRow.AddCell().SetString(v.InvoiceDate.Format(utils.FormatDate)) // 开票日期
  1360. newCompany := 0
  1361. if v.ContractType == 1 {
  1362. newCompany = 1
  1363. }
  1364. dataRow.AddCell().SetString(strconv.Itoa(newCompany)) // 新客户
  1365. dataRow.AddCell().SetString(v.CompanyName) // 客户名称
  1366. dataRow.AddCell().SetString(fmt.Sprint(v.Amount)) // 金额
  1367. dataRow.AddCell().SetString(v.SellerName) // 销售员
  1368. }
  1369. // 输出文件
  1370. var buffer bytes.Buffer
  1371. _ = xlsxFile.Write(&buffer)
  1372. content := bytes.NewReader(buffer.Bytes())
  1373. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1374. fileName := sheetName + randStr + ".xlsx"
  1375. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1376. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1377. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1378. }