income_list.go 61 KB

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