income_list.go 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724
  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"
  11. "hongze/fms_api/models/base"
  12. "hongze/fms_api/models/fms"
  13. "hongze/fms_api/services/alarm_msg"
  14. "hongze/fms_api/utils"
  15. "net/http"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. // IncomeList
  22. // @Title 业务收入统计表
  23. // @Description 获取业务收入统计表接口
  24. // @Param ListParam query int false "套餐类型: 0-月度; 1-季度; 2-半年度;3-年度;4-月度累计"
  25. // @Success 200 {object} fms.CensusIncomeChartResp
  26. // @router /census/income/chart_list [get]
  27. func (this *InvoicePaymentController) IncomeChartList(c *gin.Context) {
  28. var req fms.IncomeChartListReq
  29. if e := c.BindQuery(&req); e != nil {
  30. err, ok := e.(validator.ValidationErrors)
  31. if !ok {
  32. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  33. return
  34. }
  35. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  36. return
  37. }
  38. //收入统计
  39. var incomeList models.CensusIncomeChartResp
  40. ch := make(chan models.CensusIncomeChartResp, 1)
  41. if req.IncomeType == 0 {
  42. go getCensusIncomeChartList(ch, req)
  43. } else {
  44. go getPaymentIncomeChartList(ch, req)
  45. }
  46. for v := range ch {
  47. incomeList = v
  48. close(ch)
  49. }
  50. resp.OkData("获取成功", incomeList, c)
  51. }
  52. func getCensusIncomeChartList(ch chan models.CensusIncomeChartResp, req fms.IncomeChartListReq) (incomeChart models.CensusIncomeChartResp, err error) {
  53. defer func() {
  54. if err != nil {
  55. global.LOG.Error(err)
  56. if err != utils.ErrNoRow {
  57. go alarm_msg.SendAlarmMsg("获取业务收入金额统计数据异常,Err:"+err.Error(), 3)
  58. }
  59. }
  60. ch <- incomeChart
  61. }()
  62. //todayStr := utils.GetToday("20060102")
  63. //key := "admin:home:fmsIncomeList:" + todayStr
  64. //
  65. //redisJsonData, redisErr := global.Redis.Get(context.TODO(), key).Result()
  66. //if redisErr != nil {
  67. //获取最新的开票到款日期
  68. cond := ``
  69. historyCond := ``
  70. pars := make([]interface{}, 0)
  71. historyPars := make([]interface{}, 0)
  72. if req.SellerIds != "" {
  73. sellerIds := strings.Split(req.SellerIds, ",")
  74. cond += ` AND (a.seller_id in ? ) `
  75. historyCond += ` AND (seller_id in ? ) `
  76. pars = append(pars, sellerIds)
  77. historyPars = append(historyPars, sellerIds)
  78. }
  79. if req.CompanyType == 1 {
  80. cond += ` AND b.contract_type = 1 `
  81. historyCond += ` AND new_company = 1 `
  82. } else if req.CompanyType == 2 {
  83. cond += ` AND b.contract_type IN (2,3,4) `
  84. historyCond += ` AND new_company = 0 `
  85. }
  86. var latestTime time.Time
  87. invoiceItem, err := fms.GetLatestIncome(cond, pars)
  88. if err != nil && err != utils.ErrNoRow {
  89. err = fmt.Errorf("获取最新的开票或到款日期, Err: %s", err.Error())
  90. return
  91. }
  92. latestTime = invoiceItem.InvoiceDate
  93. if err == utils.ErrNoRow {
  94. historyItem, e := fms.GetLatestHistoryIncome(historyCond, historyPars)
  95. if e != nil && e != utils.ErrNoRow {
  96. err = fmt.Errorf("获取最新的历史开票或到款日期, Err: %s", e.Error())
  97. return
  98. }
  99. latestTime = historyItem.InvoiceDate
  100. }
  101. if latestTime.IsZero() {
  102. latestTime = time.Now()
  103. }
  104. if req.CompanyType == 3 {
  105. cond += ` AND b.contract_type IN (2,3,4) `
  106. historyCond += ` AND new_company = 0 `
  107. }
  108. latestTime = latestTime.AddDate(0, 0, -latestTime.Day()+1)
  109. addMonth := 0
  110. if req.ListParam == "1" {
  111. addMonth = int(3 - latestTime.Month()%3)
  112. }
  113. if req.ListParam == "2" {
  114. addMonth = int(6 - latestTime.Month()%6)
  115. }
  116. if req.ListParam == "3" {
  117. addMonth = int(12 - latestTime.Month()%12)
  118. }
  119. latestTime = latestTime.AddDate(0, addMonth, 0)
  120. var dateSlice []string
  121. var totalMoneySlice, prevTotalMoneySlice []float64
  122. var yoySlice []string
  123. var yearNum, monthNum int
  124. var reqStartDate, reqEndDate time.Time
  125. historyTime, _ := time.Parse(utils.FormatDate, "2023-04-01")
  126. // 套餐筛选
  127. if req.ServiceTypes != "" {
  128. serviceTypes := strings.Split(req.ServiceTypes, ",")
  129. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  130. if e != nil {
  131. err = fmt.Errorf("获取合同登记IDs失败, Err: %s", e.Error())
  132. return
  133. }
  134. if len(registerIds) > 0 {
  135. cond += ` AND b.contract_register_id IN ?`
  136. pars = append(pars, registerIds)
  137. } else {
  138. cond += ` AND 1 = 2`
  139. }
  140. // 勾选套餐筛选时忽略导入的历史数据
  141. if req.StartDate == "" {
  142. req.StartDate = "2023-04"
  143. req.EndDate = "3023-04"
  144. } else {
  145. startDateTime, _ := time.Parse(utils.FormatMonth, req.StartDate)
  146. if startDateTime.Before(historyTime) {
  147. req.StartDate = "2023-04"
  148. }
  149. }
  150. }
  151. if req.StartDate != "" && req.EndDate != "" {
  152. st := fmt.Sprint(req.StartDate, "-01 00:00:00")
  153. ed := fmt.Sprint(req.EndDate, "-01 23:59:59")
  154. reqStartDate, _ = time.Parse(utils.FormatDateTime, st)
  155. reqEndDate, _ = time.Parse(utils.FormatDateTime, ed)
  156. if reqEndDate.After(latestTime) {
  157. yearNum = latestTime.Year() - reqStartDate.Year()
  158. monthNum = int(latestTime.Month() - reqStartDate.Month())
  159. } else {
  160. yearNum = reqEndDate.Year() - reqStartDate.Year()
  161. monthNum = int(reqEndDate.Month() - reqStartDate.Month())
  162. }
  163. } else {
  164. yearNum = latestTime.Year() - 2020
  165. monthNum = int(latestTime.Month() - 1)
  166. }
  167. //if yearNum < 0 {
  168. // yearNum = -yearNum
  169. //}
  170. //if monthNum < 0 {
  171. // monthNum = -monthNum
  172. //}
  173. numMonth := yearNum*12 + monthNum //共存在多少个月
  174. if numMonth < 0 {
  175. numMonth = -numMonth
  176. }
  177. //if req.ListParam == "1" {
  178. // numMonth = numMonth / 3
  179. //} else if req.ListParam == "2" {
  180. // numMonth = numMonth / 6
  181. //} else if req.ListParam == "3" {
  182. // numMonth = numMonth / 12
  183. //}
  184. // 累计值
  185. var accumulate float64
  186. var partAccumulate float64
  187. var historyAccumulate float64
  188. var partHistoryAccumulate float64
  189. //dataList := make([]*fms.IncomeSummaryItem, 0)
  190. //historydataList := make([]*fms.IncomeSummaryItem, 0)
  191. fmt.Println("numMonth:", numMonth)
  192. fmt.Println("InvoiceDate:", latestTime)
  193. var j int
  194. for i := 0; i <= numMonth; i++ {
  195. //timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
  196. var endDateTime time.Time
  197. var prevEndDateTime time.Time
  198. var prevStartDate, prevEndDate string
  199. var startDate, endDate string
  200. //开始日期
  201. if req.StartDate != "" && req.EndDate != "" {
  202. startDate = reqStartDate.AddDate(0, i, 0).Format("2006-01")
  203. prevStartDate = reqStartDate.AddDate(-1, i, 0).Format("2006-01")
  204. } else {
  205. startDate = latestTime.AddDate(0, i-numMonth, 0).Format("2006-01")
  206. prevStartDate = latestTime.AddDate(-1, i-numMonth, 0).Format("2006-01")
  207. }
  208. startDate = fmt.Sprint(startDate, "-01")
  209. prevStartDate = fmt.Sprint(prevStartDate, "-01")
  210. startDateTime, _ := time.Parse(utils.FormatDate, startDate)
  211. prevStartDateTime, _ := time.Parse(utils.FormatDate, prevStartDate)
  212. //结束日期
  213. if req.StartDate != "" && req.EndDate != "" {
  214. endDateTime = reqStartDate.AddDate(0, i+1, -1)
  215. prevEndDateTime = reqStartDate.AddDate(-1, i+1, -1)
  216. if reqEndDate.After(latestTime) {
  217. endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
  218. prevEndDateTime = latestTime.AddDate(-1, i-numMonth+1, -1)
  219. }
  220. } else {
  221. endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
  222. prevEndDateTime = latestTime.AddDate(-1, i-numMonth+1, -1)
  223. }
  224. endDate = endDateTime.Format(utils.FormatDate)
  225. prevEndDate = prevEndDateTime.Format(utils.FormatDate)
  226. cond := `1 = 1`
  227. histrtyCond := `1 = 1`
  228. pars := make([]interface{}, 0)
  229. historyPars := make([]interface{}, 0)
  230. prevCond := `1 = 1`
  231. prevHistoryCond := `1 = 1`
  232. prevPars := make([]interface{}, 0)
  233. prevHistoryPars := make([]interface{}, 0)
  234. if req.CompanyType == 1 {
  235. cond += ` AND b.contract_type = 1 `
  236. prevCond += ` AND b.contract_type = 1 `
  237. histrtyCond += ` AND new_company = 1 `
  238. prevHistoryCond += ` AND new_company = 1 `
  239. } else if req.CompanyType == 2 {
  240. cond += ` AND b.contract_type IN (2,3,4) `
  241. prevCond += ` AND b.contract_type IN (2,3,4) `
  242. histrtyCond += ` AND new_company = 0 `
  243. prevHistoryCond += ` AND new_company = 0 `
  244. } else if req.CompanyType == 3 {
  245. //未续约收入金额=去年同期总收入金额(新客户+老客户)-当期老客户收入金额
  246. cond += ` AND b.contract_type IN (2,3,4) `
  247. //prevCond += ` AND b.contract_type IN (2,3,4) `
  248. histrtyCond += ` AND new_company = 0 `
  249. //prevHistoryCond += ` AND new_company = 0 `
  250. }
  251. if req.SellerIds != "" {
  252. sellerIds := strings.Split(req.SellerIds, ",")
  253. cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  254. pars = append(pars, sellerIds, sellerIds)
  255. prevCond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  256. prevPars = append(prevPars, sellerIds, sellerIds)
  257. histrtyCond += ` AND seller_id in ? `
  258. prevHistoryCond += ` AND seller_id in ? `
  259. historyPars = append(historyPars, sellerIds)
  260. prevHistoryPars = append(prevHistoryPars, sellerIds)
  261. }
  262. // 套餐筛选
  263. if req.ServiceTypes != "" {
  264. serviceTypes := strings.Split(req.ServiceTypes, ",")
  265. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  266. if e != nil {
  267. err = fmt.Errorf("获取合同登记IDs失败, Err: %s", e.Error())
  268. return
  269. }
  270. if len(registerIds) > 0 {
  271. cond += ` AND a.register_id IN ?`
  272. prevCond += ` AND a.register_id IN ?`
  273. pars = append(pars, registerIds)
  274. prevPars = append(pars, registerIds)
  275. } else {
  276. cond += ` AND 1 = 2`
  277. prevCond += ` AND 1 = 2`
  278. }
  279. }
  280. //fmt.Println("i:",i)
  281. //fmt.Println("j:",j)
  282. {
  283. //本期
  284. st := fmt.Sprint(startDate, " 00:00:00")
  285. ed := fmt.Sprint(endDate, " 23:59:59")
  286. //校验日期,分段查询
  287. if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
  288. //全部走新查询
  289. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  290. pars = append(pars, st, ed, st, ed)
  291. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  292. if e != nil {
  293. return
  294. }
  295. // 开票到款金额合计(换算后)
  296. var amountTotal float64
  297. if len(summaryIds) > 0 {
  298. amountCond := `a.id IN ? `
  299. amountPars := make([]interface{}, 0)
  300. amountPars = append(amountPars, summaryIds)
  301. if req.SellerIds != "" {
  302. sellerIds := strings.Split(req.SellerIds, ",")
  303. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  304. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  305. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  306. } else {
  307. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  308. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  309. amountPars = append(amountPars, st, ed, st, ed)
  310. }
  311. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  312. if e != nil {
  313. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  314. return
  315. }
  316. //dataList = append(dataList, results...)
  317. var amountSum float64
  318. for _, result := range results {
  319. incomeChart.DataList = append(incomeChart.DataList, result)
  320. amountSum += result.Amount
  321. fmt.Println("result.Amount:", result.Amount)
  322. }
  323. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  324. accumulate += amountTotal
  325. partAccumulate += amountTotal
  326. }
  327. if i == j || i == numMonth {
  328. if req.ListParam == "4" {
  329. totalMoneySlice = append(totalMoneySlice, accumulate)
  330. if startDateTime.Month() == 12 {
  331. accumulate = 0
  332. }
  333. } else if req.ListParam == "0" {
  334. totalMoneySlice = append(totalMoneySlice, amountTotal)
  335. } else if i > 0 || i == numMonth {
  336. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  337. fmt.Println("partAccumulate:", partAccumulate)
  338. partAccumulate = 0.0
  339. }
  340. }
  341. } else if endDateTime.Before(historyTime) || endDateTime.Equal(historyTime) {
  342. //全部走旧查询
  343. //fmt.Println("旧查询")
  344. //fmt.Println("st:",st)
  345. //fmt.Println("ed:",ed)
  346. histrtyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  347. historyPars = append(historyPars, st, ed)
  348. //fmt.Println("st:",st)
  349. //fmt.Println("ed:",ed)
  350. // 开票到款金额合计(换算后)
  351. var amountTotal float64
  352. results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
  353. if e != nil {
  354. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  355. return
  356. }
  357. var amountSum float64
  358. //dataList = append(dataList, results...)
  359. for _, result := range results {
  360. incomeChart.DataList = append(incomeChart.DataList, result)
  361. amountSum += result.Amount
  362. }
  363. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  364. accumulate += amountTotal
  365. partAccumulate += amountTotal
  366. if i == j || i == numMonth {
  367. if req.ListParam == "4" {
  368. totalMoneySlice = append(totalMoneySlice, accumulate)
  369. if startDateTime.Month() == 12 {
  370. accumulate = 0
  371. }
  372. } else if req.ListParam == "0" {
  373. totalMoneySlice = append(totalMoneySlice, amountTotal)
  374. } else if i > 0 || i == numMonth {
  375. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  376. partAccumulate = 0.0
  377. }
  378. }
  379. //fmt.Println("partAccumulate:",partAccumulate)
  380. }
  381. }
  382. { // 去年同期,用于计算同比值
  383. prevSt := fmt.Sprint(prevStartDate, " 00:00:00") // 格式化上一年同一天的开始时间
  384. prevEd := fmt.Sprint(prevEndDate, " 23:59:59") // 格式化上一年同一天的结束时间
  385. // 校验日期,分段查询
  386. if prevStartDateTime.After(historyTime) || prevStartDateTime.Equal(historyTime) {
  387. // 全部走新查询
  388. prevCond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))` // 查询条件加入新的时间范围
  389. prevPars = append(prevPars, prevSt, prevEd, prevSt, prevEd) // 添加时间参数到参数列表
  390. prevSummaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(prevCond, prevPars) // 获取摘要ID列表
  391. if e != nil {
  392. return
  393. }
  394. // 开票到款金额合计(换算后)
  395. var prevAmountTotal float64
  396. if len(prevSummaryIds) > 0 {
  397. amountCond := `a.id IN ? ` // 查询条件为ID在给定的摘要ID列表中
  398. amountPars := make([]interface{}, 0)
  399. amountPars = append(amountPars, prevSummaryIds) // 将摘要ID列表添加到参数列表
  400. if req.SellerIds != "" {
  401. sellerIds := strings.Split(req.SellerIds, ",")
  402. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  403. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) ` // 根据卖家ID和发票/支付状态筛选时间范围
  404. amountPars = append(amountPars, sellerIds, prevSt, prevEd, sellerIds, prevSt, prevEd) // 将卖家ID列表添加到参数列表
  405. } else {
  406. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  407. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))` // 根据发票/支付状态筛选时间范围
  408. amountPars = append(amountPars, prevSt, prevEd, prevSt, prevEd)
  409. }
  410. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars) // 获取合同摘要收入金额数据
  411. if e != nil {
  412. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  413. return
  414. }
  415. var amountSum float64
  416. //historydataList = append(historydataList, results...)
  417. for _, result := range results {
  418. amountSum += result.Amount // 累计收入金额
  419. }
  420. prevAmountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64) // 将累计金额转换为浮点数
  421. historyAccumulate += prevAmountTotal // 累计历史金额
  422. partHistoryAccumulate += prevAmountTotal // 累计部分历史金额
  423. }
  424. if i == j || i == numMonth {
  425. if req.ListParam == "4" {
  426. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate) // 将累计金额添加到总金额切片中
  427. if prevStartDateTime.Month() == 12 {
  428. historyAccumulate = 0 // 如果是去年的12月份,则将历史金额清零
  429. }
  430. } else if req.ListParam == "0" {
  431. prevTotalMoneySlice = append(prevTotalMoneySlice, prevAmountTotal) // 将部分历史金额添加到总金额切片中
  432. } else if i > 0 || i == numMonth {
  433. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate) // 将部分历史金额添加到总金额切片中
  434. fmt.Println("partHistoryAccumulate:", partHistoryAccumulate)
  435. partHistoryAccumulate = 0.0 // 清零部分历史金额
  436. }
  437. }
  438. } else if prevEndDateTime.Before(historyTime) || prevEndDateTime.Equal(historyTime) {
  439. // 全部走旧查询
  440. fmt.Println("prevSt:", prevSt)
  441. fmt.Println("prevEd:", prevEd)
  442. prevHistoryCond += ` AND (invoice_time BETWEEN ? AND ?)` // 查询条件加入旧的时间范围
  443. prevHistoryPars = append(prevHistoryPars, prevSt, prevEd) // 添加时间参数到参数列表
  444. // 开票到款金额合计(换算后)
  445. var amountTotal float64
  446. results, e := fms.GetIncomeHistory(prevHistoryCond, prevHistoryPars) // 获取历史收入数据
  447. if e != nil {
  448. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  449. return
  450. }
  451. //historydataList = append(historydataList, results...)
  452. var amountSum float64
  453. for _, result := range results {
  454. amountSum += result.Amount // 累计收入金额
  455. }
  456. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64) // 将累计金额转换为浮点数
  457. historyAccumulate += amountTotal // 累计历史金额
  458. partHistoryAccumulate += amountTotal // 累计部分历史金额
  459. if i == j || i == numMonth {
  460. if req.ListParam == "4" {
  461. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate) // 将累计金额添加到总金额切片中
  462. if prevStartDateTime.Month() == 12 {
  463. historyAccumulate = 0 // 如果是去年的12月份,则将历史金额清零
  464. }
  465. } else if req.ListParam == "0" {
  466. prevTotalMoneySlice = append(prevTotalMoneySlice, amountTotal) // 将历史金额添加到总金额切片中
  467. } else if i > 0 || i == numMonth {
  468. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate) // 将部分历史金额添加到总金额切片中
  469. fmt.Println("partHistoryAccumulate:", partHistoryAccumulate)
  470. partHistoryAccumulate = 0.0 // 清零部分历史金额
  471. }
  472. }
  473. if req.ListParam == "1" && i == j {
  474. if i == 0 {
  475. dateSlice = append(dateSlice, startDateTime.AddDate(0, 2, 0).Format("06/01")) // 添加下一个月份的开始日期到日期切片中
  476. j = j + 2
  477. } else {
  478. dateSlice = append(dateSlice, startDateTime.AddDate(0, 3, 0).Format("06/01")) // 添加下一季度的开始日期到日期切片中
  479. j = j + 3
  480. }
  481. } else if req.ListParam == "2" && i == j {
  482. if i == 0 {
  483. dateSlice = append(dateSlice, startDateTime.AddDate(0, 5, 0).Format("06/01")) // 添加下五个月份的开始日期到日期切片中
  484. j = j + 5
  485. } else {
  486. dateSlice = append(dateSlice, startDateTime.AddDate(0, 6, 0).Format("06/01")) // 添加下半年的开始日期到日期切片中
  487. j = j + 6
  488. }
  489. } else if req.ListParam == "3" && i == j {
  490. if i == 0 {
  491. dateSlice = append(dateSlice, startDateTime.AddDate(0, 11, 0).Format("06/01")) // 添加下十一个月份的开始日期到日期切片中
  492. j = j + 11
  493. } else {
  494. dateSlice = append(dateSlice, startDateTime.AddDate(0, 12, 0).Format("06/01")) // 添加下一季度的开始日期到日期切片中
  495. j = j + 12
  496. }
  497. } else if i == j {
  498. dateSlice = append(dateSlice, startDateTime.Format("06/01")) // 添加当月开始日期到日期切片中
  499. j++
  500. }
  501. }
  502. if req.ListParam == "1" && i == j {
  503. if i == 0 {
  504. dateSlice = append(dateSlice, startDateTime.AddDate(0, 2, 0).Format("06/01")) // 添加下一个月份的开始日期到日期切片中
  505. j = j + 2
  506. } else {
  507. dateSlice = append(dateSlice, startDateTime.AddDate(0, 3, 0).Format("06/01")) // 添加下一季度的开始日期到日期切片中
  508. j = j + 3
  509. }
  510. } else if req.ListParam == "2" && i == j {
  511. if i == 0 {
  512. dateSlice = append(dateSlice, startDateTime.AddDate(0, 5, 0).Format("06/01")) // 添加下五个月份的开始日期到日期切片中
  513. j = j + 5
  514. } else {
  515. dateSlice = append(dateSlice, startDateTime.AddDate(0, 6, 0).Format("06/01")) // 添加下半年的开始日期到日期切片中
  516. j = j + 6
  517. }
  518. } else if req.ListParam == "3" && i == j {
  519. if i == 0 {
  520. dateSlice = append(dateSlice, startDateTime.AddDate(0, 11, 0).Format("06/01"))
  521. j = j + 11
  522. } else {
  523. dateSlice = append(dateSlice, startDateTime.AddDate(0, 12, 0).Format("06/01"))
  524. j = j + 12
  525. }
  526. } else if i == j {
  527. dateSlice = append(dateSlice, startDateTime.Format("06/01"))
  528. j++
  529. }
  530. }
  531. }
  532. fmt.Println("prevTotalMoneySlice:", len(prevTotalMoneySlice))
  533. fmt.Println("totalMoneySlice:", len(totalMoneySlice))
  534. if req.CompanyType != 3 {
  535. //计算同比值
  536. for i := range prevTotalMoneySlice {
  537. var yoy float64
  538. var yoyStr string
  539. //fmt.Println("1:", prevTotalMoneySlice[i])
  540. //fmt.Println("2:", totalMoneySlice[i])
  541. //fmt.Println("3:", totalMoneySlice[i]-prevTotalMoneySlice[i])
  542. totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", totalMoneySlice[i]), 64)
  543. if prevTotalMoneySlice[i] != 0 && totalMoneySlice[i] != 0 {
  544. yoy = (totalMoneySlice[i] - prevTotalMoneySlice[i]) / prevTotalMoneySlice[i]
  545. yoyStr = fmt.Sprintf("%.4f", yoy)
  546. if i == len(prevTotalMoneySlice)-1 && i > 0 && req.ListParam == "3" {
  547. fmt.Println("totalMoneySlice[i-1]:", totalMoneySlice[i-1])
  548. yoy = (totalMoneySlice[i] - totalMoneySlice[i-1]) / totalMoneySlice[i-1]
  549. yoyStr = fmt.Sprintf("%.4f", yoy)
  550. }
  551. }
  552. yoySlice = append(yoySlice, yoyStr)
  553. }
  554. } else {
  555. // 当筛选条件是”月度“时,并且客户是”未续约“客户,展示柱形图和曲线图
  556. // 当筛选条件是”季度“、”半年度“、”年度“、”月度统计“时,并且客户是”未续约“时,仅展示柱形图,无曲线图
  557. // 未续约收入金额=去年同期总收入金额(新客户+老客户)-当期老客户收入金额
  558. // 移动平均值:若是10月份,计算8月,9月,10月,这三个月的收入金额平均值
  559. for i := range prevTotalMoneySlice {
  560. totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", prevTotalMoneySlice[i]-totalMoneySlice[i]), 64)
  561. var yoy float64
  562. var yoyStr string
  563. if i > 1 && req.ListParam == "0" {
  564. // 前俩月没有
  565. yoy = (totalMoneySlice[i] + totalMoneySlice[i-1] + totalMoneySlice[i-2]) / 3
  566. yoyStr = fmt.Sprintf("%.4f", yoy)
  567. yoySlice = append(yoySlice, yoyStr)
  568. } else {
  569. yoySlice = append(yoySlice, "")
  570. }
  571. }
  572. }
  573. incomeChart.Title = "开票到款统计图"
  574. incomeChart.Date = dateSlice[:len(totalMoneySlice)]
  575. incomeChart.TotalMoney = totalMoneySlice
  576. incomeChart.PrevTotalMoney = prevTotalMoneySlice
  577. incomeChart.Yoy = yoySlice
  578. //redisJsonData, err := json.Marshal(incomeChart)
  579. //if err == nil {
  580. // global.Redis.SetEX(context.TODO(), key, string(redisJsonData), time.Minute*30)
  581. //}
  582. //} else {
  583. // err = json.Unmarshal([]byte(redisJsonData), &incomeChart)
  584. // if err != nil {
  585. // fmt.Println("近两年的收入统计数据,json转换失败")
  586. // }
  587. //}
  588. return
  589. }
  590. func getPaymentIncomeChartList(ch chan models.CensusIncomeChartResp, req fms.IncomeChartListReq) (incomeChart models.CensusIncomeChartResp, err error) {
  591. defer func() {
  592. if err != nil {
  593. global.LOG.Error(err)
  594. if err != utils.ErrNoRow {
  595. go alarm_msg.SendAlarmMsg("获取业务收入金额统计数据异常,Err:"+err.Error(), 3)
  596. }
  597. }
  598. ch <- incomeChart
  599. }()
  600. //todayStr := utils.GetToday("20060102")
  601. //key := "admin:home:fmsIncomeList:" + todayStr
  602. //
  603. //redisJsonData, redisErr := global.Redis.Get(context.TODO(), key).Result()
  604. //if redisErr != nil {
  605. //获取最新的开票到款日期
  606. cond := ``
  607. historyCond := ``
  608. pars := make([]interface{}, 0)
  609. historyPars := make([]interface{}, 0)
  610. if req.SellerIds != "" {
  611. sellerIds := strings.Split(req.SellerIds, ",")
  612. cond += ` AND (a.seller_id in ? ) `
  613. historyCond += ` AND (seller_id in ? ) `
  614. pars = append(pars, sellerIds)
  615. historyPars = append(historyPars, sellerIds)
  616. }
  617. if req.CompanyType == 1 {
  618. cond += ` AND b.contract_type = 1 `
  619. historyCond += ` AND new_company = 1 `
  620. } else if req.CompanyType == 2 {
  621. cond += ` AND b.contract_type IN (2,3,4) `
  622. historyCond += ` AND new_company = 0 `
  623. }
  624. var earliestTime time.Time
  625. EarliestinvoiceItem, err := fms.GetEarliestPaymentIncome(cond, pars)
  626. if err != nil && err != utils.ErrNoRow {
  627. err = fmt.Errorf("获取最新的开票或到款日期, Err: %s", err.Error())
  628. return
  629. }
  630. earliestTime = EarliestinvoiceItem.InvoiceDate
  631. var latestTime time.Time
  632. invoiceItem, err := fms.GetLatestPaymentIncome(cond, pars)
  633. if err != nil && err != utils.ErrNoRow {
  634. err = fmt.Errorf("获取最新的开票或到款日期, Err: %s", err.Error())
  635. return
  636. }
  637. latestTime = invoiceItem.InvoiceDate
  638. if latestTime.IsZero() {
  639. latestTime = time.Now()
  640. }
  641. if req.CompanyType == 3 {
  642. cond += ` AND b.contract_type IN (2,3,4) `
  643. historyCond += ` AND new_company = 0 `
  644. }
  645. latestTime = latestTime.AddDate(0, 0, -latestTime.Day()+1)
  646. addMonth := 0
  647. if req.ListParam == "1" {
  648. addMonth = int(3 - latestTime.Month()%3)
  649. }
  650. if req.ListParam == "2" {
  651. addMonth = int(6 - latestTime.Month()%6)
  652. }
  653. if req.ListParam == "3" {
  654. addMonth = int(12 - latestTime.Month()%12)
  655. }
  656. latestTime = latestTime.AddDate(0, addMonth, 0)
  657. var dateSlice []string
  658. var totalMoneySlice, prevTotalMoneySlice []float64
  659. var yoySlice []string
  660. var yearNum, monthNum int
  661. var reqStartDate, reqEndDate time.Time
  662. // 套餐筛选
  663. if req.ServiceTypes != "" {
  664. serviceTypes := strings.Split(req.ServiceTypes, ",")
  665. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  666. if e != nil {
  667. err = fmt.Errorf("获取合同登记IDs失败, Err: %s", e.Error())
  668. return
  669. }
  670. if len(registerIds) > 0 {
  671. cond += ` AND b.contract_register_id IN ?`
  672. pars = append(pars, registerIds)
  673. } else {
  674. cond += ` AND 1 = 2`
  675. }
  676. }
  677. if req.StartDate != "" && req.EndDate != "" {
  678. st := fmt.Sprint(req.StartDate, "-01 00:00:00")
  679. ed := fmt.Sprint(req.EndDate, "-01 23:59:59")
  680. reqStartDate, _ = time.Parse(utils.FormatDateTime, st)
  681. reqEndDate, _ = time.Parse(utils.FormatDateTime, ed)
  682. if reqEndDate.After(latestTime) {
  683. yearNum = latestTime.Year() - reqStartDate.Year()
  684. monthNum = int(latestTime.Month() - reqStartDate.Month())
  685. } else {
  686. yearNum = reqEndDate.Year() - reqStartDate.Year()
  687. monthNum = int(reqEndDate.Month() - reqStartDate.Month())
  688. }
  689. } else {
  690. yearNum = latestTime.Year() - earliestTime.Year()
  691. monthNum = int(latestTime.Month() - earliestTime.Month())
  692. }
  693. numMonth := yearNum*12 + monthNum //共存在多少个月
  694. if numMonth < 0 {
  695. numMonth = -numMonth
  696. }
  697. // 累计值
  698. var accumulate float64
  699. var partAccumulate float64
  700. var historyAccumulate float64
  701. var partHistoryAccumulate float64
  702. //dataList := make([]*fms.IncomeSummaryItem, 0)
  703. //historydataList := make([]*fms.IncomeSummaryItem, 0)
  704. fmt.Println("numMonth:", numMonth)
  705. fmt.Println("InvoiceDate:", latestTime)
  706. var j int
  707. for i := 0; i <= numMonth; i++ {
  708. //timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
  709. var endDateTime time.Time
  710. var prevEndDateTime time.Time
  711. var prevStartDate, prevEndDate string
  712. var startDate, endDate string
  713. //开始日期
  714. if req.StartDate != "" && req.EndDate != "" {
  715. startDate = reqStartDate.AddDate(0, i, 0).Format("2006-01")
  716. prevStartDate = reqStartDate.AddDate(-1, i, 0).Format("2006-01")
  717. } else {
  718. startDate = latestTime.AddDate(0, i-numMonth, 0).Format("2006-01")
  719. prevStartDate = latestTime.AddDate(-1, i-numMonth, 0).Format("2006-01")
  720. }
  721. startDate = fmt.Sprint(startDate, "-01")
  722. prevStartDate = fmt.Sprint(prevStartDate, "-01")
  723. startDateTime, _ := time.Parse(utils.FormatDate, startDate)
  724. prevStartDateTime, _ := time.Parse(utils.FormatDate, prevStartDate)
  725. //结束日期
  726. if req.StartDate != "" && req.EndDate != "" {
  727. endDateTime = reqStartDate.AddDate(0, i+1, -1)
  728. prevEndDateTime = reqStartDate.AddDate(-1, i+1, -1)
  729. if reqEndDate.After(latestTime) {
  730. endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
  731. prevEndDateTime = latestTime.AddDate(-1, i-numMonth+1, -1)
  732. }
  733. } else {
  734. endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
  735. prevEndDateTime = latestTime.AddDate(-1, i-numMonth+1, -1)
  736. }
  737. endDate = endDateTime.Format(utils.FormatDate)
  738. prevEndDate = prevEndDateTime.Format(utils.FormatDate)
  739. cond := `1 = 1`
  740. histrtyCond := `1 = 1`
  741. pars := make([]interface{}, 0)
  742. historyPars := make([]interface{}, 0)
  743. prevCond := `1 = 1`
  744. prevHistoryCond := `1 = 1`
  745. prevPars := make([]interface{}, 0)
  746. prevHistoryPars := make([]interface{}, 0)
  747. if req.CompanyType == 1 {
  748. cond += ` AND b.contract_type = 1 `
  749. prevCond += ` AND b.contract_type = 1 `
  750. histrtyCond += ` AND new_company = 1 `
  751. prevHistoryCond += ` AND new_company = 1 `
  752. } else if req.CompanyType == 2 {
  753. cond += ` AND b.contract_type IN (2,3,4) `
  754. prevCond += ` AND b.contract_type IN (2,3,4) `
  755. histrtyCond += ` AND new_company = 0 `
  756. prevHistoryCond += ` AND new_company = 0 `
  757. } else if req.CompanyType == 3 {
  758. //未续约收入金额=去年同期总收入金额(新客户+老客户)-当期老客户收入金额
  759. cond += ` AND b.contract_type IN (2,3,4) `
  760. //prevCond += ` AND b.contract_type IN (2,3,4) `
  761. histrtyCond += ` AND new_company = 0 `
  762. //prevHistoryCond += ` AND new_company = 0 `
  763. }
  764. if req.SellerIds != "" {
  765. sellerIds := strings.Split(req.SellerIds, ",")
  766. cond += ` AND d.seller_id in ? `
  767. pars = append(pars, sellerIds)
  768. prevCond += ` AND d.seller_id in ?`
  769. prevPars = append(prevPars, sellerIds)
  770. histrtyCond += ` AND seller_id in ? `
  771. prevHistoryCond += ` AND seller_id in ? `
  772. historyPars = append(historyPars, sellerIds)
  773. prevHistoryPars = append(prevHistoryPars, sellerIds)
  774. }
  775. // 套餐筛选
  776. if req.ServiceTypes != "" {
  777. serviceTypes := strings.Split(req.ServiceTypes, ",")
  778. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  779. if e != nil {
  780. err = fmt.Errorf("获取合同登记IDs失败, Err: %s", e.Error())
  781. return
  782. }
  783. if len(registerIds) > 0 {
  784. cond += ` AND a.register_id IN ?`
  785. prevCond += ` AND a.register_id IN ?`
  786. pars = append(pars, registerIds)
  787. prevPars = append(pars, registerIds)
  788. } else {
  789. cond += ` AND 1 = 2`
  790. prevCond += ` AND 1 = 2`
  791. }
  792. }
  793. //fmt.Println("i:",i)
  794. //fmt.Println("j:",j)
  795. {
  796. //本期
  797. st := fmt.Sprint(startDate, " 00:00:00")
  798. ed := fmt.Sprint(endDate, " 23:59:59")
  799. //校验日期
  800. //全部走新查询
  801. cond += ` AND (d.invoice_time BETWEEN ? AND ?)`
  802. pars = append(pars, st, ed, st, ed)
  803. summaryIds, e := fms.GetPaymentCensusSummaryDataIds(cond, pars)
  804. if e != nil {
  805. return
  806. }
  807. // 开票到款金额合计(换算后)
  808. var amountTotal float64
  809. if len(summaryIds) > 0 {
  810. amountCond := `a.id IN ? `
  811. amountPars := make([]interface{}, 0)
  812. amountPars = append(amountPars, summaryIds)
  813. if req.SellerIds != "" {
  814. sellerIds := strings.Split(req.SellerIds, ",")
  815. amountCond += `AND ( d.seller_id IN ? AND a.payment_id <> 0 AND d.invoice_time BETWEEN ? AND ?) `
  816. amountPars = append(amountPars, sellerIds, st, ed)
  817. } else {
  818. amountCond += `AND (a.payment_id <> 0 AND d.invoice_time BETWEEN ? AND ?)`
  819. amountPars = append(amountPars, st, ed, st, ed)
  820. }
  821. results, e := fms.GetContractSummaryPaymentIncomeAmount(amountCond, amountPars)
  822. if e != nil {
  823. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  824. return
  825. }
  826. //dataList = append(dataList, results...)
  827. var amountSum float64
  828. for _, result := range results {
  829. incomeChart.DataList = append(incomeChart.DataList, result)
  830. amountSum += result.Amount
  831. fmt.Println("result.Amount:", result.Amount)
  832. }
  833. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  834. accumulate += amountTotal
  835. partAccumulate += amountTotal
  836. }
  837. if i == j || i == numMonth {
  838. if req.ListParam == "4" {
  839. totalMoneySlice = append(totalMoneySlice, accumulate)
  840. if startDateTime.Month() == 12 {
  841. accumulate = 0
  842. }
  843. } else if req.ListParam == "0" {
  844. totalMoneySlice = append(totalMoneySlice, amountTotal)
  845. } else if i > 0 || i == numMonth {
  846. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  847. fmt.Println("partAccumulate:", partAccumulate)
  848. partAccumulate = 0.0
  849. }
  850. }
  851. }
  852. { // 去年同期,用于计算同比值
  853. prevSt := fmt.Sprint(prevStartDate, " 00:00:00") // 格式化上一年同一天的开始时间
  854. prevEd := fmt.Sprint(prevEndDate, " 23:59:59") // 格式化上一年同一天的结束时间
  855. // 校验日期,分段查询
  856. // 全部走新查询
  857. prevCond += ` AND (d.invoice_time BETWEEN ? AND ?)` // 查询条件加入新的时间范围
  858. prevPars = append(prevPars, prevSt, prevEd, prevSt, prevEd) // 添加时间参数到参数列表
  859. prevSummaryIds, e := fms.GetPaymentCensusSummaryDataIds(prevCond, prevPars) // 获取摘要ID列表
  860. if e != nil {
  861. return
  862. }
  863. // 开票到款金额合计(换算后)
  864. var prevAmountTotal float64
  865. if len(prevSummaryIds) > 0 {
  866. amountCond := `a.id IN ? ` // 查询条件为ID在给定的摘要ID列表中
  867. amountPars := make([]interface{}, 0)
  868. amountPars = append(amountPars, prevSummaryIds) // 将摘要ID列表添加到参数列表
  869. if req.SellerIds != "" {
  870. sellerIds := strings.Split(req.SellerIds, ",")
  871. amountCond += `AND ( d.seller_id IN ? AND a.payment_id <> 0 AND d.invoice_time BETWEEN ? AND ?) ` // 根据卖家ID和发票/支付状态筛选时间范围
  872. amountPars = append(amountPars, sellerIds, prevSt, prevEd, sellerIds, prevSt, prevEd) // 将卖家ID列表添加到参数列表
  873. } else {
  874. amountCond += `AND (a.payment_id <> 0 AND d.invoice_time BETWEEN ? AND ?)` // 根据发票/支付状态筛选时间范围
  875. amountPars = append(amountPars, prevSt, prevEd, prevSt, prevEd)
  876. }
  877. results, e := fms.GetContractSummaryPaymentIncomeAmount(amountCond, amountPars) // 获取合同摘要收入金额数据
  878. if e != nil {
  879. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  880. return
  881. }
  882. var amountSum float64
  883. //historydataList = append(historydataList, results...)
  884. for _, result := range results {
  885. amountSum += result.Amount // 累计收入金额
  886. }
  887. prevAmountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64) // 将累计金额转换为浮点数
  888. historyAccumulate += prevAmountTotal // 累计历史金额
  889. partHistoryAccumulate += prevAmountTotal // 累计部分历史金额
  890. }
  891. if i == j || i == numMonth {
  892. if req.ListParam == "4" {
  893. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate) // 将累计金额添加到总金额切片中
  894. if prevStartDateTime.Month() == 12 {
  895. historyAccumulate = 0 // 如果是去年的12月份,则将历史金额清零
  896. }
  897. } else if req.ListParam == "0" {
  898. prevTotalMoneySlice = append(prevTotalMoneySlice, prevAmountTotal) // 将部分历史金额添加到总金额切片中
  899. } else if i > 0 || i == numMonth {
  900. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate) // 将部分历史金额添加到总金额切片中
  901. fmt.Println("partHistoryAccumulate:", partHistoryAccumulate)
  902. partHistoryAccumulate = 0.0 // 清零部分历史金额
  903. }
  904. }
  905. if req.ListParam == "1" && i == j {
  906. if i == 0 {
  907. dateSlice = append(dateSlice, startDateTime.AddDate(0, 2, 0).Format("06/01")) // 添加下一个月份的开始日期到日期切片中
  908. j = j + 2
  909. } else {
  910. dateSlice = append(dateSlice, startDateTime.AddDate(0, 3, 0).Format("06/01")) // 添加下一季度的开始日期到日期切片中
  911. j = j + 3
  912. }
  913. } else if req.ListParam == "2" && i == j {
  914. if i == 0 {
  915. dateSlice = append(dateSlice, startDateTime.AddDate(0, 5, 0).Format("06/01")) // 添加下五个月份的开始日期到日期切片中
  916. j = j + 5
  917. } else {
  918. dateSlice = append(dateSlice, startDateTime.AddDate(0, 6, 0).Format("06/01")) // 添加下半年的开始日期到日期切片中
  919. j = j + 6
  920. }
  921. } else if req.ListParam == "3" && i == j {
  922. if i == 0 {
  923. dateSlice = append(dateSlice, startDateTime.AddDate(0, 11, 0).Format("06/01"))
  924. j = j + 11
  925. } else {
  926. dateSlice = append(dateSlice, startDateTime.AddDate(0, 12, 0).Format("06/01"))
  927. j = j + 12
  928. }
  929. } else if i == j {
  930. dateSlice = append(dateSlice, startDateTime.Format("06/01"))
  931. j++
  932. }
  933. }
  934. }
  935. fmt.Println("prevTotalMoneySlice:", len(prevTotalMoneySlice))
  936. fmt.Println("totalMoneySlice:", len(totalMoneySlice))
  937. if req.CompanyType != 3 {
  938. //计算同比值
  939. for i := range prevTotalMoneySlice {
  940. var yoy float64
  941. var yoyStr string
  942. //fmt.Println("1:", prevTotalMoneySlice[i])
  943. //fmt.Println("2:", totalMoneySlice[i])
  944. //fmt.Println("3:", totalMoneySlice[i]-prevTotalMoneySlice[i])
  945. totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", totalMoneySlice[i]), 64)
  946. if prevTotalMoneySlice[i] != 0 && totalMoneySlice[i] != 0 {
  947. yoy = (totalMoneySlice[i] - prevTotalMoneySlice[i]) / prevTotalMoneySlice[i]
  948. yoyStr = fmt.Sprintf("%.4f", yoy)
  949. if i == len(prevTotalMoneySlice)-1 && i > 0 && req.ListParam == "3" {
  950. fmt.Println("totalMoneySlice[i-1]:", totalMoneySlice[i-1])
  951. yoy = (totalMoneySlice[i] - totalMoneySlice[i-1]) / totalMoneySlice[i-1]
  952. yoyStr = fmt.Sprintf("%.4f", yoy)
  953. }
  954. }
  955. yoySlice = append(yoySlice, yoyStr)
  956. }
  957. } else {
  958. // 当筛选条件是”月度“时,并且客户是”未续约“客户,展示柱形图和曲线图
  959. // 当筛选条件是”季度“、”半年度“、”年度“、”月度统计“时,并且客户是”未续约“时,仅展示柱形图,无曲线图
  960. // 未续约收入金额=去年同期总收入金额(新客户+老客户)-当期老客户收入金额
  961. // 移动平均值:若是10月份,计算8月,9月,10月,这三个月的收入金额平均值
  962. for i := range prevTotalMoneySlice {
  963. totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", prevTotalMoneySlice[i]-totalMoneySlice[i]), 64)
  964. var yoy float64
  965. var yoyStr string
  966. if i > 1 && req.ListParam == "0" {
  967. // 前俩月没有
  968. yoy = (totalMoneySlice[i] + totalMoneySlice[i-1] + totalMoneySlice[i-2]) / 3
  969. yoyStr = fmt.Sprintf("%.4f", yoy)
  970. yoySlice = append(yoySlice, yoyStr)
  971. } else {
  972. yoySlice = append(yoySlice, "")
  973. }
  974. }
  975. }
  976. incomeChart.Title = "开票到款统计图"
  977. incomeChart.Date = dateSlice[:len(totalMoneySlice)]
  978. incomeChart.TotalMoney = totalMoneySlice
  979. incomeChart.PrevTotalMoney = prevTotalMoneySlice
  980. incomeChart.Yoy = yoySlice
  981. //redisJsonData, err := json.Marshal(incomeChart)
  982. //if err == nil {
  983. // global.Redis.SetEX(context.TODO(), key, string(redisJsonData), time.Minute*30)
  984. //}
  985. //} else {
  986. // err = json.Unmarshal([]byte(redisJsonData), &incomeChart)
  987. // if err != nil {
  988. // fmt.Println("近两年的收入统计数据,json转换失败")
  989. // }
  990. //}
  991. return
  992. }
  993. // IncomeList
  994. // @Title 业务收入统计表
  995. // @Description 获取业务收入统计表接口
  996. // @Param ListParam query int false "套餐类型: 0-月度; 1-季度; 2-半年度;3-年度;4-月度累计"
  997. // @Success 200 {object} fms.CensusIncomeChartResp
  998. // @router /census/income/list [get]
  999. func (this *InvoicePaymentController) IncomeList(c *gin.Context) {
  1000. var req fms.IncomeListReq
  1001. if e := c.BindQuery(&req); e != nil {
  1002. err, ok := e.(validator.ValidationErrors)
  1003. if !ok {
  1004. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1005. return
  1006. }
  1007. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1008. return
  1009. }
  1010. //收入统计
  1011. var incomeList base.BaseData
  1012. ch := make(chan base.BaseData, 1)
  1013. if req.IncomeType == 0 {
  1014. go getCensusIncomeList(ch, req)
  1015. } else {
  1016. go getPaymentIncomeList(ch, req)
  1017. }
  1018. for v := range ch {
  1019. incomeList = v
  1020. close(ch)
  1021. }
  1022. // 是否导出
  1023. if req.IsExport == 1 {
  1024. ExportIncomeList(c, incomeList.List, req.IncomeType)
  1025. return
  1026. }
  1027. resp.OkData("获取成功", incomeList, c)
  1028. }
  1029. func getPaymentIncomeList(ch chan base.BaseData, req fms.IncomeListReq) (baseData base.BaseData, err error) {
  1030. defer func() {
  1031. if err != nil {
  1032. global.LOG.Error(err)
  1033. if err != utils.ErrNoRow {
  1034. go alarm_msg.SendAlarmMsg("获取业务收入金额统计数据异常,Err:"+err.Error(), 3)
  1035. }
  1036. }
  1037. ch <- baseData
  1038. }()
  1039. var reqStartDate, reqEndDate time.Time
  1040. var startDate, endDate string
  1041. //开始日期
  1042. if req.StartDate != "" && req.EndDate != "" {
  1043. st := fmt.Sprint(req.StartDate, "-01 00:00:00")
  1044. ed := fmt.Sprint(req.EndDate, "-01 23:59:59")
  1045. reqStartDate, _ = time.Parse(utils.FormatDateTime, st)
  1046. reqEndDate, _ = time.Parse(utils.FormatDateTime, ed)
  1047. startDate = reqStartDate.Format(utils.FormatDate)
  1048. endDate = reqEndDate.AddDate(0, 1, -1).Format(utils.FormatDate)
  1049. }
  1050. cond := `1 = 1`
  1051. pars := make([]interface{}, 0)
  1052. if req.CompanyType == 1 {
  1053. cond += ` AND b.contract_type = 1 `
  1054. } else if req.CompanyType == 2 {
  1055. cond += ` AND b.contract_type IN (2,3,4) `
  1056. } else if req.CompanyType == 3 {
  1057. //未续约收入金额=去年同期总收入金额(新客户+老客户)-当期老客户收入金额
  1058. cond += ` AND b.contract_type IN (2,3,4) `
  1059. }
  1060. if req.SellerIds != "" {
  1061. sellerIds := strings.Split(req.SellerIds, ",")
  1062. cond += ` AND d.seller_id in ?`
  1063. pars = append(pars, sellerIds)
  1064. }
  1065. // 套餐筛选
  1066. if req.ServiceTypes != "" {
  1067. serviceTypes := strings.Split(req.ServiceTypes, ",")
  1068. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  1069. if e != nil {
  1070. err = fmt.Errorf("获取合同登记IDs失败, Err: %s", e.Error())
  1071. return
  1072. }
  1073. if len(registerIds) > 0 {
  1074. cond += ` AND a.register_id IN ?`
  1075. pars = append(pars, registerIds)
  1076. } else {
  1077. cond += ` AND 1 = 2`
  1078. }
  1079. }
  1080. {
  1081. if startDate != "" && endDate != "" {
  1082. st := fmt.Sprint(startDate, " 00:00:00")
  1083. ed := fmt.Sprint(endDate, " 23:59:59")
  1084. cond += ` AND (d.invoice_time BETWEEN ? AND ?)`
  1085. pars = append(pars, st, ed)
  1086. }
  1087. if req.Keyword != "" {
  1088. cond += ` AND b.company_name LIKE ?`
  1089. pars = append(pars, "%"+req.Keyword+"%")
  1090. }
  1091. summaryIds, e := fms.GetPaymentCensusSummaryDataIds(cond, pars)
  1092. if e != nil {
  1093. return
  1094. }
  1095. if len(summaryIds) > 0 {
  1096. amountCond := `a.id IN ? `
  1097. amountPars := make([]interface{}, 0)
  1098. amountPars = append(amountPars, summaryIds)
  1099. if req.SellerIds != "" {
  1100. sellerIds := strings.Split(req.SellerIds, ",")
  1101. amountCond += `AND ( d.seller_id IN ? AND a.payment_id <> 0 ) `
  1102. amountPars = append(amountPars, sellerIds)
  1103. } else {
  1104. amountCond += `AND (a.payment_id <> 0)`
  1105. }
  1106. page := new(base.Page)
  1107. page.SetPageSize(req.PageSize)
  1108. page.SetCurrent(req.Current)
  1109. if req.IsExport == 1 {
  1110. page.SetPageSize(10000)
  1111. page.SetCurrent(1)
  1112. }
  1113. if req.SortType == "asc" {
  1114. page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: true})
  1115. } else {
  1116. page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: false})
  1117. }
  1118. results, total, e := fms.GetContractSummaryPaymentIncomeAmountPage(amountCond, amountPars, page)
  1119. if e != nil {
  1120. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1121. return
  1122. }
  1123. // 货币列表
  1124. currencyOB := new(fms.CurrencyUnit)
  1125. currencyCond := `enable = 1`
  1126. currencyPars := make([]interface{}, 0)
  1127. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1128. if e != nil {
  1129. err = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  1130. return
  1131. }
  1132. unitMap := make(map[string]string)
  1133. for i := range currencyList {
  1134. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1135. }
  1136. respItems := make([]*fms.IncomeSummaryRespItem, 0)
  1137. for _, v := range results {
  1138. respItem := &fms.IncomeSummaryRespItem{
  1139. CompanyName: v.CompanyName,
  1140. ContractType: v.ContractType,
  1141. InvoiceDate: v.InvoiceDate.Format(utils.FormatDate),
  1142. Amount: v.Amount,
  1143. SellerName: v.SellerName,
  1144. FinalSellerId: v.FinalSellerId,
  1145. OriginAmount: v.OriginAmount,
  1146. UnitName: unitMap[v.CurrencyUnit],
  1147. ServicesName: v.ServicesName,
  1148. }
  1149. respItems = append(respItems, respItem)
  1150. }
  1151. page.SetTotal(total)
  1152. baseData.SetPage(page)
  1153. baseData.SetList(respItems)
  1154. }
  1155. }
  1156. return
  1157. }
  1158. func getCensusIncomeList(ch chan base.BaseData, req fms.IncomeListReq) (baseData base.BaseData, err error) {
  1159. defer func() {
  1160. if err != nil {
  1161. global.LOG.Error(err)
  1162. if err != utils.ErrNoRow {
  1163. go alarm_msg.SendAlarmMsg("获取业务收入金额统计数据异常,Err:"+err.Error(), 3)
  1164. }
  1165. }
  1166. ch <- baseData
  1167. }()
  1168. var reqStartDate, reqEndDate time.Time
  1169. historyTime, _ := time.Parse(utils.FormatDate, "2023-04-01")
  1170. // 套餐筛选
  1171. if req.ServiceTypes != "" {
  1172. // 勾选套餐筛选时忽略导入的历史数据
  1173. if req.StartDate == "" {
  1174. req.StartDate = "2023-04"
  1175. req.EndDate = "3023-04"
  1176. } else {
  1177. startDateTime, _ := time.Parse(utils.FormatMonth, req.StartDate)
  1178. if startDateTime.Before(historyTime) {
  1179. req.StartDate = "2023-04"
  1180. }
  1181. }
  1182. }
  1183. if req.StartDate != "" && req.EndDate != "" {
  1184. st := fmt.Sprint(req.StartDate, "-01 00:00:00")
  1185. ed := fmt.Sprint(req.EndDate, "-01 23:59:59")
  1186. reqStartDate, _ = time.Parse(utils.FormatDateTime, st)
  1187. reqEndDate, _ = time.Parse(utils.FormatDateTime, ed)
  1188. }
  1189. //timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
  1190. var startDate, endDate string
  1191. //开始日期
  1192. if req.StartDate != "" && req.EndDate != "" {
  1193. startDate = reqStartDate.Format("2006-01")
  1194. startDate = fmt.Sprint(startDate, "-01")
  1195. }
  1196. startDateTime, _ := time.Parse(utils.FormatDate, startDate)
  1197. //结束日期
  1198. if req.StartDate != "" && req.EndDate != "" {
  1199. endDate = reqEndDate.Format(utils.FormatDate)
  1200. }
  1201. cond := `1 = 1`
  1202. histrtyCond := `1 = 1`
  1203. pars := make([]interface{}, 0)
  1204. historyPars := make([]interface{}, 0)
  1205. if req.CompanyType == 1 {
  1206. cond += ` AND b.contract_type = 1 `
  1207. histrtyCond += ` AND new_company = 1 `
  1208. } else if req.CompanyType == 2 {
  1209. cond += ` AND b.contract_type IN (2,3,4) `
  1210. histrtyCond += ` AND new_company = 0 `
  1211. } else if req.CompanyType == 3 {
  1212. //未续约收入金额=去年同期总收入金额(新客户+老客户)-当期老客户收入金额
  1213. cond += ` AND b.contract_type IN (2,3,4) `
  1214. histrtyCond += ` AND new_company = 0 `
  1215. }
  1216. if req.SellerIds != "" {
  1217. sellerIds := strings.Split(req.SellerIds, ",")
  1218. cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  1219. pars = append(pars, sellerIds, sellerIds)
  1220. histrtyCond += ` AND seller_id in ? `
  1221. historyPars = append(historyPars, sellerIds)
  1222. }
  1223. // 套餐筛选
  1224. if req.ServiceTypes != "" {
  1225. serviceTypes := strings.Split(req.ServiceTypes, ",")
  1226. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  1227. if e != nil {
  1228. err = fmt.Errorf("获取合同登记IDs失败, Err: %s", e.Error())
  1229. return
  1230. }
  1231. if len(registerIds) > 0 {
  1232. cond += ` AND a.register_id IN ?`
  1233. pars = append(pars, registerIds)
  1234. } else {
  1235. cond += ` AND 1 = 2`
  1236. }
  1237. }
  1238. {
  1239. page := new(base.Page)
  1240. page.SetPageSize(req.PageSize)
  1241. page.SetCurrent(req.Current)
  1242. if req.IsExport == 1 {
  1243. page.SetPageSize(10000)
  1244. page.SetCurrent(1)
  1245. }
  1246. //校验日期,分段查询
  1247. st := fmt.Sprint(startDate, " 00:00:00")
  1248. ed := fmt.Sprint(endDate, " 23:59:59")
  1249. if req.StartDate != "" && req.EndDate != "" {
  1250. if reqEndDate.Before(historyTime) || reqEndDate.Equal(historyTime) {
  1251. //旧查询
  1252. histrtyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1253. historyPars = append(historyPars, st, ed)
  1254. if req.SortType == "asc" {
  1255. page.AddOrderItem(base.OrderItem{Column: "invoice_time", Asc: true})
  1256. } else {
  1257. page.AddOrderItem(base.OrderItem{Column: "invoice_time", Asc: false})
  1258. }
  1259. results, total, e := fms.GetIncomeHistoryPage(histrtyCond, historyPars, page)
  1260. if e != nil {
  1261. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1262. return
  1263. }
  1264. // 货币列表
  1265. currencyOB := new(fms.CurrencyUnit)
  1266. currencyCond := `enable = 1`
  1267. currencyPars := make([]interface{}, 0)
  1268. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1269. if e != nil {
  1270. err = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  1271. return
  1272. }
  1273. unitMap := make(map[string]string)
  1274. for i := range currencyList {
  1275. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1276. }
  1277. respItems := make([]*fms.IncomeSummaryRespItem, 0)
  1278. for _, v := range results {
  1279. respItem := &fms.IncomeSummaryRespItem{
  1280. CompanyName: v.CompanyName,
  1281. ContractType: v.ContractType,
  1282. InvoiceDate: v.InvoiceDate.Format(utils.FormatDate),
  1283. Amount: v.Amount,
  1284. SellerName: v.SellerName,
  1285. FinalSellerId: v.FinalSellerId,
  1286. OriginAmount: v.OriginAmount,
  1287. UnitName: unitMap[v.CurrencyUnit],
  1288. ServicesName: v.ServicesName,
  1289. }
  1290. respItems = append(respItems, respItem)
  1291. }
  1292. page.SetTotal(total)
  1293. baseData.SetPage(page)
  1294. baseData.SetList(respItems)
  1295. return
  1296. } else if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
  1297. //全部走新查询
  1298. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1299. pars = append(pars, st, ed, st, ed)
  1300. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1301. if e != nil {
  1302. return
  1303. }
  1304. if len(summaryIds) > 0 {
  1305. amountCond := `a.id IN ? `
  1306. amountPars := make([]interface{}, 0)
  1307. amountPars = append(amountPars, summaryIds)
  1308. if req.SellerIds != "" {
  1309. sellerIds := strings.Split(req.SellerIds, ",")
  1310. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1311. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1312. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  1313. } else {
  1314. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1315. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)`
  1316. amountPars = append(amountPars, st, ed, st, ed)
  1317. }
  1318. if req.SortType == "asc" {
  1319. page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: true})
  1320. } else {
  1321. page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: false})
  1322. }
  1323. results, total, e := fms.GetContractSummaryPaymentIncomeAmountPage(amountCond, amountPars, page)
  1324. if e != nil {
  1325. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1326. return
  1327. }
  1328. // 货币列表
  1329. currencyOB := new(fms.CurrencyUnit)
  1330. currencyCond := `enable = 1`
  1331. currencyPars := make([]interface{}, 0)
  1332. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1333. if e != nil {
  1334. err = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  1335. return
  1336. }
  1337. unitMap := make(map[string]string)
  1338. for i := range currencyList {
  1339. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1340. }
  1341. respItems := make([]*fms.IncomeSummaryRespItem, 0)
  1342. for _, v := range results {
  1343. respItem := &fms.IncomeSummaryRespItem{
  1344. CompanyName: v.CompanyName,
  1345. ContractType: v.ContractType,
  1346. InvoiceDate: v.InvoiceDate.Format(utils.FormatDate),
  1347. Amount: v.Amount,
  1348. SellerName: v.SellerName,
  1349. FinalSellerId: v.FinalSellerId,
  1350. OriginAmount: v.OriginAmount,
  1351. UnitName: unitMap[v.CurrencyUnit],
  1352. ServicesName: v.ServicesName,
  1353. }
  1354. respItems = append(respItems, respItem)
  1355. }
  1356. page.SetTotal(total)
  1357. baseData.SetPage(page)
  1358. baseData.SetList(respItems[:])
  1359. return
  1360. }
  1361. } else {
  1362. resultList := make([]*fms.IncomeSummaryItem, 0)
  1363. //旧查询
  1364. histrtyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1365. historyPars = append(historyPars, st, ed)
  1366. results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
  1367. if e != nil {
  1368. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1369. return
  1370. }
  1371. resultList = append(resultList, results...)
  1372. //新查询
  1373. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1374. pars = append(pars, "2023-04-01 00:00:00", ed, "2023-04-01 00:00:00", ed)
  1375. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1376. if e != nil {
  1377. return
  1378. }
  1379. if len(summaryIds) > 0 {
  1380. amountCond := `a.id IN ? `
  1381. amountPars := make([]interface{}, 0)
  1382. amountPars = append(amountPars, summaryIds)
  1383. if req.SellerIds != "" {
  1384. sellerIds := strings.Split(req.SellerIds, ",")
  1385. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1386. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1387. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  1388. } else {
  1389. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1390. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)`
  1391. amountPars = append(amountPars, st, ed, st, ed)
  1392. }
  1393. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1394. if e != nil {
  1395. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1396. return
  1397. }
  1398. resultList = append(resultList, results...)
  1399. }
  1400. // 货币列表
  1401. currencyOB := new(fms.CurrencyUnit)
  1402. currencyCond := `enable = 1`
  1403. currencyPars := make([]interface{}, 0)
  1404. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1405. if e != nil {
  1406. err = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  1407. return
  1408. }
  1409. unitMap := make(map[string]string)
  1410. for i := range currencyList {
  1411. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1412. }
  1413. respItems := make([]*fms.IncomeSummaryRespItem, 0)
  1414. for _, v := range resultList {
  1415. respItem := &fms.IncomeSummaryRespItem{
  1416. CompanyName: v.CompanyName,
  1417. ContractType: v.ContractType,
  1418. InvoiceDate: v.InvoiceDate.Format(utils.FormatDate),
  1419. Amount: v.Amount,
  1420. SellerName: v.SellerName,
  1421. FinalSellerId: v.FinalSellerId,
  1422. OriginAmount: v.OriginAmount,
  1423. UnitName: unitMap[v.CurrencyUnit],
  1424. ServicesName: v.ServicesName,
  1425. }
  1426. respItems = append(respItems, respItem)
  1427. }
  1428. page.SetTotal(int64(len(respItems)))
  1429. baseData.SetPage(page)
  1430. start := (page.GetCurrent() - 1) * page.PageSize
  1431. end := start + page.PageSize
  1432. if end > int64(len(respItems)) {
  1433. end = int64(len(respItems))
  1434. }
  1435. baseData.SetList(respItems[start:end])
  1436. }
  1437. } else {
  1438. resultList := make(fms.IncomeSummaryItemList, 0)
  1439. //旧查询
  1440. results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
  1441. if e != nil {
  1442. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1443. return
  1444. }
  1445. resultList = append(resultList, results...)
  1446. //新查询
  1447. st = "2023-04-01 00:00:00"
  1448. cond += ` AND ((c.invoice_time > ?) or (d.invoice_time > ?))`
  1449. pars = append(pars, st, st)
  1450. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1451. if e != nil {
  1452. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1453. return
  1454. }
  1455. if len(summaryIds) > 0 {
  1456. amountCond := `a.id IN ? `
  1457. amountPars := make([]interface{}, 0)
  1458. amountPars = append(amountPars, summaryIds)
  1459. if req.SellerIds != "" {
  1460. sellerIds := strings.Split(req.SellerIds, ",")
  1461. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time > ?)`
  1462. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time > ? )) `
  1463. amountPars = append(amountPars, sellerIds, st, sellerIds, st)
  1464. } else {
  1465. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time > ?)`
  1466. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time > ?))`
  1467. amountPars = append(amountPars, st, st)
  1468. }
  1469. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1470. if e != nil {
  1471. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1472. return
  1473. }
  1474. resultList = append(resultList, results...)
  1475. }
  1476. sort.Sort(resultList)
  1477. // 货币列表
  1478. currencyOB := new(fms.CurrencyUnit)
  1479. currencyCond := `enable = 1`
  1480. currencyPars := make([]interface{}, 0)
  1481. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1482. if e != nil {
  1483. err = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  1484. return
  1485. }
  1486. unitMap := make(map[string]string)
  1487. for i := range currencyList {
  1488. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1489. }
  1490. respItems := make([]*fms.IncomeSummaryRespItem, 0)
  1491. for _, v := range resultList {
  1492. respItem := &fms.IncomeSummaryRespItem{
  1493. CompanyName: v.CompanyName,
  1494. ContractType: v.ContractType,
  1495. InvoiceDate: v.InvoiceDate.Format(utils.FormatDate),
  1496. Amount: v.Amount,
  1497. SellerName: v.SellerName,
  1498. FinalSellerId: v.FinalSellerId,
  1499. OriginAmount: v.OriginAmount,
  1500. UnitName: unitMap[v.CurrencyUnit],
  1501. ServicesName: v.ServicesName,
  1502. }
  1503. respItems = append(respItems, respItem)
  1504. }
  1505. page.SetTotal(int64(len(respItems)))
  1506. baseData.SetPage(page)
  1507. start := (page.GetCurrent() - 1) * page.PageSize
  1508. end := start + page.PageSize
  1509. if end > int64(len(respItems)) {
  1510. end = int64(len(respItems))
  1511. }
  1512. baseData.SetList(respItems[start:end])
  1513. }
  1514. }
  1515. return
  1516. }
  1517. // ExportIncomeList 导出业务收入统计列表
  1518. func ExportIncomeList(c *gin.Context, results interface{}, incomeType int) {
  1519. list := results.([]*fms.IncomeSummaryRespItem)
  1520. // 生成Excel文件
  1521. xlsxFile := xlsx.NewFile()
  1522. style := xlsx.NewStyle()
  1523. alignment := xlsx.Alignment{
  1524. Horizontal: "center",
  1525. Vertical: "center",
  1526. WrapText: true,
  1527. }
  1528. style.Alignment = alignment
  1529. style.ApplyAlignment = true
  1530. sheetName := "业务收入统计表"
  1531. sheet, err := xlsxFile.AddSheet(sheetName)
  1532. if err != nil {
  1533. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1534. return
  1535. }
  1536. // 数据表头
  1537. rowTitle := make([]string, 0)
  1538. if incomeType == 0 {
  1539. rowTitle = []string{"客户名称", "新客户(1)", "开票日期", "开票金额", "金额单位", "开票金额(换算后)", "销售名称", "套餐名称"}
  1540. } else {
  1541. rowTitle = []string{"客户名称", "新客户(1)", "到款日期", "到款金额", "金额单位", "到款金额(换算后)", "销售名称", "套餐名称"}
  1542. }
  1543. titleRow := sheet.AddRow()
  1544. for i := range rowTitle {
  1545. v := titleRow.AddCell()
  1546. v.SetString(rowTitle[i])
  1547. v.SetStyle(style)
  1548. }
  1549. incomeSummaryItemList := make([]*fms.IncomeSummaryRespItem, 0)
  1550. incomeSummaryItemList = list
  1551. //sort.Sort(incomeSummaryItemList)
  1552. // 填充数据
  1553. for _, v := range incomeSummaryItemList {
  1554. dataRow := sheet.AddRow()
  1555. dataRow.AddCell().SetString(v.CompanyName) // 客户名称
  1556. newCompany := 0
  1557. if v.ContractType == 1 {
  1558. newCompany = 1
  1559. }
  1560. dataRow.AddCell().SetString(strconv.Itoa(newCompany)) // 新客户
  1561. dataRow.AddCell().SetString(v.InvoiceDate) // 开票到款日期
  1562. dataRow.AddCell().SetString(fmt.Sprintf("%.2f", v.OriginAmount)) // 开票到款金额
  1563. dataRow.AddCell().SetString(v.UnitName) // 金额单位
  1564. dataRow.AddCell().SetString(fmt.Sprintf("%.2f", v.Amount)) // 开票到款金额 换算后
  1565. dataRow.AddCell().SetString(v.SellerName) // 销售员
  1566. dataRow.AddCell().SetString(v.ServicesName) // 套餐名称
  1567. }
  1568. // 输出文件
  1569. var buffer bytes.Buffer
  1570. _ = xlsxFile.Write(&buffer)
  1571. content := bytes.NewReader(buffer.Bytes())
  1572. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1573. fileName := sheetName + randStr + ".xlsx"
  1574. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1575. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1576. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1577. }