invoice_payment.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  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/base"
  11. "hongze/fms_api/models/fms"
  12. fmsService "hongze/fms_api/services/fms"
  13. "hongze/fms_api/utils"
  14. "net/http"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. )
  20. // InvoicePaymentController 商品到款统计
  21. type InvoicePaymentController struct{}
  22. // List2 原版(已废弃)
  23. //func (ct *InvoicePaymentController) List2(c *gin.Context) {
  24. // var req fms.InvoicePaymentCensusListReq
  25. // if e := c.BindQuery(&req); e != nil {
  26. // err, ok := e.(validator.ValidationErrors)
  27. // if !ok {
  28. // resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  29. // return
  30. // }
  31. // resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  32. // return
  33. // }
  34. //
  35. // cond := `1 = 1`
  36. // pars := make([]interface{}, 0)
  37. // // 合同编号/客户姓名/销售
  38. // if req.Keyword != "" {
  39. // kw := "%" + req.Keyword + "%"
  40. // cond += ` AND b.company_name LIKE ? OR a.seller_name LIKE ?`
  41. // pars = append(pars, kw, kw)
  42. // }
  43. // if req.SellGroupId > 0 {
  44. // cond += ` AND a.seller_group_id = ?`
  45. // pars = append(pars, req.SellGroupId)
  46. // }
  47. // // 套餐筛选
  48. // if req.ServiceType != 0 {
  49. // registerIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
  50. // if e != nil {
  51. // resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  52. // return
  53. // }
  54. // if len(registerIds) > 0 {
  55. // cond += ` AND b.contract_register_id IN ?`
  56. // pars = append(pars, registerIds)
  57. // } else {
  58. // cond += ` AND 1 = 2`
  59. // }
  60. // }
  61. // // 开票到款日期
  62. // if req.TimeType > 0 && req.StartDate != "" && req.EndDate != "" {
  63. // st := fmt.Sprint(req.StartDate, " 00:00:00")
  64. // ed := fmt.Sprint(req.EndDate, " 23:59:59")
  65. // cond += ` AND a.invoice_type = ? AND (a.invoice_time BETWEEN ? AND ?)`
  66. // pars = append(pars, req.TimeType, st, ed)
  67. // }
  68. // // 已开票
  69. // if req.HasInvoice == 1 && req.HasPayment == 0 {
  70. // cond += ` AND a.invoice_type = 1`
  71. // }
  72. // // 已到款
  73. // if req.HasInvoice == 0 && req.HasPayment == 1 {
  74. // cond += ` AND a.invoice_type = 2`
  75. // }
  76. //
  77. // page := new(base.Page)
  78. // page.SetPageSize(req.PageSize)
  79. // page.SetCurrent(req.Current)
  80. // page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  81. // page.AddOrderItem(base.OrderItem{Column: "b.contract_register_id", Asc: true})
  82. // if req.IsExport == 1 {
  83. // page.SetPageSize(10000)
  84. // page.SetCurrent(1)
  85. // }
  86. //
  87. // list, allRegisterIds, e := fms.GetInvoicePaymentCensusPageList(page, cond, pars)
  88. // if e != nil {
  89. // resp.FailMsg("获取失败", "获取商品到款统计列表失败, Err: "+e.Error(), c)
  90. // return
  91. // }
  92. // total := int64(len(allRegisterIds))
  93. // registerIds := make([]int, 0)
  94. // for i := range list {
  95. // registerIds = append(registerIds, list[i].ContractRegisterId)
  96. // }
  97. //
  98. // results := new(fms.InvoicePaymentCensusResp)
  99. // if len(registerIds) > 0 {
  100. // // 获取开票到款列表
  101. // ivCond := `contract_register_id IN ?`
  102. // ivPars := make([]interface{}, 0)
  103. // ivPars = append(ivPars, registerIds)
  104. // iv := new(fms.ContractInvoice)
  105. // invoiceList, e := iv.List(ivCond, ivPars, "")
  106. // if e != nil {
  107. // resp.FailMsg("获取失败", "获取开票到款列表失败, Err: "+e.Error(), c)
  108. // return
  109. // }
  110. // // 取出开票、到款
  111. // invoiceMap := make(map[int][]*fms.ContractInvoice, 0)
  112. // paymentMap := make(map[int][]*fms.ContractInvoice, 0)
  113. // paymentIds := make([]int, 0)
  114. // for i := range invoiceList {
  115. // if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
  116. // invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoice, 0)
  117. // }
  118. // if paymentMap[invoiceList[i].ContractRegisterId] == nil {
  119. // paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoice, 0)
  120. // }
  121. // if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  122. // invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  123. // }
  124. // if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  125. // paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  126. // paymentIds = append(paymentIds, invoiceList[i].ContractInvoiceId)
  127. // }
  128. // }
  129. //
  130. // // 合同套餐
  131. // contractServiceCond := `contract_register_id IN ?`
  132. // contractServicePars := make([]interface{}, 0)
  133. // contractServicePars = append(contractServicePars, registerIds)
  134. // contractServiceOB := new(fms.ContractService)
  135. // contractServiceList, e := contractServiceOB.List(contractServiceCond, contractServicePars)
  136. // if e != nil {
  137. // resp.FailMsg("获取失败", "获取合同套餐列表失败, Err:"+e.Error(), c)
  138. // return
  139. // }
  140. // contractServiceMap := make(map[int][]*fms.ContractService, 0)
  141. // servicesNameMap := make(map[int][]string, 0)
  142. // for i := range contractServiceList {
  143. // if contractServiceMap[contractServiceList[i].ContractRegisterId] == nil {
  144. // contractServiceMap[contractServiceList[i].ContractRegisterId] = make([]*fms.ContractService, 0)
  145. // }
  146. // contractServiceMap[contractServiceList[i].ContractRegisterId] = append(contractServiceMap[contractServiceList[i].ContractRegisterId], contractServiceList[i])
  147. // servicesNameMap[contractServiceList[i].ContractRegisterId] = append(servicesNameMap[contractServiceList[i].ContractRegisterId], contractServiceList[i].Title)
  148. // }
  149. //
  150. // // 到款套餐分配
  151. // serviceAmountMap := make(map[int][]*fms.ContractPaymentServiceAmount, 0)
  152. // if len(paymentIds) > 0 {
  153. // serviceAmountCond := `contract_payment_id IN ?`
  154. // serviceAmountPars := make([]interface{}, 0)
  155. // serviceAmountPars = append(serviceAmountPars, paymentIds)
  156. // serviceAmountOB := new(fms.ContractPaymentServiceAmount)
  157. // serviceAmountList, e := serviceAmountOB.List(serviceAmountCond, serviceAmountPars)
  158. // if e != nil {
  159. // resp.FailMsg("获取失败", "获取到款套餐分配列表失败, Err:"+e.Error(), c)
  160. // return
  161. // }
  162. // for i := range serviceAmountList {
  163. // if serviceAmountMap[serviceAmountList[i].ContractRegisterId] == nil {
  164. // serviceAmountMap[serviceAmountList[i].ContractRegisterId] = make([]*fms.ContractPaymentServiceAmount, 0)
  165. // }
  166. // serviceAmountMap[serviceAmountList[i].ContractRegisterId] = append(serviceAmountMap[serviceAmountList[i].ContractRegisterId], serviceAmountList[i])
  167. // }
  168. // }
  169. //
  170. // // 整合响应数据
  171. // respList := make([]*fms.InvoicePaymentCensusItem, 0)
  172. // for i := range list {
  173. // v := new(fms.InvoicePaymentCensusItem)
  174. // v.ContractRegisterId = list[i].ContractRegisterId
  175. // v.CompanyName = list[i].CompanyName
  176. // v.NewCompany = list[i].NewCompany
  177. // v.StartDate = list[i].StartDate.Format(utils.FormatDate)
  178. // v.EndDate = list[i].EndDate.Format(utils.FormatDate)
  179. // svList := servicesNameMap[list[i].ContractRegisterId]
  180. // v.ServicesName = strings.Join(svList, ",")
  181. // // 格式化(合并)开票到款数据
  182. // v.InvoicePaymentList = fmsService.MergeInvoiceList2InvoicePaymentCensusInfo(invoiceMap[list[i].ContractRegisterId], paymentMap[list[i].ContractRegisterId],
  183. // contractServiceMap[list[i].ContractRegisterId], serviceAmountMap[list[i].ContractRegisterId])
  184. // respList = append(respList, v)
  185. // }
  186. //
  187. // // 开票到款金额合计(换算后)
  188. // amountTotalCond := `contract_register_id IN ?`
  189. // amountTotalPars := make([]interface{}, 0)
  190. // amountTotalPars = append(amountTotalPars, allRegisterIds)
  191. // amountTotalList, e := fms.GetContractInvoiceAmountTotal(amountTotalCond, amountTotalPars)
  192. // if e != nil {
  193. // resp.FailMsg("获取失败", "获取开票到款金额合计失败, Err:"+e.Error(), c)
  194. // return
  195. // }
  196. // amountTotalMap := make(map[int]float64)
  197. // for i := range amountTotalList {
  198. // amountTotalMap[amountTotalList[i].InvoiceType] = amountTotalList[i].TotalAmount
  199. // }
  200. // invoiceTotal, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amountTotalMap[fms.ContractInvoiceTypeMake]), 64)
  201. // paymentTotal, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amountTotalMap[fms.ContractInvoiceTypePay]), 64)
  202. //
  203. // // 分币种金额统计
  204. // currencyOB := new(fms.CurrencyUnit)
  205. // currencyCond := `enable = 1`
  206. // currencyPars := make([]interface{}, 0)
  207. // currencyList, e := currencyOB.List(currencyCond, currencyPars)
  208. // if e != nil {
  209. // resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  210. // return
  211. // }
  212. // unitMap := make(map[string]string)
  213. // invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  214. // paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  215. // for i := range currencyList {
  216. // unitMap[currencyList[i].Code] = currencyList[i].UnitName
  217. // invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  218. // Name: currencyList[i].Name,
  219. // UnitName: currencyList[i].UnitName,
  220. // Code: currencyList[i].Code,
  221. // FlagImg: currencyList[i].FlagImg,
  222. // })
  223. // paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  224. // Name: currencyList[i].Name,
  225. // UnitName: currencyList[i].UnitName,
  226. // Code: currencyList[i].Code,
  227. // FlagImg: currencyList[i].FlagImg,
  228. // })
  229. // }
  230. // sumList, e := fms.GetInvoiceListCurrencySum(amountTotalCond, amountTotalPars, "currency_unit, invoice_type")
  231. // if e != nil {
  232. // resp.FailMsg("获取失败", "获取商品到款统计货币合计金额失败, Err: "+e.Error(), c)
  233. // return
  234. // }
  235. // invoiceSumMap := make(map[string]float64)
  236. // paymentSumMap := make(map[string]float64)
  237. // for i := range sumList {
  238. // if sumList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  239. // invoiceSumMap[sumList[i].CurrencyUnit] = sumList[i].OriginAmountTotal
  240. // continue
  241. // }
  242. // if sumList[i].InvoiceType == fms.ContractInvoiceTypePay {
  243. // paymentSumMap[sumList[i].CurrencyUnit] = sumList[i].OriginAmountTotal
  244. // }
  245. // }
  246. // for i := range invoiceCurrencyTotals {
  247. // a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
  248. // invoiceCurrencyTotals[i].Amount = a
  249. // }
  250. // for i := range paymentCurrencyTotals {
  251. // a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  252. // paymentCurrencyTotals[i].Amount = a
  253. // }
  254. //
  255. // results.DataList = respList
  256. // results.InvoiceTotal = invoiceTotal
  257. // results.PaymentTotal = paymentTotal
  258. // results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  259. // results.PaymentCurrencyTotal = paymentCurrencyTotals
  260. // }
  261. //
  262. // // 是否导出
  263. // if req.IsExport == 1 {
  264. // ExportInvoicePaymentCensusList(c, results)
  265. // return
  266. // }
  267. // page.SetTotal(total)
  268. // baseData := new(base.BaseData)
  269. // baseData.SetPage(page)
  270. // baseData.SetList(results)
  271. // resp.OkData("获取成功", baseData, c)
  272. //}
  273. // ExportInvoicePaymentCensusList 导出商品到款统计列表
  274. func ExportInvoicePaymentCensusList(c *gin.Context, results *fms.InvoicePaymentCensusResp) {
  275. list := results.DataList
  276. if len(list) == 0 {
  277. resp.Fail("列表数据为空", c)
  278. return
  279. }
  280. // 生成Excel文件
  281. xlsxFile := xlsx.NewFile()
  282. style := xlsx.NewStyle()
  283. alignment := xlsx.Alignment{
  284. Horizontal: "center",
  285. Vertical: "center",
  286. WrapText: true,
  287. }
  288. style.Alignment = alignment
  289. style.ApplyAlignment = true
  290. sheet, err := xlsxFile.AddSheet("商品到款统计")
  291. if err != nil {
  292. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  293. return
  294. }
  295. _ = sheet.SetColWidth(1, 1, 30)
  296. _ = sheet.SetColWidth(3, 3, 30)
  297. // 前三行-开票金额合计
  298. rowA := sheet.AddRow()
  299. cellAA := rowA.AddCell()
  300. cellAA.SetString(fmt.Sprintf("已开票合计金额(换算后):%.2f(元)", results.InvoiceTotal))
  301. rowBData := "已开票金额:"
  302. for _, v := range results.InvoiceCurrencyTotal {
  303. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  304. }
  305. rowB := sheet.AddRow()
  306. rowB.AddCell().SetString(rowBData)
  307. sheet.AddRow()
  308. // 四至六-到款金额合计
  309. rowD := sheet.AddRow()
  310. cellDA := rowD.AddCell()
  311. cellDA.SetString(fmt.Sprintf("已到款合计金额(换算后):%.2f(元)", results.PaymentTotal))
  312. rowEData := "已到款金额:"
  313. for _, v := range results.PaymentCurrencyTotal {
  314. rowEData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  315. }
  316. rowE := sheet.AddRow()
  317. rowE.AddCell().SetString(rowEData)
  318. sheet.AddRow()
  319. // 表头, 套餐动态获取
  320. rowTitle := []string{"序号", "客户名称", "是否新客户", "合同有效期", "开票日", "开票金额", "到款日", "到款金额", "付款方式", "销售",
  321. "销售组别", "销售类型"}
  322. serviceTempCond := ``
  323. serviceTempPars := make([]interface{}, 0)
  324. serviceTempOB := new(fms.ContractServiceTemplate)
  325. serviceTempList, e := serviceTempOB.List(serviceTempCond, serviceTempPars)
  326. if e != nil {
  327. resp.FailData("获取套餐模板列表失败", "Err:"+e.Error(), c)
  328. return
  329. }
  330. serviceTempListMap := make(map[int]*fms.ContractServiceTemplate)
  331. var serviceTempShow [] *fms.ContractServiceTemplate
  332. for i := range serviceTempList {
  333. serviceTempListMap[serviceTempList[i].ServiceTemplateId] = serviceTempList[i]
  334. }
  335. for i := range serviceTempList {
  336. if serviceTempList[i].ProductId == 1 {
  337. rowTitle = append(rowTitle, serviceTempList[i].Title)
  338. serviceTempShow = append(serviceTempShow, serviceTempList[i])
  339. }else if serviceTempList[i].ProductId == 2{
  340. if serviceTempList[i].Title == "行业套餐" || serviceTempList[i].Title == "45万" || serviceTempList[i].Title == "70万"{
  341. continue
  342. }
  343. if serviceTempList[i].Pid > 0 && serviceTempListMap[serviceTempList[i].Pid].Pid > 0 {
  344. continue
  345. }
  346. rowTitle = append(rowTitle, serviceTempList[i].Title)
  347. serviceTempShow = append(serviceTempShow, serviceTempList[i])
  348. }
  349. }
  350. hi := 0
  351. insertHi := 0
  352. titleRow := sheet.AddRow()
  353. for i := range rowTitle {
  354. v := titleRow.AddCell()
  355. v.SetString(rowTitle[i])
  356. v.SetStyle(style)
  357. if rowTitle[i] != "权益大套餐" && rowTitle[i] != "医药" && rowTitle[i] != "消费" && rowTitle[i] != "科技" && rowTitle[i] != "智造" {
  358. v.VMerge = 1
  359. hi ++
  360. }else{
  361. if insertHi == 0 {
  362. insertHi = hi
  363. }
  364. v.HMerge = 1
  365. titleRow.AddCell().SetString("")
  366. }
  367. }
  368. // 新增一行放主观和客观
  369. specialRow := sheet.AddRow()
  370. for i:=0; i< hi; i++ {
  371. if i == insertHi {
  372. v1 := specialRow.AddCell()
  373. v1.SetString("45万")
  374. v1.SetStyle(style)
  375. v1 = specialRow.AddCell()
  376. v1.SetString("70万")
  377. v1.SetStyle(style)
  378. for j:=0; j<8;j++ {
  379. if j%2 ==0 {
  380. v1 = specialRow.AddCell()
  381. v1.SetString("主观")
  382. v1.SetStyle(style)
  383. }else{
  384. v1 = specialRow.AddCell()
  385. v1.SetString("客观")
  386. v1.SetStyle(style)
  387. }
  388. }
  389. }else{
  390. v := specialRow.AddCell()
  391. v.SetString("")
  392. }
  393. }
  394. newCompanyMap := map[int]string{0: "否", 1: "是"}
  395. sellerTypeMap := map[int]string{1:"FICC销售", 2:"权益销售"}
  396. for k, v := range list {
  397. dataRow := sheet.AddRow()
  398. // 前四个单元格根据每行开票到款条数向下合并
  399. l := len(v.InvoicePaymentList)
  400. mergeRowNum := l - 1
  401. // 序号
  402. sortNum := k + 1
  403. colA := dataRow.AddCell()
  404. colA.VMerge = mergeRowNum
  405. colA.SetString(fmt.Sprint(sortNum))
  406. // 客户名称
  407. colB := dataRow.AddCell()
  408. colB.VMerge = mergeRowNum
  409. colB.SetString(v.CompanyName)
  410. // 是否新客户
  411. colC := dataRow.AddCell()
  412. colC.VMerge = mergeRowNum
  413. colC.SetString(newCompanyMap[v.NewCompany])
  414. // 合同有效期
  415. colD := dataRow.AddCell()
  416. colD.VMerge = mergeRowNum
  417. colD.SetString(fmt.Sprint(v.StartDate, "至", v.EndDate))
  418. // 开票到款信息
  419. for k2, v2 := range v.InvoicePaymentList {
  420. rowData := []string{
  421. v2.InvoiceDate, // 开票日
  422. fmt.Sprint(v2.InvoiceAmount), // 开票金额
  423. v2.PaymentDate, // 到款日
  424. fmt.Sprint(v2.PaymentAmount), // 到款金额
  425. fms.ContractPaymentPayTypeNameMap[v2.PayType], // 付款方式
  426. v2.SellerName, // 销售
  427. v2.SellerGroupName, // 组别
  428. sellerTypeMap[v2.SellerType], // 销售类型
  429. }
  430. // 套餐金额信息
  431. for i := range serviceTempShow {
  432. sa := ""
  433. for s2 := range v2.ServiceAmountList {
  434. item := v2.ServiceAmountList[s2]
  435. if item.ServiceTemplateId == serviceTempList[i].ServiceTemplateId {
  436. if serviceTempList[i].Title == "医药" || serviceTempList[i].Title == "消费" {
  437. // todo 则需要查询对应的主观和客观的金额
  438. break
  439. }else{
  440. sa = fmt.Sprint(v2.ServiceAmountList[s2].Amount)
  441. break
  442. }
  443. }
  444. }
  445. rowData = append(rowData, sa)
  446. }
  447. // 首行开票到款
  448. if k2 == 0 {
  449. for i := range rowData {
  450. dataRow.AddCell().SetString(rowData[i])
  451. }
  452. continue
  453. }
  454. // 其他行开票到款, 加四列空的单元格用于合并
  455. dataRowExtra := sheet.AddRow()
  456. for i := 0; i < 4; i++ {
  457. dataRowExtra.AddCell()
  458. }
  459. for i := range rowData {
  460. dataRowExtra.AddCell().SetString(rowData[i])
  461. }
  462. }
  463. }
  464. // 输出文件
  465. var buffer bytes.Buffer
  466. _ = xlsxFile.Write(&buffer)
  467. content := bytes.NewReader(buffer.Bytes())
  468. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  469. fileName := "商品到款统计_" + randStr + ".xlsx"
  470. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  471. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  472. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  473. }
  474. // List
  475. // @Title 商品到款统计列表
  476. // @Description 商品到款统计列表
  477. // @Param Keyword query string false "关键词"
  478. // @Param SellGroupId query int false "销售组别ID"
  479. // @Param ServiceType query int false "套餐类型"
  480. // @Param StartDate query string false "合同开始日期"
  481. // @Param EndDate query string false "合同结束日期"
  482. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  483. // @Param HasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
  484. // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
  485. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  486. // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'invoice_time':开票日 、 'payment_date':到款日"
  487. // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
  488. // @Success 200 {object} fms.ContractRegisterItem
  489. // @router /census/invoice_payment/list [get]
  490. func (ct *InvoicePaymentController) List(c *gin.Context) {
  491. var req fms.InvoicePaymentCensusListReq
  492. if e := c.BindQuery(&req); e != nil {
  493. err, ok := e.(validator.ValidationErrors)
  494. if !ok {
  495. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  496. return
  497. }
  498. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  499. return
  500. }
  501. cond := `1 = 1`
  502. pars := make([]interface{}, 0)
  503. // 客户姓名/销售
  504. if req.Keyword != "" {
  505. kw := "%" + req.Keyword + "%"
  506. cond += ` AND b.company_name LIKE ?`
  507. pars = append(pars, kw)
  508. }
  509. if req.SellerIds != "" {
  510. sellerIds := strings.Split(req.SellerIds, ",")
  511. cond += ` AND (c.seller_id in ?)`
  512. pars = append(pars, sellerIds)
  513. }
  514. // 套餐筛选
  515. if req.ServiceTypes != "" {
  516. serviceTypes := strings.Split(req.ServiceTypes, ",")
  517. tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  518. if e != nil {
  519. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  520. return
  521. }
  522. if len(tempRegisterIds) > 0 {
  523. cond += ` AND a.register_id IN ?`
  524. pars = append(pars, tempRegisterIds)
  525. } else {
  526. cond += ` AND 1 = 2`
  527. }
  528. }
  529. // 开票到款日期
  530. if req.StartDate != "" && req.EndDate != "" {
  531. st := fmt.Sprint(req.StartDate, " 00:00:00")
  532. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  533. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  534. pars = append(pars, st, ed, st, ed)
  535. }
  536. if req.HasInvoice == "1" {
  537. cond += ` AND a.invoice_id > 0 `
  538. }else if req.HasInvoice == "0" {
  539. cond += ` AND a.invoice_id = 0 `
  540. }
  541. if req.HasPayment == "1" {
  542. cond += ` AND a.payment_id > 0 `
  543. }else if req.HasPayment == "0" {
  544. cond += ` AND a.payment_id = 0 `
  545. }
  546. page := new(base.Page)
  547. page.SetPageSize(req.PageSize)
  548. page.SetCurrent(req.Current)
  549. //排序
  550. if req.SortType == "" {
  551. req.SortType = "desc"
  552. }
  553. if req.SortType != "desc" && req.SortType != "asc" {
  554. resp.Fail("排序类型不正确", c)
  555. return
  556. }
  557. if req.SortParam == "" {
  558. page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: true})
  559. page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: false})
  560. page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: false})
  561. page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: false})
  562. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  563. }else if req.SortParam == "invoice_time" {
  564. if req.SortType == "asc" {
  565. page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: false})
  566. page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: true})
  567. page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: true})
  568. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: true})
  569. }else{
  570. page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: true})
  571. page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: false})
  572. page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: false})
  573. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  574. }
  575. }else if req.SortParam == "payment_date" {
  576. if req.SortType == "asc" {
  577. page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: false})
  578. page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: true})
  579. page.AddOrderItem(base.OrderItem{Column: "d.amount", Asc: true})
  580. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: true})
  581. }else{
  582. page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: true})
  583. page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: false})
  584. page.AddOrderItem(base.OrderItem{Column: "d.amount", Asc: false})
  585. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  586. }
  587. }else{
  588. resp.Fail("排序字段不正确", c)
  589. return
  590. }
  591. if req.IsExport == 1 {
  592. page.SetPageSize(10000)
  593. page.SetCurrent(1)
  594. }
  595. registerList, total, e := fms.GetInvoicePaymentCensusPageList(page, cond, pars)
  596. if e != nil {
  597. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  598. return
  599. }
  600. queryRegisterIds := make([]int, 0)
  601. for i := range registerList {
  602. queryRegisterIds = append(queryRegisterIds, registerList[i].ContractRegisterId)
  603. }
  604. results := new(fms.InvoicePaymentCensusResp)
  605. if len(queryRegisterIds) > 0 {
  606. // 获取汇总数据IDs, 用于查询合计数据
  607. summaryIdsCond := cond
  608. summaryIdsPars := pars
  609. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(summaryIdsCond, summaryIdsPars)
  610. if e != nil {
  611. resp.FailMsg("获取失败", "获取商品到款汇总IDs失败, Err: "+e.Error(), c)
  612. return
  613. }
  614. var listErr, totalErr, totalGroupErr error
  615. wg := sync.WaitGroup{}
  616. // 响应列表
  617. respList := make([]*fms.InvoicePaymentCensusItem, 0)
  618. summaryList := make([]*fms.InvoicePaymentSummaryItem, 0)
  619. wg.Add(1)
  620. go func() {
  621. defer wg.Done()
  622. // 获取汇总数据
  623. summaryCond := cond
  624. summaryCond += ` AND a.register_id IN ?`
  625. summaryPars := pars
  626. summaryPars = append(summaryPars, queryRegisterIds)
  627. summaryData, e := fms.GetInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  628. if e != nil {
  629. resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
  630. return
  631. }
  632. summaryList = summaryData
  633. //summaryIds := make([]int, 0)
  634. paymentIds := make([]int, 0)
  635. for i := range summaryList {
  636. //summaryIds = append(summaryIds, summaryList[i].SummaryId)
  637. if summaryList[i].PaymentId > 0 {
  638. paymentIds = append(paymentIds, summaryList[i].PaymentId)
  639. }
  640. }
  641. // 合同套餐
  642. /*contractServiceCond := `contract_register_id IN ?`
  643. contractServicePars := make([]interface{}, 0)
  644. contractServicePars = append(contractServicePars, queryRegisterIds)
  645. contractServiceOB := new(fms.ContractService)
  646. contractServiceList, e := contractServiceOB.List(contractServiceCond, contractServicePars)
  647. if e != nil {
  648. listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
  649. return
  650. }
  651. contractServiceMap := make(map[int][]*fms.ContractService, 0)
  652. servicesNameMap := make(map[int][]string, 0)
  653. for i := range contractServiceList {
  654. if contractServiceMap[contractServiceList[i].ContractRegisterId] == nil {
  655. contractServiceMap[contractServiceList[i].ContractRegisterId] = make([]*fms.ContractService, 0)
  656. }
  657. contractServiceMap[contractServiceList[i].ContractRegisterId] = append(contractServiceMap[contractServiceList[i].ContractRegisterId], contractServiceList[i])
  658. servicesNameMap[contractServiceList[i].ContractRegisterId] = append(servicesNameMap[contractServiceList[i].ContractRegisterId], contractServiceList[i].Title)
  659. }
  660. */
  661. servicesNameMap, serviceFormatMap, e := fmsService.GetContractServiceNameFormat(queryRegisterIds)
  662. if e != nil {
  663. listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
  664. return
  665. }
  666. // 到款套餐分配
  667. serviceAmountMap := make(map[int][]*fms.ContractPaymentServiceAmount, 0)
  668. if len(paymentIds) > 0 {
  669. serviceAmountCond := `contract_payment_id IN ?`
  670. serviceAmountPars := make([]interface{}, 0)
  671. serviceAmountPars = append(serviceAmountPars, paymentIds)
  672. serviceAmountOB := new(fms.ContractPaymentServiceAmount)
  673. serviceAmountList, e := serviceAmountOB.List(serviceAmountCond, serviceAmountPars)
  674. if e != nil {
  675. listErr = fmt.Errorf("获取到款套餐分配列表失败, Err: %s", e.Error())
  676. return
  677. }
  678. for i := range serviceAmountList {
  679. if serviceAmountMap[serviceAmountList[i].ContractPaymentId] == nil {
  680. serviceAmountMap[serviceAmountList[i].ContractPaymentId] = make([]*fms.ContractPaymentServiceAmount, 0)
  681. }
  682. serviceAmountMap[serviceAmountList[i].ContractPaymentId] = append(serviceAmountMap[serviceAmountList[i].ContractPaymentId], serviceAmountList[i])
  683. }
  684. }
  685. // 重组汇总数据
  686. summaryMap := make(map[int][]*fms.InvoicePaymentCensusInfo)
  687. amountMap := make(map[string]*fms.ContractPaymentServiceAmount)
  688. for i := range summaryList {
  689. v := new(fms.InvoicePaymentCensusInfo)
  690. v.InvoiceId = summaryList[i].InvoiceId
  691. v.InvoiceDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].InvoiceDate)
  692. v.InvoiceAmount = summaryList[i].InvoiceAmount
  693. v.SellerId = summaryList[i].SellerId
  694. v.SellerName = summaryList[i].SellerName
  695. v.SellerGroupId = summaryList[i].SellerGroupId
  696. v.SellerGroupName = summaryList[i].SellerGroupName
  697. v.SellerType = summaryList[i].ServiceProductId
  698. v.PaymentId = summaryList[i].PaymentId
  699. v.PaymentDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].PaymentDate)
  700. v.PaymentAmount = summaryList[i].PaymentAmount
  701. v.PayType = summaryList[i].PayType
  702. // 套餐到款分配
  703. svaList := make([]*fms.ContractPaymentServiceAmountItem, 0)
  704. amountList := serviceAmountMap[summaryList[i].PaymentId]
  705. if amountList != nil {
  706. for i := range amountList {
  707. k := fmt.Sprintf("%d-%d", amountList[i].ContractPaymentId, amountList[i].ServiceTemplateId)
  708. amountMap[k] = amountList[i]
  709. }
  710. }
  711. // 合同对应的所有套餐
  712. svList := serviceFormatMap[summaryList[i].RegisterId]
  713. if svList != nil {
  714. for ii := range svList {
  715. vv := new(fms.ContractPaymentServiceAmountItem)
  716. vv.ServiceTemplateId = svList[ii].ServiceTemplateId
  717. vv.ServiceTemplateName = svList[ii].FormatTitle
  718. vv.ServiceTemplatePid = svList[ii].ServiceTemplatePid
  719. k2 := fmt.Sprintf("%d-%d", summaryList[i].PaymentId, svList[ii].ServiceTemplateId)
  720. a := amountMap[k2]
  721. if a != nil {
  722. vv.ContractPaymentServiceAmountId = a.ContractPaymentServiceAmountId
  723. vv.ContractPaymentId = a.ContractPaymentId
  724. vv.Amount = a.Amount
  725. }
  726. svaList = append(svaList, vv)
  727. }
  728. }
  729. v.ServiceAmountList = svaList
  730. summaryMap[summaryList[i].SummaryId] = append(summaryMap[summaryList[i].SummaryId], v)
  731. }
  732. // 响应列表
  733. for i := range registerList {
  734. v := new(fms.InvoicePaymentCensusItem)
  735. v.SummaryId = registerList[i].SummaryId
  736. v.ContractRegisterId = registerList[i].ContractRegisterId
  737. v.CompanyName = registerList[i].CompanyName
  738. v.NewCompany = registerList[i].NewCompany
  739. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  740. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  741. v.ServicesName = servicesNameMap[registerList[i].ContractRegisterId]
  742. v.InvoicePaymentList = summaryMap[registerList[i].SummaryId]
  743. respList = append(respList, v)
  744. }
  745. }()
  746. // 开票到款金额合计(换算后)
  747. var invoiceTotal, paymentTotal float64
  748. wg.Add(1)
  749. go func() {
  750. defer wg.Done()
  751. if len(summaryIds) == 0 {
  752. return
  753. }
  754. amountTotalCond := `a.id IN ?`
  755. amountTotalPars := make([]interface{}, 0)
  756. amountTotalPars = append(amountTotalPars, summaryIds)
  757. invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
  758. if e != nil {
  759. totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
  760. return
  761. }
  762. invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
  763. paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
  764. if e != nil {
  765. totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
  766. return
  767. }
  768. paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
  769. }()
  770. // 分币种金额统计
  771. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  772. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  773. wg.Add(1)
  774. go func() {
  775. defer wg.Done()
  776. currencyOB := new(fms.CurrencyUnit)
  777. currencyCond := `enable = 1`
  778. currencyPars := make([]interface{}, 0)
  779. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  780. if e != nil {
  781. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  782. return
  783. }
  784. unitMap := make(map[string]string)
  785. for i := range currencyList {
  786. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  787. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  788. Name: currencyList[i].Name,
  789. UnitName: currencyList[i].UnitName,
  790. Code: currencyList[i].Code,
  791. FlagImg: currencyList[i].FlagImg,
  792. })
  793. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  794. Name: currencyList[i].Name,
  795. UnitName: currencyList[i].UnitName,
  796. Code: currencyList[i].Code,
  797. FlagImg: currencyList[i].FlagImg,
  798. })
  799. }
  800. if len(summaryIds) == 0 {
  801. return
  802. }
  803. totalGroupCond := `a.id IN ?`
  804. totalGroupPars := make([]interface{}, 0)
  805. totalGroupPars = append(totalGroupPars, summaryIds)
  806. invoiceSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 1)
  807. if e != nil {
  808. totalGroupErr = fmt.Errorf("获取汇总货币合计开票金额失败, Err: %s", e.Error())
  809. return
  810. }
  811. paymentSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 2)
  812. if e != nil {
  813. totalGroupErr = fmt.Errorf("获取汇总货币合计到款金额失败, Err: %s", e.Error())
  814. return
  815. }
  816. invoiceSumMap := make(map[string]float64)
  817. paymentSumMap := make(map[string]float64)
  818. for i := range invoiceSumGroup {
  819. invoiceSumMap[invoiceSumGroup[i].CurrencyUnit] = invoiceSumGroup[i].OriginAmountTotal
  820. continue
  821. }
  822. for i := range paymentSumGroup {
  823. paymentSumMap[paymentSumGroup[i].CurrencyUnit] = paymentSumGroup[i].OriginAmountTotal
  824. continue
  825. }
  826. for i := range invoiceCurrencyTotals {
  827. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
  828. invoiceCurrencyTotals[i].Amount = a
  829. }
  830. for i := range paymentCurrencyTotals {
  831. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  832. paymentCurrencyTotals[i].Amount = a
  833. }
  834. }()
  835. wg.Wait()
  836. if listErr != nil {
  837. resp.FailMsg("获取失败", listErr.Error(), c)
  838. return
  839. }
  840. if totalErr != nil {
  841. resp.FailMsg("获取失败", totalErr.Error(), c)
  842. return
  843. }
  844. if totalGroupErr != nil {
  845. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  846. return
  847. }
  848. results.DataList = respList
  849. results.InvoiceTotal = invoiceTotal
  850. results.PaymentTotal = paymentTotal
  851. results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  852. results.PaymentCurrencyTotal = paymentCurrencyTotals
  853. }
  854. // 是否导出
  855. if req.IsExport == 1 {
  856. ExportInvoicePaymentCensusList(c, results)
  857. return
  858. }
  859. page.SetTotal(total)
  860. baseData := new(base.BaseData)
  861. baseData.SetPage(page)
  862. baseData.SetList(results)
  863. resp.OkData("获取成功", baseData, c)
  864. }