invoice_payment.go 57 KB

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