invoice_payment.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. list, allRegisterIds, e := fms.GetInvoicePaymentCensusPageList(page, cond, pars)
  97. if e != nil {
  98. resp.FailMsg("获取失败", "获取商品到款统计列表失败, Err: "+e.Error(), c)
  99. return
  100. }
  101. total := int64(len(allRegisterIds))
  102. registerIds := make([]int, 0)
  103. for i := range list {
  104. registerIds = append(registerIds, list[i].ContractRegisterId)
  105. }
  106. results := new(fms.InvoicePaymentCensusResp)
  107. if len(registerIds) > 0 {
  108. // 获取开票到款列表
  109. ivCond := `contract_register_id IN ?`
  110. ivPars := make([]interface{}, 0)
  111. ivPars = append(ivPars, registerIds)
  112. iv := new(fms.ContractInvoice)
  113. invoiceList, e := iv.List(ivCond, ivPars, "")
  114. if e != nil {
  115. resp.FailMsg("获取失败", "获取开票到款列表失败, Err: "+e.Error(), c)
  116. return
  117. }
  118. // 取出开票、到款
  119. invoiceMap := make(map[int][]*fms.ContractInvoice, 0)
  120. paymentMap := make(map[int][]*fms.ContractInvoice, 0)
  121. paymentIds := make([]int, 0)
  122. for i := range invoiceList {
  123. if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
  124. invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoice, 0)
  125. }
  126. if paymentMap[invoiceList[i].ContractRegisterId] == nil {
  127. paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoice, 0)
  128. }
  129. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  130. invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  131. }
  132. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  133. paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  134. paymentIds = append(paymentIds, invoiceList[i].ContractInvoiceId)
  135. }
  136. }
  137. // 合同套餐
  138. contractServiceCond := `contract_register_id IN ?`
  139. contractServicePars := make([]interface{}, 0)
  140. contractServicePars = append(contractServicePars, registerIds)
  141. contractServiceOB := new(fms.ContractService)
  142. contractServiceList, e := contractServiceOB.List(contractServiceCond, contractServicePars)
  143. if e != nil {
  144. resp.FailMsg("获取失败", "获取合同套餐列表失败, Err:"+e.Error(), c)
  145. return
  146. }
  147. contractServiceMap := make(map[int][]*fms.ContractService, 0)
  148. servicesNameMap := make(map[int][]string, 0)
  149. for i := range contractServiceList {
  150. if contractServiceMap[contractServiceList[i].ContractRegisterId] == nil {
  151. contractServiceMap[contractServiceList[i].ContractRegisterId] = make([]*fms.ContractService, 0)
  152. }
  153. contractServiceMap[contractServiceList[i].ContractRegisterId] = append(contractServiceMap[contractServiceList[i].ContractRegisterId], contractServiceList[i])
  154. servicesNameMap[contractServiceList[i].ContractRegisterId] = append(servicesNameMap[contractServiceList[i].ContractRegisterId], contractServiceList[i].Title)
  155. }
  156. // 到款套餐分配
  157. serviceAmountMap := make(map[int][]*fms.ContractPaymentServiceAmount, 0)
  158. if len(paymentIds) > 0 {
  159. serviceAmountCond := `contract_payment_id IN ?`
  160. serviceAmountPars := make([]interface{}, 0)
  161. serviceAmountPars = append(serviceAmountPars, paymentIds)
  162. serviceAmountOB := new(fms.ContractPaymentServiceAmount)
  163. serviceAmountList, e := serviceAmountOB.List(serviceAmountCond, serviceAmountPars)
  164. if e != nil {
  165. resp.FailMsg("获取失败", "获取到款套餐分配列表失败, Err:"+e.Error(), c)
  166. return
  167. }
  168. for i := range serviceAmountList {
  169. if serviceAmountMap[serviceAmountList[i].ContractRegisterId] == nil {
  170. serviceAmountMap[serviceAmountList[i].ContractRegisterId] = make([]*fms.ContractPaymentServiceAmount, 0)
  171. }
  172. serviceAmountMap[serviceAmountList[i].ContractRegisterId] = append(serviceAmountMap[serviceAmountList[i].ContractRegisterId], serviceAmountList[i])
  173. }
  174. }
  175. // 整合响应数据
  176. respList := make([]*fms.InvoicePaymentCensusItem, 0)
  177. for i := range list {
  178. v := new(fms.InvoicePaymentCensusItem)
  179. v.ContractRegisterId = list[i].ContractRegisterId
  180. v.CompanyName = list[i].CompanyName
  181. v.NewCompany = list[i].NewCompany
  182. v.StartDate = list[i].StartDate.Format(utils.FormatDate)
  183. v.EndDate = list[i].EndDate.Format(utils.FormatDate)
  184. svList := servicesNameMap[list[i].ContractRegisterId]
  185. v.ServicesName = strings.Join(svList, ",")
  186. // 格式化(合并)开票到款数据
  187. v.InvoicePaymentList = fmsService.MergeInvoiceList2InvoicePaymentCensusInfo(invoiceMap[list[i].ContractRegisterId], paymentMap[list[i].ContractRegisterId],
  188. contractServiceMap[list[i].ContractRegisterId], serviceAmountMap[list[i].ContractRegisterId])
  189. respList = append(respList, v)
  190. }
  191. // 开票到款金额合计(换算后)
  192. amountTotalCond := `contract_register_id IN ?`
  193. amountTotalPars := make([]interface{}, 0)
  194. amountTotalPars = append(amountTotalPars, allRegisterIds)
  195. amountTotalList, e := fms.GetContractInvoiceAmountTotal(cond, pars)
  196. if e != nil {
  197. resp.FailMsg("获取失败", "获取开票到款金额合计失败, Err:"+e.Error(), c)
  198. return
  199. }
  200. amountTotalMap := make(map[int]float64)
  201. for i := range amountTotalList {
  202. amountTotalMap[amountTotalList[i].InvoiceType] = amountTotalList[i].TotalAmount
  203. }
  204. invoiceTotal, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amountTotalMap[fms.ContractInvoiceTypeMake]), 64)
  205. paymentTotal, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amountTotalMap[fms.ContractInvoiceTypePay]), 64)
  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. results.DataList = respList
  258. results.InvoiceTotal = invoiceTotal
  259. results.PaymentTotal = paymentTotal
  260. results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  261. results.PaymentCurrencyTotal = paymentCurrencyTotals
  262. }
  263. // 是否导出
  264. if req.IsExport == 1 {
  265. ExportInvoicePaymentCensusList(c, results)
  266. return
  267. }
  268. page.SetTotal(total)
  269. baseData := new(base.BaseData)
  270. baseData.SetPage(page)
  271. baseData.SetList(results)
  272. resp.OkData("获取成功", baseData, c)
  273. }
  274. // ExportInvoicePaymentCensusList 导出商品到款统计列表
  275. func ExportInvoicePaymentCensusList(c *gin.Context, results *fms.InvoicePaymentCensusResp) {
  276. list := results.DataList
  277. if len(list) == 0 {
  278. resp.Fail("列表数据为空", c)
  279. return
  280. }
  281. // 生成Excel文件
  282. xlsxFile := xlsx.NewFile()
  283. style := xlsx.NewStyle()
  284. alignment := xlsx.Alignment{
  285. Horizontal: "center",
  286. Vertical: "center",
  287. WrapText: true,
  288. }
  289. style.Alignment = alignment
  290. style.ApplyAlignment = true
  291. sheet, err := xlsxFile.AddSheet("商品到款统计")
  292. if err != nil {
  293. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  294. return
  295. }
  296. _ = sheet.SetColWidth(1, 1, 30)
  297. _ = sheet.SetColWidth(3, 3, 30)
  298. // 前三行-开票金额合计
  299. rowA := sheet.AddRow()
  300. cellAA := rowA.AddCell()
  301. cellAA.SetString(fmt.Sprintf("已开票合计金额(换算后):%.2f(元)", results.InvoiceTotal))
  302. rowBData := "已开票金额:"
  303. for _, v := range results.InvoiceCurrencyTotal {
  304. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  305. }
  306. rowB := sheet.AddRow()
  307. rowB.AddCell().SetString(rowBData)
  308. sheet.AddRow()
  309. // 四至六-到款金额合计
  310. rowD := sheet.AddRow()
  311. cellDA := rowD.AddCell()
  312. cellDA.SetString(fmt.Sprintf("已到款合计金额(换算后):%.2f(元)", results.PaymentTotal))
  313. rowEData := "已到款金额:"
  314. for _, v := range results.PaymentCurrencyTotal {
  315. rowEData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  316. }
  317. rowE := sheet.AddRow()
  318. rowE.AddCell().SetString(rowEData)
  319. sheet.AddRow()
  320. // 表头, 套餐动态获取
  321. rowTitle := []string{"序号", "客户名称", "是否新客户", "合同有效期", "开票日", "开票金额", "到款日", "到款金额", "付款方式", "销售",
  322. "组别"}
  323. serviceTempCond := ``
  324. serviceTempPars := make([]interface{}, 0)
  325. serviceTempOB := new(fms.ContractServiceTemplate)
  326. serviceTempList, e := serviceTempOB.List(serviceTempCond, serviceTempPars)
  327. if e != nil {
  328. resp.FailData("获取套餐模板列表失败", "Err:"+e.Error(), c)
  329. return
  330. }
  331. for i := range serviceTempList {
  332. rowTitle = append(rowTitle, serviceTempList[i].Title)
  333. }
  334. titleRow := sheet.AddRow()
  335. for i := range rowTitle {
  336. v := titleRow.AddCell()
  337. v.SetString(rowTitle[i])
  338. v.SetStyle(style)
  339. }
  340. newCompanyMap := map[int]string{0: "否", 1: "是"}
  341. for k, v := range list {
  342. dataRow := sheet.AddRow()
  343. // 前四个单元格根据每行开票到款条数向下合并
  344. l := len(v.InvoicePaymentList)
  345. mergeRowNum := l - 1
  346. // 序号
  347. sortNum := k + 1
  348. colA := dataRow.AddCell()
  349. colA.VMerge = mergeRowNum
  350. colA.SetString(fmt.Sprint(sortNum))
  351. // 客户名称
  352. colB := dataRow.AddCell()
  353. colB.VMerge = mergeRowNum
  354. colB.SetString(v.CompanyName)
  355. // 是否新客户
  356. colC := dataRow.AddCell()
  357. colC.VMerge = mergeRowNum
  358. colC.SetString(newCompanyMap[v.NewCompany])
  359. // 合同有效期
  360. colD := dataRow.AddCell()
  361. colD.VMerge = mergeRowNum
  362. colD.SetString(fmt.Sprint(v.StartDate, "至", v.EndDate))
  363. // 开票到款信息
  364. for k2, v2 := range v.InvoicePaymentList {
  365. rowData := []string{
  366. v2.InvoiceDate, // 开票日
  367. fmt.Sprint(v2.InvoiceAmount), // 开票金额
  368. v2.PaymentDate, // 到款日
  369. fmt.Sprint(v2.PaymentAmount), // 到款金额
  370. fms.ContractPaymentPayTypeNameMap[v2.PayType], // 付款方式
  371. v2.SellerName, // 销售
  372. v2.SellerGroupName, // 组别
  373. }
  374. // 套餐金额信息
  375. for i := range serviceTempList {
  376. sa := ""
  377. for s2 := range v2.ServiceAmountList {
  378. if v2.ServiceAmountList[s2].ServiceTemplateId == serviceTempList[i].ServiceTemplateId {
  379. sa = fmt.Sprint(v2.ServiceAmountList[s2].Amount)
  380. break
  381. }
  382. }
  383. rowData = append(rowData, sa)
  384. }
  385. // 首行开票到款
  386. if k2 == 0 {
  387. for i := range rowData {
  388. dataRow.AddCell().SetString(rowData[i])
  389. }
  390. continue
  391. }
  392. // 其他行开票到款, 加四列空的单元格用于合并
  393. dataRowExtra := sheet.AddRow()
  394. for i := 0; i < 4; i++ {
  395. dataRowExtra.AddCell()
  396. }
  397. for i := range rowData {
  398. dataRowExtra.AddCell().SetString(rowData[i])
  399. }
  400. }
  401. }
  402. // 输出文件
  403. var buffer bytes.Buffer
  404. _ = xlsxFile.Write(&buffer)
  405. content := bytes.NewReader(buffer.Bytes())
  406. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  407. fileName := "商品到款统计_" + randStr + ".xlsx"
  408. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  409. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  410. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  411. }