invoice_payment.go 27 KB

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