invoice_payment.go 54 KB

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