invoice_payment.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. "strings"
  16. "time"
  17. )
  18. // InvoicePaymentController 商品到款统计
  19. type InvoicePaymentController struct{}
  20. // List
  21. // @Title 商品到款统计列表
  22. // @Description 商品到款统计列表
  23. // @Param Keyword query string false "关键词"
  24. // @Param SellGroupId query int false "销售组别ID"
  25. // @Param ServiceType query int false "套餐类型"
  26. // @Param StartDate query string false "合同开始日期"
  27. // @Param EndDate query string false "合同结束日期"
  28. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  29. // @Param HasInvoice query int false "是否已开票: 0-否; 1-是"
  30. // @Param HasPayment query int false "是否已到款: 0-否; 1-是"
  31. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  32. // @Success 200 {object} fms.ContractRegisterItem
  33. // @router /census/invoice_payment/list [get]
  34. func (ct *InvoicePaymentController) List(c *gin.Context) {
  35. var req fms.InvoicePaymentCensusListReq
  36. if e := c.BindQuery(&req); e != nil {
  37. err, ok := e.(validator.ValidationErrors)
  38. if !ok {
  39. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  40. return
  41. }
  42. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  43. return
  44. }
  45. cond := `1 = 1`
  46. pars := make([]interface{}, 0)
  47. // 合同编号/客户姓名/销售
  48. if req.Keyword != "" {
  49. kw := "%" + req.Keyword + "%"
  50. cond += ` AND b.company_name LIKE ? OR a.seller_name LIKE ?`
  51. pars = append(pars, kw, kw)
  52. }
  53. if req.SellGroupId > 0 {
  54. cond += ` AND a.seller_group_id = ?`
  55. pars = append(pars, req.SellGroupId)
  56. }
  57. // 套餐筛选
  58. if req.ServiceType != 0 {
  59. registerIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
  60. if e != nil {
  61. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  62. return
  63. }
  64. if len(registerIds) > 0 {
  65. cond += ` AND b.contract_register_id IN ?`
  66. pars = append(pars, registerIds)
  67. } else {
  68. cond += ` AND 1 = 2`
  69. }
  70. }
  71. // 开票到款日期
  72. if req.TimeType > 0 && req.StartDate != "" && req.EndDate != "" {
  73. st := fmt.Sprint(req.StartDate, " 00:00:00")
  74. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  75. cond += ` AND a.invoice_type = ? AND (a.invoice_time BETWEEN ? AND ?)`
  76. pars = append(pars, req.TimeType, st, ed)
  77. }
  78. // 已开票
  79. if req.HasInvoice == 1 && req.HasPayment == 0 {
  80. cond += ` AND a.invoice_type = 1`
  81. }
  82. // 已到款
  83. if req.HasInvoice == 0 && req.HasPayment == 1 {
  84. cond += ` AND a.invoice_type = 2`
  85. }
  86. page := new(base.Page)
  87. page.SetPageSize(req.PageSize)
  88. page.SetCurrent(req.Current)
  89. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  90. page.AddOrderItem(base.OrderItem{Column: "b.contract_register_id", Asc: true})
  91. if req.IsExport == 1 {
  92. page.SetPageSize(10000)
  93. page.SetCurrent(1)
  94. }
  95. total, list, e := fms.GetInvoicePaymentCensusPageList(page, cond, pars)
  96. if e != nil {
  97. resp.FailMsg("获取失败", "获取商品到款统计列表失败, Err: "+e.Error(), c)
  98. return
  99. }
  100. registerIds := make([]int, 0)
  101. for i := range list {
  102. registerIds = append(registerIds, list[i].ContractRegisterId)
  103. }
  104. results := new(fms.InvoicePaymentCensusResp)
  105. if len(registerIds) > 0 {
  106. // 获取开票到款列表
  107. ivCond := `contract_register_id IN ?`
  108. ivPars := make([]interface{}, 0)
  109. ivPars = append(ivPars, registerIds)
  110. iv := new(fms.ContractInvoice)
  111. invoiceList, e := iv.List(ivCond, ivPars, "")
  112. if e != nil {
  113. resp.FailMsg("获取失败", "获取开票到款列表失败, Err: "+e.Error(), c)
  114. return
  115. }
  116. // 取出开票、到款
  117. invoiceMap := make(map[int][]*fms.ContractInvoice, 0)
  118. paymentMap := make(map[int][]*fms.ContractInvoice, 0)
  119. paymentIds := make([]int, 0)
  120. for i := range invoiceList {
  121. if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
  122. invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoice, 0)
  123. }
  124. if paymentMap[invoiceList[i].ContractRegisterId] == nil {
  125. paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoice, 0)
  126. }
  127. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  128. invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  129. }
  130. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  131. paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  132. paymentIds = append(paymentIds, invoiceList[i].ContractInvoiceId)
  133. }
  134. }
  135. // 合同套餐
  136. contractServiceCond := `contract_register_id IN ?`
  137. contractServicePars := make([]interface{}, 0)
  138. contractServicePars = append(contractServicePars, registerIds)
  139. contractServiceOB := new(fms.ContractService)
  140. contractServiceList, e := contractServiceOB.List(contractServiceCond, contractServicePars)
  141. if e != nil {
  142. resp.FailMsg("获取失败", "获取合同套餐列表失败, Err:"+e.Error(), c)
  143. return
  144. }
  145. contractServiceMap := make(map[int][]*fms.ContractService, 0)
  146. servicesNameMap := make(map[int][]string, 0)
  147. for i := range contractServiceList {
  148. if contractServiceMap[contractServiceList[i].ContractRegisterId] == nil {
  149. contractServiceMap[contractServiceList[i].ContractRegisterId] = make([]*fms.ContractService, 0)
  150. }
  151. contractServiceMap[contractServiceList[i].ContractRegisterId] = append(contractServiceMap[contractServiceList[i].ContractRegisterId], contractServiceList[i])
  152. servicesNameMap[contractServiceList[i].ContractRegisterId] = append(servicesNameMap[contractServiceList[i].ContractRegisterId], contractServiceList[i].Title)
  153. }
  154. // 到款套餐分配
  155. serviceAmountMap := make(map[int][]*fms.ContractPaymentServiceAmount, 0)
  156. if len(paymentIds) > 0 {
  157. serviceAmountCond := `contract_payment_id IN ?`
  158. serviceAmountPars := make([]interface{}, 0)
  159. serviceAmountPars = append(serviceAmountPars, paymentIds)
  160. serviceAmountOB := new(fms.ContractPaymentServiceAmount)
  161. serviceAmountList, e := serviceAmountOB.List(serviceAmountCond, serviceAmountPars)
  162. if e != nil {
  163. resp.FailMsg("获取失败", "获取到款套餐分配列表失败, Err:"+e.Error(), c)
  164. return
  165. }
  166. for i := range serviceAmountList {
  167. if serviceAmountMap[serviceAmountList[i].ContractRegisterId] == nil {
  168. serviceAmountMap[serviceAmountList[i].ContractRegisterId] = make([]*fms.ContractPaymentServiceAmount, 0)
  169. }
  170. serviceAmountMap[serviceAmountList[i].ContractRegisterId] = append(serviceAmountMap[serviceAmountList[i].ContractRegisterId], serviceAmountList[i])
  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. amountTotalCond := `contract_register_id IN ?`
  191. amountTotalPars := make([]interface{}, 0)
  192. amountTotalPars = append(amountTotalPars, registerIds)
  193. amountTotalList, e := fms.GetContractInvoiceAmountTotal(amountTotalCond, amountTotalPars)
  194. if e != nil {
  195. resp.FailMsg("获取失败", "获取开票到款金额合计失败, Err:"+e.Error(), c)
  196. return
  197. }
  198. amountTotalMap := make(map[int]float64)
  199. for i := range amountTotalList {
  200. amountTotalMap[amountTotalList[i].InvoiceType] = amountTotalList[i].TotalAmount
  201. }
  202. // 分币种金额统计
  203. currencyOB := new(fms.CurrencyUnit)
  204. currencyCond := `enable = 1`
  205. currencyPars := make([]interface{}, 0)
  206. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  207. if e != nil {
  208. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  209. return
  210. }
  211. unitMap := make(map[string]string)
  212. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  213. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  214. for i := range currencyList {
  215. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  216. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  217. Name: currencyList[i].Name,
  218. UnitName: currencyList[i].UnitName,
  219. Code: currencyList[i].Code,
  220. FlagImg: currencyList[i].FlagImg,
  221. })
  222. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  223. Name: currencyList[i].Name,
  224. UnitName: currencyList[i].UnitName,
  225. Code: currencyList[i].Code,
  226. FlagImg: currencyList[i].FlagImg,
  227. })
  228. }
  229. sumList, e := fms.GetInvoiceListCurrencySum(amountTotalCond, amountTotalPars, "currency_unit, invoice_type")
  230. if e != nil {
  231. resp.FailMsg("获取失败", "获取商品到款统计货币合计金额失败, Err: "+e.Error(), c)
  232. return
  233. }
  234. invoiceSumMap := make(map[string]float64)
  235. paymentSumMap := make(map[string]float64)
  236. for i := range sumList {
  237. if sumList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  238. invoiceSumMap[sumList[i].CurrencyUnit] = sumList[i].OriginAmountTotal
  239. continue
  240. }
  241. if sumList[i].InvoiceType == fms.ContractInvoiceTypePay {
  242. paymentSumMap[sumList[i].CurrencyUnit] = sumList[i].OriginAmountTotal
  243. }
  244. }
  245. for i := range invoiceCurrencyTotals {
  246. invoiceCurrencyTotals[i].Amount = invoiceSumMap[invoiceCurrencyTotals[i].Code]
  247. }
  248. for i := range paymentCurrencyTotals {
  249. paymentCurrencyTotals[i].Amount = paymentSumMap[paymentCurrencyTotals[i].Code]
  250. }
  251. results.DataList = respList
  252. results.InvoiceTotal = amountTotalMap[fms.ContractInvoiceTypeMake]
  253. results.PaymentTotal = amountTotalMap[fms.ContractInvoiceTypePay]
  254. results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  255. results.PaymentCurrencyTotal = paymentCurrencyTotals
  256. }
  257. // 是否导出
  258. if req.IsExport == 1 {
  259. ExportInvoicePaymentCensusList(c, results)
  260. return
  261. }
  262. page.SetTotal(total)
  263. baseData := new(base.BaseData)
  264. baseData.SetPage(page)
  265. baseData.SetList(results)
  266. resp.OkData("获取成功", baseData, c)
  267. }
  268. // ExportInvoicePaymentCensusList 导出商品到款统计列表
  269. func ExportInvoicePaymentCensusList(c *gin.Context, results *fms.InvoicePaymentCensusResp) {
  270. list := results.DataList
  271. if len(list) == 0 {
  272. resp.Fail("列表数据为空", c)
  273. return
  274. }
  275. // 生成Excel文件
  276. xlsxFile := xlsx.NewFile()
  277. style := xlsx.NewStyle()
  278. alignment := xlsx.Alignment{
  279. Horizontal: "center",
  280. Vertical: "center",
  281. WrapText: true,
  282. }
  283. style.Alignment = alignment
  284. style.ApplyAlignment = true
  285. sheet, err := xlsxFile.AddSheet("商品到款统计")
  286. if err != nil {
  287. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  288. return
  289. }
  290. _ = sheet.SetColWidth(1, 1, 30)
  291. _ = sheet.SetColWidth(3, 3, 30)
  292. // 前三行-开票金额合计
  293. rowA := sheet.AddRow()
  294. cellAA := rowA.AddCell()
  295. cellAA.SetString(fmt.Sprintf("已开票合计金额(换算后):%.2f(元)", results.InvoiceTotal))
  296. rowBData := "已开票金额:"
  297. for _, v := range results.InvoiceCurrencyTotal {
  298. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  299. }
  300. rowB := sheet.AddRow()
  301. rowB.AddCell().SetString(rowBData)
  302. sheet.AddRow()
  303. // 四至六-到款金额合计
  304. rowD := sheet.AddRow()
  305. cellDA := rowD.AddCell()
  306. cellDA.SetString(fmt.Sprintf("已到款合计金额(换算后):%.2f(元)", results.PaymentTotal))
  307. rowEData := "已到款金额:"
  308. for _, v := range results.PaymentCurrencyTotal {
  309. rowEData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  310. }
  311. rowE := sheet.AddRow()
  312. rowE.AddCell().SetString(rowEData)
  313. sheet.AddRow()
  314. // 表头, 套餐动态获取
  315. rowTitle := []string{"序号", "客户名称", "是否新客户", "合同有效期", "开票日", "开票金额", "到款日", "到款金额", "付款方式", "销售",
  316. "组别"}
  317. serviceTempCond := ``
  318. serviceTempPars := make([]interface{}, 0)
  319. serviceTempOB := new(fms.ContractServiceTemplate)
  320. serviceTempList, e := serviceTempOB.List(serviceTempCond, serviceTempPars)
  321. if e != nil {
  322. resp.FailData("获取套餐模板列表失败", "Err:"+e.Error(), c)
  323. return
  324. }
  325. for i := range serviceTempList {
  326. rowTitle = append(rowTitle, serviceTempList[i].Title)
  327. }
  328. titleRow := sheet.AddRow()
  329. for i := range rowTitle {
  330. v := titleRow.AddCell()
  331. v.SetString(rowTitle[i])
  332. v.SetStyle(style)
  333. }
  334. newCompanyMap := map[int]string{0: "否", 1: "是"}
  335. for k, v := range list {
  336. dataRow := sheet.AddRow()
  337. // 前四个单元格根据每行开票到款条数向下合并
  338. l := len(v.InvoicePaymentList)
  339. mergeRowNum := l - 1
  340. // 序号
  341. sortNum := k + 1
  342. colA := dataRow.AddCell()
  343. colA.VMerge = mergeRowNum
  344. colA.SetString(fmt.Sprint(sortNum))
  345. // 客户名称
  346. colB := dataRow.AddCell()
  347. colB.VMerge = mergeRowNum
  348. colB.SetString(v.CompanyName)
  349. // 是否新客户
  350. colC := dataRow.AddCell()
  351. colC.VMerge = mergeRowNum
  352. colC.SetString(newCompanyMap[v.NewCompany])
  353. // 合同有效期
  354. colD := dataRow.AddCell()
  355. colD.VMerge = mergeRowNum
  356. colD.SetString(fmt.Sprint(v.StartDate, "至", v.EndDate))
  357. // 开票到款信息
  358. for k2, v2 := range v.InvoicePaymentList {
  359. rowData := []string{
  360. v2.InvoiceDate, // 开票日
  361. fmt.Sprint(v2.InvoiceAmount), // 开票金额
  362. v2.PaymentDate, // 到款日
  363. fmt.Sprint(v2.PaymentAmount), // 到款金额
  364. fms.ContractPaymentPayTypeNameMap[v2.PayType], // 付款方式
  365. v2.SellerName, // 销售
  366. v2.SellerGroupName, // 组别
  367. }
  368. // 套餐金额信息
  369. for i := range serviceTempList {
  370. sa := ""
  371. for s2 := range v2.ServiceAmountList {
  372. if v2.ServiceAmountList[s2].ServiceTemplateId == serviceTempList[i].ServiceTemplateId {
  373. sa = fmt.Sprint(v2.ServiceAmountList[s2].Amount)
  374. break
  375. }
  376. }
  377. rowData = append(rowData, sa)
  378. }
  379. // 首行开票到款
  380. if k2 == 0 {
  381. for i := range rowData {
  382. dataRow.AddCell().SetString(rowData[i])
  383. }
  384. continue
  385. }
  386. // 其他行开票到款, 加四列空的单元格用于合并
  387. dataRowExtra := sheet.AddRow()
  388. for i := 0; i < 4; i++ {
  389. dataRowExtra.AddCell()
  390. }
  391. for i := range rowData {
  392. dataRowExtra.AddCell().SetString(rowData[i])
  393. }
  394. }
  395. }
  396. // 输出文件
  397. var buffer bytes.Buffer
  398. _ = xlsxFile.Write(&buffer)
  399. content := bytes.NewReader(buffer.Bytes())
  400. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  401. fileName := "商品到款统计_" + randStr + ".xlsx"
  402. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  403. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  404. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  405. }