invoice_payment.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. "time"
  18. )
  19. // InvoicePaymentController 商品到款统计
  20. type InvoicePaymentController struct{}
  21. // List
  22. // @Title 商品到款统计列表
  23. // @Description 商品到款统计列表
  24. // @Param Keyword query string false "关键词"
  25. // @Param SellGroupId query int false "销售组别ID"
  26. // @Param ServiceType query int false "套餐类型"
  27. // @Param StartDate query string false "合同开始日期"
  28. // @Param EndDate query string false "合同结束日期"
  29. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  30. // @Param HasInvoice query int false "是否已开票: 0-否; 1-是"
  31. // @Param HasPayment query int false "是否已到款: 0-否; 1-是"
  32. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  33. // @Success 200 {object} fms.ContractRegisterItem
  34. // @router /census/invoice_payment/list [get]
  35. func (ct *InvoicePaymentController) List(c *gin.Context) {
  36. var req fms.InvoicePaymentCensusListReq
  37. if e := c.BindQuery(&req); e != nil {
  38. err, ok := e.(validator.ValidationErrors)
  39. if !ok {
  40. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  41. return
  42. }
  43. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  44. return
  45. }
  46. cond := `1 = 1`
  47. pars := make([]interface{}, 0)
  48. // 合同编号/客户姓名/销售
  49. if req.Keyword != "" {
  50. kw := "%" + req.Keyword + "%"
  51. cond += ` AND b.company_name LIKE ? OR a.seller_name LIKE ?`
  52. pars = append(pars, kw, kw)
  53. }
  54. if req.SellGroupId > 0 {
  55. cond += ` AND a.seller_group_id = ?`
  56. pars = append(pars, req.SellGroupId)
  57. }
  58. // 套餐筛选
  59. if req.ServiceType != 0 {
  60. registerIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
  61. if e != nil {
  62. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  63. return
  64. }
  65. if len(registerIds) > 0 {
  66. cond += ` AND b.contract_register_id IN ?`
  67. pars = append(pars, registerIds)
  68. } else {
  69. cond += ` AND 1 = 2`
  70. }
  71. }
  72. // 开票到款日期
  73. if req.TimeType > 0 && req.StartDate != "" && req.EndDate != "" {
  74. st := fmt.Sprint(req.StartDate, " 00:00:00")
  75. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  76. cond += ` AND a.invoice_type = ? AND (a.invoice_time BETWEEN ? AND ?)`
  77. pars = append(pars, req.TimeType, st, ed)
  78. }
  79. // 已开票
  80. if req.HasInvoice == 1 && req.HasPayment == 0 {
  81. cond += ` AND a.invoice_type = 1`
  82. }
  83. // 已到款
  84. if req.HasInvoice == 0 && req.HasPayment == 1 {
  85. cond += ` AND a.invoice_type = 2`
  86. }
  87. page := new(base.Page)
  88. page.SetPageSize(req.PageSize)
  89. page.SetCurrent(req.Current)
  90. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  91. page.AddOrderItem(base.OrderItem{Column: "b.contract_register_id", Asc: true})
  92. if req.IsExport == 1 {
  93. page.SetPageSize(10000)
  94. page.SetCurrent(1)
  95. }
  96. total, list, e := fms.GetInvoicePaymentCensusPageList(page, cond, pars)
  97. if e != nil {
  98. resp.FailMsg("获取失败", "获取商品到款统计列表失败, Err: "+e.Error(), c)
  99. return
  100. }
  101. registerIds := make([]int, 0)
  102. for i := range list {
  103. registerIds = append(registerIds, list[i].ContractRegisterId)
  104. }
  105. results := new(fms.InvoicePaymentCensusResp)
  106. if len(registerIds) > 0 {
  107. // 获取开票到款列表
  108. ivCond := `contract_register_id IN ?`
  109. ivPars := make([]interface{}, 0)
  110. ivPars = append(ivPars, registerIds)
  111. iv := new(fms.ContractInvoice)
  112. invoiceList, e := iv.List(ivCond, ivPars, "")
  113. if e != nil {
  114. resp.FailMsg("获取失败", "获取开票到款列表失败, Err: "+e.Error(), c)
  115. return
  116. }
  117. // 取出开票、到款
  118. invoiceMap := make(map[int][]*fms.ContractInvoice, 0)
  119. paymentMap := make(map[int][]*fms.ContractInvoice, 0)
  120. paymentIds := make([]int, 0)
  121. for i := range invoiceList {
  122. if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
  123. invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoice, 0)
  124. }
  125. if paymentMap[invoiceList[i].ContractRegisterId] == nil {
  126. paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoice, 0)
  127. }
  128. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  129. invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  130. }
  131. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  132. paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  133. paymentIds = append(paymentIds, invoiceList[i].ContractInvoiceId)
  134. }
  135. }
  136. // 合同套餐
  137. contractServiceCond := `contract_register_id IN ?`
  138. contractServicePars := make([]interface{}, 0)
  139. contractServicePars = append(contractServicePars, registerIds)
  140. contractServiceOB := new(fms.ContractService)
  141. contractServiceList, e := contractServiceOB.List(contractServiceCond, contractServicePars)
  142. if e != nil {
  143. resp.FailMsg("获取失败", "获取合同套餐列表失败, Err:"+e.Error(), c)
  144. return
  145. }
  146. contractServiceMap := make(map[int][]*fms.ContractService, 0)
  147. servicesNameMap := make(map[int][]string, 0)
  148. for i := range contractServiceList {
  149. if contractServiceMap[contractServiceList[i].ContractRegisterId] == nil {
  150. contractServiceMap[contractServiceList[i].ContractRegisterId] = make([]*fms.ContractService, 0)
  151. }
  152. contractServiceMap[contractServiceList[i].ContractRegisterId] = append(contractServiceMap[contractServiceList[i].ContractRegisterId], contractServiceList[i])
  153. servicesNameMap[contractServiceList[i].ContractRegisterId] = append(servicesNameMap[contractServiceList[i].ContractRegisterId], contractServiceList[i].Title)
  154. }
  155. // 到款套餐分配
  156. serviceAmountMap := make(map[int][]*fms.ContractPaymentServiceAmount, 0)
  157. if len(paymentIds) > 0 {
  158. serviceAmountCond := `contract_payment_id IN ?`
  159. serviceAmountPars := make([]interface{}, 0)
  160. serviceAmountPars = append(serviceAmountPars, paymentIds)
  161. serviceAmountOB := new(fms.ContractPaymentServiceAmount)
  162. serviceAmountList, e := serviceAmountOB.List(serviceAmountCond, serviceAmountPars)
  163. if e != nil {
  164. resp.FailMsg("获取失败", "获取到款套餐分配列表失败, Err:"+e.Error(), c)
  165. return
  166. }
  167. for i := range serviceAmountList {
  168. if serviceAmountMap[serviceAmountList[i].ContractRegisterId] == nil {
  169. serviceAmountMap[serviceAmountList[i].ContractRegisterId] = make([]*fms.ContractPaymentServiceAmount, 0)
  170. }
  171. serviceAmountMap[serviceAmountList[i].ContractRegisterId] = append(serviceAmountMap[serviceAmountList[i].ContractRegisterId], serviceAmountList[i])
  172. }
  173. }
  174. // 整合响应数据
  175. respList := make([]*fms.InvoicePaymentCensusItem, 0)
  176. for i := range list {
  177. v := new(fms.InvoicePaymentCensusItem)
  178. v.ContractRegisterId = list[i].ContractRegisterId
  179. v.CompanyName = list[i].CompanyName
  180. v.NewCompany = list[i].NewCompany
  181. v.StartDate = list[i].StartDate.Format(utils.FormatDate)
  182. v.EndDate = list[i].EndDate.Format(utils.FormatDate)
  183. svList := servicesNameMap[list[i].ContractRegisterId]
  184. v.ServicesName = strings.Join(svList, ",")
  185. // 格式化(合并)开票到款数据
  186. v.InvoicePaymentList = fmsService.MergeInvoiceList2InvoicePaymentCensusInfo(invoiceMap[list[i].ContractRegisterId], paymentMap[list[i].ContractRegisterId],
  187. contractServiceMap[list[i].ContractRegisterId], serviceAmountMap[list[i].ContractRegisterId])
  188. respList = append(respList, v)
  189. }
  190. // 开票到款金额合计(换算后)
  191. amountTotalCond := `contract_register_id IN ?`
  192. amountTotalPars := make([]interface{}, 0)
  193. amountTotalPars = append(amountTotalPars, registerIds)
  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. currencyOB := new(fms.CurrencyUnit)
  207. currencyCond := `enable = 1`
  208. currencyPars := make([]interface{}, 0)
  209. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  210. if e != nil {
  211. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  212. return
  213. }
  214. unitMap := make(map[string]string)
  215. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  216. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  217. for i := range currencyList {
  218. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  219. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  220. Name: currencyList[i].Name,
  221. UnitName: currencyList[i].UnitName,
  222. Code: currencyList[i].Code,
  223. FlagImg: currencyList[i].FlagImg,
  224. })
  225. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  226. Name: currencyList[i].Name,
  227. UnitName: currencyList[i].UnitName,
  228. Code: currencyList[i].Code,
  229. FlagImg: currencyList[i].FlagImg,
  230. })
  231. }
  232. sumList, e := fms.GetInvoiceListCurrencySum(amountTotalCond, amountTotalPars, "currency_unit, invoice_type")
  233. if e != nil {
  234. resp.FailMsg("获取失败", "获取商品到款统计货币合计金额失败, Err: "+e.Error(), c)
  235. return
  236. }
  237. invoiceSumMap := make(map[string]float64)
  238. paymentSumMap := make(map[string]float64)
  239. for i := range sumList {
  240. if sumList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  241. invoiceSumMap[sumList[i].CurrencyUnit] = sumList[i].OriginAmountTotal
  242. continue
  243. }
  244. if sumList[i].InvoiceType == fms.ContractInvoiceTypePay {
  245. paymentSumMap[sumList[i].CurrencyUnit] = sumList[i].OriginAmountTotal
  246. }
  247. }
  248. for i := range invoiceCurrencyTotals {
  249. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
  250. invoiceCurrencyTotals[i].Amount = a
  251. }
  252. for i := range paymentCurrencyTotals {
  253. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  254. paymentCurrencyTotals[i].Amount = a
  255. }
  256. results.DataList = respList
  257. results.InvoiceTotal = invoiceTotal
  258. results.PaymentTotal = paymentTotal
  259. results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  260. results.PaymentCurrencyTotal = paymentCurrencyTotals
  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. for i := range serviceTempList {
  331. rowTitle = append(rowTitle, serviceTempList[i].Title)
  332. }
  333. titleRow := sheet.AddRow()
  334. for i := range rowTitle {
  335. v := titleRow.AddCell()
  336. v.SetString(rowTitle[i])
  337. v.SetStyle(style)
  338. }
  339. newCompanyMap := map[int]string{0: "否", 1: "是"}
  340. for k, v := range list {
  341. dataRow := sheet.AddRow()
  342. // 前四个单元格根据每行开票到款条数向下合并
  343. l := len(v.InvoicePaymentList)
  344. mergeRowNum := l - 1
  345. // 序号
  346. sortNum := k + 1
  347. colA := dataRow.AddCell()
  348. colA.VMerge = mergeRowNum
  349. colA.SetString(fmt.Sprint(sortNum))
  350. // 客户名称
  351. colB := dataRow.AddCell()
  352. colB.VMerge = mergeRowNum
  353. colB.SetString(v.CompanyName)
  354. // 是否新客户
  355. colC := dataRow.AddCell()
  356. colC.VMerge = mergeRowNum
  357. colC.SetString(newCompanyMap[v.NewCompany])
  358. // 合同有效期
  359. colD := dataRow.AddCell()
  360. colD.VMerge = mergeRowNum
  361. colD.SetString(fmt.Sprint(v.StartDate, "至", v.EndDate))
  362. // 开票到款信息
  363. for k2, v2 := range v.InvoicePaymentList {
  364. rowData := []string{
  365. v2.InvoiceDate, // 开票日
  366. fmt.Sprint(v2.InvoiceAmount), // 开票金额
  367. v2.PaymentDate, // 到款日
  368. fmt.Sprint(v2.PaymentAmount), // 到款金额
  369. fms.ContractPaymentPayTypeNameMap[v2.PayType], // 付款方式
  370. v2.SellerName, // 销售
  371. v2.SellerGroupName, // 组别
  372. }
  373. // 套餐金额信息
  374. for i := range serviceTempList {
  375. sa := ""
  376. for s2 := range v2.ServiceAmountList {
  377. if v2.ServiceAmountList[s2].ServiceTemplateId == serviceTempList[i].ServiceTemplateId {
  378. sa = fmt.Sprint(v2.ServiceAmountList[s2].Amount)
  379. break
  380. }
  381. }
  382. rowData = append(rowData, sa)
  383. }
  384. // 首行开票到款
  385. if k2 == 0 {
  386. for i := range rowData {
  387. dataRow.AddCell().SetString(rowData[i])
  388. }
  389. continue
  390. }
  391. // 其他行开票到款, 加四列空的单元格用于合并
  392. dataRowExtra := sheet.AddRow()
  393. for i := 0; i < 4; i++ {
  394. dataRowExtra.AddCell()
  395. }
  396. for i := range rowData {
  397. dataRowExtra.AddCell().SetString(rowData[i])
  398. }
  399. }
  400. }
  401. // 输出文件
  402. var buffer bytes.Buffer
  403. _ = xlsxFile.Write(&buffer)
  404. content := bytes.NewReader(buffer.Bytes())
  405. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  406. fileName := "商品到款统计_" + randStr + ".xlsx"
  407. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  408. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  409. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  410. }