income_list.go 60 KB

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