invoice_payment.go 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638
  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/crm"
  13. "hongze/fms_api/models/fms"
  14. "hongze/fms_api/services/alarm_msg"
  15. crmService "hongze/fms_api/services/crm"
  16. fmsService "hongze/fms_api/services/fms"
  17. "hongze/fms_api/utils"
  18. "net/http"
  19. "sort"
  20. "strconv"
  21. "strings"
  22. "sync"
  23. "time"
  24. )
  25. // InvoicePaymentController 商品到款统计
  26. type InvoicePaymentController struct{}
  27. // ExportInvoicePaymentCensusList 导出商品到款统计列表
  28. func ExportInvoicePaymentCensusList(c *gin.Context, results *fms.InvoicePaymentCensusResp) {
  29. list := results.DataList
  30. if len(list) == 0 {
  31. resp.Fail("列表数据为空", c)
  32. return
  33. }
  34. // 生成Excel文件
  35. xlsxFile := xlsx.NewFile()
  36. style := xlsx.NewStyle()
  37. alignment := xlsx.Alignment{
  38. Horizontal: "center",
  39. Vertical: "center",
  40. WrapText: true,
  41. }
  42. style.Alignment = alignment
  43. style.ApplyAlignment = true
  44. sheet, err := xlsxFile.AddSheet("商品到款统计")
  45. if err != nil {
  46. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  47. return
  48. }
  49. _ = sheet.SetColWidth(1, 1, 30)
  50. _ = sheet.SetColWidth(3, 3, 30)
  51. // 前三行-开票金额合计
  52. rowA := sheet.AddRow()
  53. cellAA := rowA.AddCell()
  54. cellAA.SetString(fmt.Sprintf("已开票合计金额(换算后):%.2f(元)", results.InvoiceTotal))
  55. rowBData := "已开票金额:"
  56. for _, v := range results.InvoiceCurrencyTotal {
  57. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  58. }
  59. rowB := sheet.AddRow()
  60. rowB.AddCell().SetString(rowBData)
  61. sheet.AddRow()
  62. // 四至六-到款金额合计
  63. rowD := sheet.AddRow()
  64. cellDA := rowD.AddCell()
  65. cellDA.SetString(fmt.Sprintf("已到款合计金额(换算后):%.2f(元)", results.PaymentTotal))
  66. rowEData := "已到款金额:"
  67. for _, v := range results.PaymentCurrencyTotal {
  68. rowEData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  69. }
  70. rowE := sheet.AddRow()
  71. rowE.AddCell().SetString(rowEData)
  72. sheet.AddRow()
  73. // 表头, 套餐动态获取
  74. rowTitle := []string{"序号", "客户名称", "代付方", "是否新客户", "合同起始日期", "合同结束日期", "开票日", "开票金额", "开票换算金额(元)", "到款日", "到款金额", "到款换算金额(元)", "付款方式", "销售",
  75. "销售组别", "销售类型"}
  76. serviceTempCond := ``
  77. serviceTempPars := make([]interface{}, 0)
  78. serviceTempOB := new(fms.ContractServiceTemplate)
  79. serviceTempList, e := serviceTempOB.OrderList(serviceTempCond, serviceTempPars)
  80. if e != nil {
  81. resp.FailData("获取套餐模板列表失败", "Err:"+e.Error(), c)
  82. return
  83. }
  84. serviceTempListMap := make(map[int]*fms.ContractServiceTemplate)
  85. var serviceTempShow []*fms.ContractServiceTemplate
  86. for i := range serviceTempList {
  87. serviceTempListMap[serviceTempList[i].ServiceTemplateId] = serviceTempList[i]
  88. }
  89. for i := range serviceTempList {
  90. if serviceTempList[i].ProductId == 1 {
  91. rowTitle = append(rowTitle, serviceTempList[i].Title)
  92. serviceTempShow = append(serviceTempShow, serviceTempList[i])
  93. } else if serviceTempList[i].ProductId == 2 {
  94. if serviceTempList[i].Title == "行业套餐" || serviceTempList[i].Title == "权益大套餐" || (serviceTempList[i].Title == "策略" && serviceTempListMap[serviceTempList[i].Pid].Pid == 0) {
  95. } else if serviceTempList[i].Title == "医药" || serviceTempList[i].Title == "消费" || serviceTempList[i].Title == "科技" || serviceTempList[i].Title == "智造" {
  96. } else {
  97. serviceTempShow = append(serviceTempShow, serviceTempList[i])
  98. }
  99. if serviceTempList[i].Title == "行业套餐" || serviceTempList[i].Title == "45万" || serviceTempList[i].Title == "70万" {
  100. continue
  101. }
  102. if serviceTempList[i].Pid > 0 && serviceTempListMap[serviceTempList[i].Pid].Pid > 0 {
  103. continue
  104. }
  105. rowTitle = append(rowTitle, serviceTempList[i].Title)
  106. }
  107. }
  108. hi := 0
  109. insertHi := 0
  110. titleRow := sheet.AddRow()
  111. for i := range rowTitle {
  112. v := titleRow.AddCell()
  113. v.SetString(rowTitle[i])
  114. v.SetStyle(style)
  115. if rowTitle[i] != "权益大套餐" && rowTitle[i] != "医药" && rowTitle[i] != "消费" && rowTitle[i] != "科技" && rowTitle[i] != "智造" {
  116. v.VMerge = 1
  117. hi++
  118. } else {
  119. if insertHi == 0 {
  120. insertHi = hi
  121. }
  122. v.HMerge = 1
  123. titleRow.AddCell().SetString("")
  124. }
  125. }
  126. // 新增一行放主观和客观
  127. specialRow := sheet.AddRow()
  128. for i := 0; i < hi; i++ {
  129. if i == insertHi {
  130. v1 := specialRow.AddCell()
  131. v1.SetString("45万")
  132. v1.SetStyle(style)
  133. v1 = specialRow.AddCell()
  134. v1.SetString("70万")
  135. v1.SetStyle(style)
  136. for j := 0; j < 8; j++ {
  137. if j%2 == 0 {
  138. v1 = specialRow.AddCell()
  139. v1.SetString("主观")
  140. v1.SetStyle(style)
  141. } else {
  142. v1 = specialRow.AddCell()
  143. v1.SetString("客观")
  144. v1.SetStyle(style)
  145. }
  146. }
  147. } else {
  148. v := specialRow.AddCell()
  149. v.SetString("")
  150. }
  151. }
  152. newCompanyMap := map[int]string{0: "/", 1: "是", 2: "否", 3: "否", 4: "否"}
  153. for k, v := range list {
  154. dataRow := sheet.AddRow()
  155. // 前四个单元格根据每行开票到款条数向下合并
  156. l := len(v.InvoicePaymentList)
  157. mergeRowNum := l - 1
  158. // 序号
  159. sortNum := k + 1
  160. colA := dataRow.AddCell()
  161. colA.VMerge = mergeRowNum
  162. colA.SetString(fmt.Sprint(sortNum))
  163. // 客户名称
  164. colB := dataRow.AddCell()
  165. colB.VMerge = mergeRowNum
  166. colB.SetString(v.CompanyName)
  167. // 代付方
  168. colE := dataRow.AddCell()
  169. colE.VMerge = mergeRowNum
  170. colE.SetString(v.ActualPayCompanies)
  171. // 是否新客户
  172. colC := dataRow.AddCell()
  173. colC.VMerge = mergeRowNum
  174. colC.SetString(newCompanyMap[v.ContractType])
  175. // 合同有效期
  176. colD := dataRow.AddCell()
  177. colD.VMerge = mergeRowNum
  178. colD.SetString(v.StartDate)
  179. colF := dataRow.AddCell()
  180. colF.VMerge = mergeRowNum
  181. colF.SetString(v.EndDate)
  182. // 开票到款信息
  183. for k2, v2 := range v.InvoicePaymentList {
  184. rowData := []string{
  185. v2.InvoiceDate, // 开票日
  186. fmt.Sprint(v2.InvoiceOriginAmount), // 开票金额
  187. fmt.Sprint(v2.InvoiceAmount), // 开票换算金额
  188. v2.PaymentDate, // 到款日
  189. fmt.Sprint(v2.PaymentOriginAmount), // 到款金额
  190. fmt.Sprint(v2.PaymentAmount), // 到款换算金额
  191. fms.ContractPaymentPayTypeNameMap[v2.PayType], // 付款方式
  192. v2.SellerName, // 销售
  193. v2.SellerGroupName, // 组别
  194. v2.SellerType, // 销售类型
  195. }
  196. // 套餐金额信息
  197. serviceTempShowAmount := make(map[int]string)
  198. for i := range serviceTempShow {
  199. for s2 := range v2.ServiceAmountList {
  200. item := v2.ServiceAmountList[s2]
  201. if item.ServiceTemplateId == serviceTempShow[i].ServiceTemplateId {
  202. serviceTempShowAmount[serviceTempShow[i].ServiceTemplateId] = fmt.Sprint(item.Amount)
  203. break
  204. } else if serviceTempShow[i].Pid == item.ServiceTemplateId {
  205. serviceTempShowAmount[serviceTempShow[i].ServiceTemplateId] = fmt.Sprint(item.Amount / 2)
  206. break
  207. }
  208. }
  209. }
  210. for i := range serviceTempShow {
  211. sa := ""
  212. if am, ok := serviceTempShowAmount[serviceTempShow[i].ServiceTemplateId]; ok {
  213. sa = am
  214. }
  215. rowData = append(rowData, sa)
  216. }
  217. // 首行开票到款
  218. if k2 == 0 {
  219. for i := range rowData {
  220. dataRow.AddCell().SetString(rowData[i])
  221. }
  222. continue
  223. }
  224. // 其他行开票到款, 加四列空的单元格用于合并
  225. dataRowExtra := sheet.AddRow()
  226. for i := 0; i < 4; i++ {
  227. dataRowExtra.AddCell()
  228. }
  229. for i := range rowData {
  230. dataRowExtra.AddCell().SetString(rowData[i])
  231. }
  232. }
  233. }
  234. // 输出文件
  235. var buffer bytes.Buffer
  236. _ = xlsxFile.Write(&buffer)
  237. content := bytes.NewReader(buffer.Bytes())
  238. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  239. fileName := "商品到款统计_" + randStr + ".xlsx"
  240. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  241. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  242. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  243. }
  244. // List
  245. // @Title 商品到款统计列表
  246. // @Description 商品到款统计列表
  247. // @Param Keyword query string false "关键词"
  248. // @Param SellGroupId query int false "销售组别ID"
  249. // @Param ServiceType query int false "套餐类型"
  250. // @Param StartDate query string false "合同开始日期"
  251. // @Param EndDate query string false "合同结束日期"
  252. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  253. // @Param HasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
  254. // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
  255. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  256. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  257. // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'invoice_time':开票日 、 'payment_date':到款日"
  258. // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
  259. // @Success 200 {object} fms.ContractRegisterItem
  260. // @router /census/invoice_payment/list [get]
  261. func (ct *InvoicePaymentController) List(c *gin.Context) {
  262. var req fms.InvoicePaymentCensusListReq
  263. if e := c.BindQuery(&req); e != nil {
  264. err, ok := e.(validator.ValidationErrors)
  265. if !ok {
  266. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  267. return
  268. }
  269. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  270. return
  271. }
  272. cond := `1 = 1`
  273. pars := make([]interface{}, 0)
  274. // 客户姓名/销售
  275. if req.Keyword != "" {
  276. kw := "%" + req.Keyword + "%"
  277. cond += ` AND (b.company_name LIKE ? OR b.actual_pay_companies LIKE ? )`
  278. pars = append(pars, kw, kw)
  279. }
  280. if req.SellerIds != "" {
  281. sellerIds := strings.Split(req.SellerIds, ",")
  282. cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  283. pars = append(pars, sellerIds, sellerIds)
  284. }
  285. // 套餐筛选
  286. if req.ServiceTypes != "" {
  287. serviceTypes := strings.Split(req.ServiceTypes, ",")
  288. tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  289. if e != nil {
  290. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  291. return
  292. }
  293. if len(tempRegisterIds) > 0 {
  294. cond += ` AND a.register_id IN ?`
  295. pars = append(pars, tempRegisterIds)
  296. } else {
  297. cond += ` AND 1 = 2`
  298. }
  299. }
  300. if req.ListParam == 1 {
  301. cond += ` AND a.service_product_id = 1 `
  302. } else if req.ListParam == 2 {
  303. cond += ` AND a.service_product_id = 2 `
  304. }
  305. // 开票到款日期
  306. if req.TimeType != 0 {
  307. if req.TimeType == 1 && req.StartDate != "" && req.EndDate != "" {
  308. st := fmt.Sprint(req.StartDate, " 00:00:00")
  309. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  310. cond += ` AND (c.invoice_time BETWEEN ? AND ?) `
  311. pars = append(pars, st, ed)
  312. } else if req.TimeType == 2 && req.StartDate != "" && req.EndDate != "" {
  313. st := fmt.Sprint(req.StartDate, " 00:00:00")
  314. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  315. cond += ` AND (d.invoice_time BETWEEN ? AND ?) `
  316. pars = append(pars, st, ed)
  317. } else if req.TimeType == 3 && req.StartDate != "" && req.EndDate != "" {
  318. st := fmt.Sprint(req.StartDate, " 00:00:00")
  319. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  320. cond += ` AND (c.invoice_time BETWEEN ? AND ?) AND (d.invoice_time BETWEEN ? AND ?) `
  321. pars = append(pars, st, ed, st, ed)
  322. }
  323. } else if req.StartDate != "" && req.EndDate != "" {
  324. st := fmt.Sprint(req.StartDate, " 00:00:00")
  325. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  326. if req.SellerIds != "" {
  327. sellerIds := strings.Split(req.SellerIds, ",")
  328. cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  329. pars = append(pars, sellerIds, sellerIds)
  330. cond += ` AND ((c.seller_id in ? AND a.invoice_id <> 0 AND c.invoice_time BETWEEN ? AND ?)`
  331. cond += `OR (d.seller_id in ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  332. pars = append(pars, sellerIds, st, ed, sellerIds, st, ed)
  333. } else {
  334. cond += ` AND ((a.invoice_id <> 0 AND c.invoice_time BETWEEN ? AND ?)`
  335. cond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  336. pars = append(pars, st, ed, st, ed)
  337. }
  338. }
  339. if req.HasInvoice == "1" {
  340. cond += ` AND a.invoice_id > 0 `
  341. } else if req.HasInvoice == "0" {
  342. cond += ` AND a.invoice_id = 0 `
  343. }
  344. if req.HasPayment == "1" {
  345. cond += ` AND a.payment_id > 0 `
  346. } else if req.HasPayment == "0" {
  347. cond += ` AND a.payment_id = 0 `
  348. }
  349. page := new(base.Page)
  350. page.SetPageSize(req.PageSize)
  351. page.SetCurrent(req.Current)
  352. //排序
  353. if req.SortType == "" {
  354. req.SortType = "desc"
  355. }
  356. if req.SortType != "desc" && req.SortType != "asc" {
  357. resp.Fail("排序类型不正确", c)
  358. return
  359. }
  360. if req.SortParam == "" {
  361. page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: true})
  362. page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: false})
  363. page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: false})
  364. page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: false})
  365. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  366. } else if req.SortParam == "invoice_time" {
  367. if req.SortType == "asc" {
  368. page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: false})
  369. page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: true})
  370. page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: true})
  371. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: true})
  372. } else {
  373. page.AddOrderItem(base.OrderItem{Column: "sort_invoice_id", Asc: true})
  374. page.AddOrderItem(base.OrderItem{Column: "c.invoice_time", Asc: false})
  375. page.AddOrderItem(base.OrderItem{Column: "c.amount", Asc: false})
  376. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  377. }
  378. } else if req.SortParam == "payment_date" {
  379. if req.SortType == "asc" {
  380. page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: false})
  381. page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: true})
  382. page.AddOrderItem(base.OrderItem{Column: "d.amount", Asc: true})
  383. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: true})
  384. } else {
  385. page.AddOrderItem(base.OrderItem{Column: "sort_payment_id", Asc: true})
  386. page.AddOrderItem(base.OrderItem{Column: "d.invoice_time", Asc: false})
  387. page.AddOrderItem(base.OrderItem{Column: "d.amount", Asc: false})
  388. page.AddOrderItem(base.OrderItem{Column: "a.create_time", Asc: false})
  389. }
  390. } else {
  391. resp.Fail("排序字段不正确", c)
  392. return
  393. }
  394. if req.IsExport == 1 {
  395. page.SetPageSize(10000)
  396. page.SetCurrent(1)
  397. }
  398. registerList, total, e := fms.GetInvoicePaymentCensusPageList(page, cond, pars)
  399. if e != nil {
  400. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  401. return
  402. }
  403. queryRegisterIds := make([]int, 0)
  404. for i := range registerList {
  405. queryRegisterIds = append(queryRegisterIds, registerList[i].ContractRegisterId)
  406. }
  407. //fmt.Println("queryRegisterIds:",queryRegisterIds)
  408. results := new(fms.InvoicePaymentCensusResp)
  409. if len(queryRegisterIds) > 0 {
  410. // 获取汇总数据IDs, 用于查询合计数据
  411. summaryIdsCond := cond
  412. summaryIdsPars := pars
  413. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(summaryIdsCond, summaryIdsPars)
  414. if e != nil {
  415. resp.FailMsg("获取失败", "获取商品到款汇总IDs失败, Err: "+e.Error(), c)
  416. return
  417. }
  418. //fmt.Println("summaryIds:",summaryIds)
  419. var listErr, totalErr, totalGroupErr error
  420. wg := sync.WaitGroup{}
  421. // 响应列表
  422. respList := make([]*fms.InvoicePaymentCensusItem, 0)
  423. summaryList := make([]*fms.InvoicePaymentSummaryItem, 0)
  424. wg.Add(1)
  425. go func() {
  426. defer wg.Done()
  427. // 获取汇总数据
  428. summaryCond := cond
  429. summaryCond += ` AND a.register_id IN ?`
  430. summaryPars := pars
  431. summaryPars = append(summaryPars, queryRegisterIds)
  432. summaryData, e := fms.GetInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  433. if e != nil {
  434. resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
  435. return
  436. }
  437. summaryList = summaryData
  438. //summaryIds := make([]int, 0)
  439. paymentIds := make([]int, 0)
  440. for i := range summaryList {
  441. //summaryIds = append(summaryIds, summaryList[i].SummaryId)
  442. if summaryList[i].PaymentId > 0 {
  443. paymentIds = append(paymentIds, summaryList[i].PaymentId)
  444. }
  445. }
  446. // 合同套餐
  447. /*contractServiceCond := `contract_register_id IN ?`
  448. contractServicePars := make([]interface{}, 0)
  449. contractServicePars = append(contractServicePars, queryRegisterIds)
  450. contractServiceOB := new(fms.ContractService)
  451. contractServiceList, e := contractServiceOB.List(contractServiceCond, contractServicePars)
  452. if e != nil {
  453. listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
  454. return
  455. }
  456. contractServiceMap := make(map[int][]*fms.ContractService, 0)
  457. servicesNameMap := make(map[int][]string, 0)
  458. for i := range contractServiceList {
  459. if contractServiceMap[contractServiceList[i].ContractRegisterId] == nil {
  460. contractServiceMap[contractServiceList[i].ContractRegisterId] = make([]*fms.ContractService, 0)
  461. }
  462. contractServiceMap[contractServiceList[i].ContractRegisterId] = append(contractServiceMap[contractServiceList[i].ContractRegisterId], contractServiceList[i])
  463. servicesNameMap[contractServiceList[i].ContractRegisterId] = append(servicesNameMap[contractServiceList[i].ContractRegisterId], contractServiceList[i].Title)
  464. }
  465. */
  466. servicesNameMap, serviceFormatMap, e := fmsService.GetContractServiceNameFormat(queryRegisterIds)
  467. if e != nil {
  468. listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
  469. return
  470. }
  471. // 到款套餐分配
  472. serviceAmountMap := make(map[int][]*fms.ContractPaymentServiceAmount, 0)
  473. if len(paymentIds) > 0 {
  474. serviceAmountCond := `contract_payment_id IN ?`
  475. serviceAmountPars := make([]interface{}, 0)
  476. serviceAmountPars = append(serviceAmountPars, paymentIds)
  477. serviceAmountOB := new(fms.ContractPaymentServiceAmount)
  478. serviceAmountList, e := serviceAmountOB.List(serviceAmountCond, serviceAmountPars)
  479. if e != nil {
  480. listErr = fmt.Errorf("获取到款套餐分配列表失败, Err: %s", e.Error())
  481. return
  482. }
  483. for i := range serviceAmountList {
  484. if serviceAmountMap[serviceAmountList[i].ContractPaymentId] == nil {
  485. serviceAmountMap[serviceAmountList[i].ContractPaymentId] = make([]*fms.ContractPaymentServiceAmount, 0)
  486. }
  487. serviceAmountMap[serviceAmountList[i].ContractPaymentId] = append(serviceAmountMap[serviceAmountList[i].ContractPaymentId], serviceAmountList[i])
  488. }
  489. }
  490. sellerTypeMap := map[int]string{2: "FICC销售", 5: "权益销售"}
  491. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  492. if e != nil {
  493. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  494. return
  495. }
  496. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  497. for i := range sellerList {
  498. sellerMap[sellerList[i].SellerId] = sellerList[i]
  499. }
  500. // 重组汇总数据
  501. summaryMap := make(map[int][]*fms.InvoicePaymentCensusInfo)
  502. amountMap := make(map[string]*fms.ContractPaymentServiceAmount)
  503. for i := range summaryList {
  504. v := new(fms.InvoicePaymentCensusInfo)
  505. v.InvoiceId = summaryList[i].InvoiceId
  506. v.InvoiceDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].InvoiceDate)
  507. v.InvoiceAmount = summaryList[i].InvoiceAmount
  508. v.InvoiceOriginAmount = summaryList[i].InvoiceOriginAmount
  509. v.SellerId = summaryList[i].SellerId
  510. v.SellerName = summaryList[i].SellerName
  511. v.SellerGroupId = summaryList[i].SellerGroupId
  512. v.SellerGroupName = summaryList[i].SellerGroupName
  513. if seller, ok := sellerMap[summaryList[i].SellerId]; ok {
  514. v.SellerType = sellerTypeMap[seller.DepartmentId]
  515. }
  516. v.PaymentId = summaryList[i].PaymentId
  517. v.PaymentDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].PaymentDate)
  518. v.PaymentAmount = summaryList[i].PaymentAmount
  519. v.PaymentOriginAmount = summaryList[i].PaymentOriginAmount
  520. v.PayType = summaryList[i].PayType
  521. // 套餐到款分配
  522. svaList := make([]*fms.ContractPaymentServiceAmountItem, 0)
  523. amountList := serviceAmountMap[summaryList[i].PaymentId]
  524. if amountList != nil {
  525. for i := range amountList {
  526. k := fmt.Sprintf("%d-%d", amountList[i].ContractPaymentId, amountList[i].ServiceTemplateId)
  527. amountMap[k] = amountList[i]
  528. }
  529. }
  530. // 合同对应的所有套餐
  531. svList := serviceFormatMap[summaryList[i].RegisterId]
  532. if svList != nil {
  533. for ii := range svList {
  534. vv := new(fms.ContractPaymentServiceAmountItem)
  535. vv.ServiceTemplateId = svList[ii].ServiceTemplateId
  536. vv.ServiceTemplateName = svList[ii].FormatTitle
  537. vv.ServiceTemplatePid = svList[ii].ServiceTemplatePid
  538. vv.ServiceProductId = svList[ii].ServiceProductId
  539. k2 := fmt.Sprintf("%d-%d", summaryList[i].PaymentId, svList[ii].ServiceTemplateId)
  540. a := amountMap[k2]
  541. if a != nil {
  542. vv.ContractPaymentServiceAmountId = a.ContractPaymentServiceAmountId
  543. vv.ContractPaymentId = a.ContractPaymentId
  544. vv.Amount = a.Amount
  545. }
  546. svaList = append(svaList, vv)
  547. }
  548. }
  549. v.ServiceAmountList = svaList
  550. summaryMap[summaryList[i].SummaryId] = append(summaryMap[summaryList[i].SummaryId], v)
  551. }
  552. // 响应列表
  553. for i := range registerList {
  554. v := new(fms.InvoicePaymentCensusItem)
  555. v.SummaryId = registerList[i].SummaryId
  556. v.ContractRegisterId = registerList[i].ContractRegisterId
  557. v.CompanyName = registerList[i].CompanyName
  558. v.NewCompany = registerList[i].NewCompany
  559. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  560. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  561. v.ServicesName = servicesNameMap[registerList[i].ContractRegisterId]
  562. v.InvoicePaymentList = summaryMap[registerList[i].SummaryId]
  563. v.ContractType = registerList[i].ContractType
  564. v.ActualPayCompanies = registerList[i].ActualPayCompanies
  565. respList = append(respList, v)
  566. }
  567. }()
  568. // 开票到款金额合计(换算后)
  569. var invoiceTotal, paymentTotal, amountTotal float64
  570. wg.Add(1)
  571. go func() {
  572. defer wg.Done()
  573. if len(summaryIds) == 0 {
  574. return
  575. }
  576. amountTotalCond := `a.id IN ?`
  577. amountTotalPars := make([]interface{}, 0)
  578. amountTotalPars = append(amountTotalPars, summaryIds)
  579. invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
  580. if e != nil {
  581. totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
  582. return
  583. }
  584. invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
  585. paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
  586. if e != nil {
  587. totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
  588. return
  589. }
  590. paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
  591. amountCond := `a.id IN ? AND (a.invoice_id <> 0 OR (a.payment_id <> 0 AND a.invoice_id =0))`
  592. amountPars := make([]interface{}, 0)
  593. amountPars = append(amountPars, summaryIds)
  594. amountSum, e := fms.GetContractSummaryInvoicePaymentAmount(amountCond, amountPars)
  595. if e != nil {
  596. totalErr = fmt.Errorf("获取汇总金额合计失败, Err: %s", e.Error())
  597. return
  598. }
  599. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  600. }()
  601. // 分币种金额统计
  602. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  603. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  604. wg.Add(1)
  605. go func() {
  606. defer wg.Done()
  607. currencyOB := new(fms.CurrencyUnit)
  608. currencyCond := `enable = 1`
  609. currencyPars := make([]interface{}, 0)
  610. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  611. if e != nil {
  612. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  613. return
  614. }
  615. //unitMap := make(map[string]string)
  616. for i := range currencyList {
  617. //unitMap[currencyList[i].Code] = currencyList[i].UnitName
  618. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  619. Name: currencyList[i].Name,
  620. UnitName: currencyList[i].UnitName,
  621. Code: currencyList[i].Code,
  622. FlagImg: currencyList[i].FlagImg,
  623. })
  624. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  625. Name: currencyList[i].Name,
  626. UnitName: currencyList[i].UnitName,
  627. Code: currencyList[i].Code,
  628. FlagImg: currencyList[i].FlagImg,
  629. })
  630. }
  631. if len(summaryIds) == 0 {
  632. return
  633. }
  634. totalGroupCond := `a.id IN ?`
  635. totalGroupPars := make([]interface{}, 0)
  636. totalGroupPars = append(totalGroupPars, summaryIds)
  637. invoiceSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 1)
  638. if e != nil {
  639. totalGroupErr = fmt.Errorf("获取汇总货币合计开票金额失败, Err: %s", e.Error())
  640. return
  641. }
  642. paymentSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 2)
  643. if e != nil {
  644. totalGroupErr = fmt.Errorf("获取汇总货币合计到款金额失败, Err: %s", e.Error())
  645. return
  646. }
  647. invoiceSumMap := make(map[string]float64)
  648. paymentSumMap := make(map[string]float64)
  649. for i := range invoiceSumGroup {
  650. invoiceSumMap[invoiceSumGroup[i].CurrencyUnit] = invoiceSumGroup[i].OriginAmountTotal
  651. continue
  652. }
  653. for i := range paymentSumGroup {
  654. paymentSumMap[paymentSumGroup[i].CurrencyUnit] = paymentSumGroup[i].OriginAmountTotal
  655. continue
  656. }
  657. for i := range invoiceCurrencyTotals {
  658. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
  659. invoiceCurrencyTotals[i].Amount = a
  660. }
  661. for i := range paymentCurrencyTotals {
  662. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  663. paymentCurrencyTotals[i].Amount = a
  664. }
  665. }()
  666. wg.Wait()
  667. if listErr != nil {
  668. resp.FailMsg("获取失败", listErr.Error(), c)
  669. return
  670. }
  671. if totalErr != nil {
  672. resp.FailMsg("获取失败", totalErr.Error(), c)
  673. return
  674. }
  675. if totalGroupErr != nil {
  676. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  677. return
  678. }
  679. results.DataList = respList
  680. results.InvoiceTotal = invoiceTotal
  681. results.PaymentTotal = paymentTotal
  682. results.AmountTotal = amountTotal
  683. results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  684. results.PaymentCurrencyTotal = paymentCurrencyTotals
  685. }
  686. // 是否导出
  687. if req.IsExport == 1 {
  688. ExportInvoicePaymentCensusList(c, results)
  689. return
  690. }
  691. page.SetTotal(total)
  692. baseData := new(base.BaseData)
  693. baseData.SetPage(page)
  694. baseData.SetList(results)
  695. resp.OkData("获取成功", baseData, c)
  696. }
  697. // IncomeList
  698. // @Title 业务收入统计表
  699. // @Description 获取业务收入统计表接口
  700. // @Param ListParam query int false "套餐类型: 0-月度; 1-季度; 2-半年度;3-年度;4-月度累计"
  701. // @Success 200 {object} fms.CensusIncomeChartResp
  702. // @router /census/income/list [get]
  703. func (this *InvoicePaymentController) IncomeList(c *gin.Context) {
  704. var req fms.IncomeListReq
  705. if e := c.BindQuery(&req); e != nil {
  706. err, ok := e.(validator.ValidationErrors)
  707. if !ok {
  708. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  709. return
  710. }
  711. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  712. return
  713. }
  714. //收入统计
  715. var incomeList models.CensusIncomeChartResp
  716. ch := make(chan models.CensusIncomeChartResp, 1)
  717. go getCensusIncomeListV2(ch, req)
  718. for v := range ch {
  719. incomeList = v
  720. close(ch)
  721. }
  722. // 是否导出
  723. if req.IsExport == 1 {
  724. ExportIncomeList(c, incomeList.DataList)
  725. return
  726. }
  727. resp.OkData("获取成功", incomeList, c)
  728. }
  729. func getCensusIncomeListV2(ch chan models.CensusIncomeChartResp, req fms.IncomeListReq) (incomeChart models.CensusIncomeChartResp, err error) {
  730. defer func() {
  731. if err != nil {
  732. global.LOG.Error(err)
  733. if err != utils.ErrNoRow {
  734. go alarm_msg.SendAlarmMsg("获取业务收入金额统计数据异常,Err:"+err.Error(), 3)
  735. }
  736. }
  737. ch <- incomeChart
  738. }()
  739. //todayStr := utils.GetToday("20060102")
  740. //key := "admin:home:fmsIncomeList:" + todayStr
  741. //
  742. //redisJsonData, redisErr := global.Redis.Get(context.TODO(), key).Result()
  743. //if redisErr != nil {
  744. //获取最新的开票到款日期
  745. cond := ``
  746. historyCond := ``
  747. pars := make([]interface{}, 0)
  748. historyPars := make([]interface{}, 0)
  749. if req.SellerIds != "" {
  750. sellerIds := strings.Split(req.SellerIds, ",")
  751. cond += ` AND (a.seller_id in ? ) `
  752. historyCond += ` AND (seller_id in ? ) `
  753. pars = append(pars, sellerIds)
  754. historyPars = append(historyPars, sellerIds)
  755. }
  756. if req.CompanyType == 1 {
  757. cond += ` AND b.contract_type = 1 `
  758. historyCond += ` AND new_company = 1 `
  759. } else if req.CompanyType == 2 {
  760. cond += ` AND b.contract_type IN (2,3,4) `
  761. historyCond += ` AND new_company = 0 `
  762. }
  763. var latestTime time.Time
  764. invoiceItem, err := fms.GetLatestIncome(cond, pars)
  765. if err != nil && err != utils.ErrNoRow {
  766. err = fmt.Errorf("获取最新的开票或到款日期, Err: %s", err.Error())
  767. return
  768. }
  769. latestTime = invoiceItem.InvoiceDate
  770. if err == utils.ErrNoRow {
  771. historyItem, e := fms.GetLatestHistoryIncome(historyCond, historyPars)
  772. if e != nil && e != utils.ErrNoRow {
  773. err = fmt.Errorf("获取最新的历史开票或到款日期, Err: %s", e.Error())
  774. return
  775. }
  776. latestTime = historyItem.InvoiceDate
  777. }
  778. if latestTime.IsZero() {
  779. latestTime = time.Now()
  780. }
  781. if req.CompanyType == 3 {
  782. cond += ` AND b.contract_type IN (2,3,4) `
  783. historyCond += ` AND new_company = 0 `
  784. }
  785. latestTime = latestTime.AddDate(0, 0, -latestTime.Day()+1)
  786. addMonth := 0
  787. if req.ListParam == "1" {
  788. addMonth = int(3 - latestTime.Month() % 3)
  789. }
  790. if req.ListParam == "2" {
  791. addMonth = int(6 - latestTime.Month() % 6)
  792. }
  793. if req.ListParam == "3" {
  794. addMonth = int(12 - latestTime.Month() % 12)
  795. }
  796. latestTime = latestTime.AddDate(0,addMonth,0)
  797. var dateSlice []string
  798. var totalMoneySlice, prevTotalMoneySlice []float64
  799. var yoySlice []string
  800. var yearNum, monthNum int
  801. var reqStartDate, reqEndDate time.Time
  802. historyTime, _ := time.Parse(utils.FormatDate, "2023-04-01")
  803. // 套餐筛选
  804. if req.ServiceTypes != "" {
  805. serviceTypes := strings.Split(req.ServiceTypes, ",")
  806. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  807. if e != nil {
  808. err = fmt.Errorf("获取合同登记IDs失败, Err: %s", e.Error())
  809. return
  810. }
  811. if len(registerIds) > 0 {
  812. cond += ` AND b.contract_register_id IN ?`
  813. pars = append(pars, registerIds)
  814. } else {
  815. cond += ` AND 1 = 2`
  816. }
  817. // 勾选套餐筛选时忽略导入的历史数据
  818. if req.StartDate == "" {
  819. req.StartDate = "2023-04"
  820. req.EndDate = "3023-04"
  821. } else {
  822. startDateTime, _ := time.Parse(utils.FormatMonth, req.StartDate)
  823. if startDateTime.Before(historyTime) {
  824. req.StartDate = "2023-04"
  825. }
  826. }
  827. }
  828. if req.StartDate != "" && req.EndDate != "" {
  829. st := fmt.Sprint(req.StartDate, "-01 00:00:00")
  830. ed := fmt.Sprint(req.EndDate, "-01 23:59:59")
  831. reqStartDate, _ = time.Parse(utils.FormatDateTime, st)
  832. reqEndDate, _ = time.Parse(utils.FormatDateTime, ed)
  833. if reqEndDate.After(latestTime) {
  834. yearNum = latestTime.Year() - reqStartDate.Year()
  835. monthNum = int(latestTime.Month() - reqStartDate.Month())
  836. } else {
  837. yearNum = reqEndDate.Year() - reqStartDate.Year()
  838. monthNum = int(reqEndDate.Month() - reqStartDate.Month())
  839. }
  840. } else {
  841. yearNum = latestTime.Year() - 2020
  842. monthNum = int(latestTime.Month() - 1)
  843. }
  844. //if yearNum < 0 {
  845. // yearNum = -yearNum
  846. //}
  847. //if monthNum < 0 {
  848. // monthNum = -monthNum
  849. //}
  850. numMonth := yearNum*12 + monthNum //共存在多少个月
  851. if numMonth < 0 {
  852. numMonth = -numMonth
  853. }
  854. //if req.ListParam == "1" {
  855. // numMonth = numMonth / 3
  856. //} else if req.ListParam == "2" {
  857. // numMonth = numMonth / 6
  858. //} else if req.ListParam == "3" {
  859. // numMonth = numMonth / 12
  860. //}
  861. // 累计值
  862. var accumulate float64
  863. var partAccumulate float64
  864. var historyAccumulate float64
  865. var partHistoryAccumulate float64
  866. //dataList := make([]*fms.IncomeSummaryItem, 0)
  867. //historydataList := make([]*fms.IncomeSummaryItem, 0)
  868. fmt.Println("numMonth:", numMonth)
  869. fmt.Println("InvoiceDate:", latestTime)
  870. var j int
  871. for i := 0; i <= numMonth; i++ {
  872. //timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
  873. var endDateTime time.Time
  874. var prevEndDateTime time.Time
  875. var prevStartDate, prevEndDate string
  876. var startDate, endDate string
  877. //开始日期
  878. if req.StartDate != "" && req.EndDate != "" {
  879. startDate = reqStartDate.AddDate(0, i, 0).Format("2006-01")
  880. prevStartDate = reqStartDate.AddDate(-1, i, 0).Format("2006-01")
  881. } else {
  882. startDate = latestTime.AddDate(0, i-numMonth, 0).Format("2006-01")
  883. prevStartDate = latestTime.AddDate(-1, i-numMonth, 0).Format("2006-01")
  884. }
  885. startDate = fmt.Sprint(startDate, "-01")
  886. prevStartDate = fmt.Sprint(prevStartDate, "-01")
  887. startDateTime, _ := time.Parse(utils.FormatDate, startDate)
  888. prevStartDateTime, _ := time.Parse(utils.FormatDate, prevStartDate)
  889. //结束日期
  890. if req.StartDate != "" && req.EndDate != "" {
  891. endDateTime = reqStartDate.AddDate(0, i+1, -1)
  892. prevEndDateTime = reqStartDate.AddDate(-1, i+1, -1)
  893. if reqEndDate.After(latestTime) {
  894. endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
  895. prevEndDateTime = latestTime.AddDate(-1, i-numMonth+1, -1)
  896. }
  897. } else {
  898. endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
  899. prevEndDateTime = latestTime.AddDate(-1, i-numMonth+1, -1)
  900. }
  901. endDate = endDateTime.Format(utils.FormatDate)
  902. prevEndDate = prevEndDateTime.Format(utils.FormatDate)
  903. cond := `1 = 1`
  904. histrtyCond := `1 = 1`
  905. pars := make([]interface{}, 0)
  906. historyPars := make([]interface{}, 0)
  907. prevCond := `1 = 1`
  908. prevHistoryCond := `1 = 1`
  909. prevPars := make([]interface{}, 0)
  910. prevHistoryPars := make([]interface{}, 0)
  911. if req.CompanyType == 1 {
  912. cond += ` AND b.contract_type = 1 `
  913. prevCond += ` AND b.contract_type = 1 `
  914. histrtyCond += ` AND new_company = 1 `
  915. prevHistoryCond += ` AND new_company = 1 `
  916. } else if req.CompanyType == 2 {
  917. cond += ` AND b.contract_type IN (2,3,4) `
  918. prevCond += ` AND b.contract_type IN (2,3,4) `
  919. histrtyCond += ` AND new_company = 0 `
  920. prevHistoryCond += ` AND new_company = 0 `
  921. } else if req.CompanyType == 3 {
  922. //未续约收入金额=去年同期总收入金额(新客户+老客户)-当期老客户收入金额
  923. cond += ` AND b.contract_type IN (2,3,4) `
  924. //prevCond += ` AND b.contract_type IN (2,3,4) `
  925. histrtyCond += ` AND new_company = 0 `
  926. //prevHistoryCond += ` AND new_company = 0 `
  927. }
  928. if req.SellerIds != "" {
  929. sellerIds := strings.Split(req.SellerIds, ",")
  930. cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  931. pars = append(pars, sellerIds, sellerIds)
  932. prevCond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  933. prevPars = append(prevPars, sellerIds, sellerIds)
  934. histrtyCond += ` AND seller_id in ? `
  935. prevHistoryCond += ` AND seller_id in ? `
  936. historyPars = append(historyPars, sellerIds)
  937. prevHistoryPars = append(prevHistoryPars, sellerIds)
  938. }
  939. // 套餐筛选
  940. if req.ServiceTypes != "" {
  941. serviceTypes := strings.Split(req.ServiceTypes, ",")
  942. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  943. if e != nil {
  944. err = fmt.Errorf("获取合同登记IDs失败, Err: %s", e.Error())
  945. return
  946. }
  947. if len(registerIds) > 0 {
  948. cond += ` AND a.register_id IN ?`
  949. prevCond += ` AND a.register_id IN ?`
  950. pars = append(pars, registerIds)
  951. prevPars = append(pars, registerIds)
  952. } else {
  953. cond += ` AND 1 = 2`
  954. prevCond += ` AND 1 = 2`
  955. }
  956. }
  957. //fmt.Println("i:",i)
  958. //fmt.Println("j:",j)
  959. {
  960. //本期
  961. st := fmt.Sprint(startDate, " 00:00:00")
  962. ed := fmt.Sprint(endDate, " 23:59:59")
  963. //校验日期,分段查询
  964. if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
  965. //全部走新查询
  966. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  967. pars = append(pars, st, ed, st, ed)
  968. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  969. if e != nil {
  970. return
  971. }
  972. // 开票到款金额合计(换算后)
  973. var amountTotal float64
  974. if len(summaryIds) > 0 {
  975. amountCond := `a.id IN ? `
  976. amountPars := make([]interface{}, 0)
  977. amountPars = append(amountPars, summaryIds)
  978. if req.SellerIds != "" {
  979. sellerIds := strings.Split(req.SellerIds, ",")
  980. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  981. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  982. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  983. } else {
  984. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  985. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  986. amountPars = append(amountPars, st, ed, st, ed)
  987. }
  988. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  989. if e != nil {
  990. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  991. return
  992. }
  993. //dataList = append(dataList, results...)
  994. var amountSum float64
  995. for _, result := range results {
  996. incomeChart.DataList = append(incomeChart.DataList, result)
  997. amountSum += result.Amount
  998. fmt.Println("result.Amount:", result.Amount)
  999. }
  1000. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1001. accumulate += amountTotal
  1002. partAccumulate += amountTotal
  1003. }
  1004. if i == j || i == numMonth {
  1005. if req.ListParam == "4" {
  1006. totalMoneySlice = append(totalMoneySlice, accumulate)
  1007. if startDateTime.Month() == 12 {
  1008. accumulate = 0
  1009. }
  1010. } else if req.ListParam == "0" {
  1011. totalMoneySlice = append(totalMoneySlice, amountTotal)
  1012. } else if i > 0 || i == numMonth {
  1013. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  1014. fmt.Println("partAccumulate:", partAccumulate)
  1015. partAccumulate = 0.0
  1016. }
  1017. }
  1018. } else if endDateTime.Before(historyTime) || endDateTime.Equal(historyTime) {
  1019. //全部走旧查询
  1020. //fmt.Println("旧查询")
  1021. //fmt.Println("st:",st)
  1022. //fmt.Println("ed:",ed)
  1023. histrtyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1024. historyPars = append(historyPars, st, ed)
  1025. //fmt.Println("st:",st)
  1026. //fmt.Println("ed:",ed)
  1027. // 开票到款金额合计(换算后)
  1028. var amountTotal float64
  1029. results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
  1030. if e != nil {
  1031. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1032. return
  1033. }
  1034. var amountSum float64
  1035. //dataList = append(dataList, results...)
  1036. for _, result := range results {
  1037. incomeChart.DataList = append(incomeChart.DataList, result)
  1038. amountSum += result.Amount
  1039. }
  1040. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1041. accumulate += amountTotal
  1042. partAccumulate += amountTotal
  1043. if i == j || i == numMonth {
  1044. if req.ListParam == "4" {
  1045. totalMoneySlice = append(totalMoneySlice, accumulate)
  1046. if startDateTime.Month() == 12 {
  1047. accumulate = 0
  1048. }
  1049. } else if req.ListParam == "0" {
  1050. totalMoneySlice = append(totalMoneySlice, amountTotal)
  1051. } else if i > 0 || i == numMonth {
  1052. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  1053. partAccumulate = 0.0
  1054. }
  1055. }
  1056. //fmt.Println("partAccumulate:",partAccumulate)
  1057. }
  1058. }
  1059. { // 去年同期,用于计算同比值
  1060. prevSt := fmt.Sprint(prevStartDate, " 00:00:00") // 格式化上一年同一天的开始时间
  1061. prevEd := fmt.Sprint(prevEndDate, " 23:59:59") // 格式化上一年同一天的结束时间
  1062. // 校验日期,分段查询
  1063. if prevStartDateTime.After(historyTime) || prevStartDateTime.Equal(historyTime) {
  1064. // 全部走新查询
  1065. prevCond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))` // 查询条件加入新的时间范围
  1066. prevPars = append(prevPars, prevSt, prevEd, prevSt, prevEd) // 添加时间参数到参数列表
  1067. prevSummaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(prevCond, prevPars) // 获取摘要ID列表
  1068. if e != nil {
  1069. return
  1070. }
  1071. // 开票到款金额合计(换算后)
  1072. var prevAmountTotal float64
  1073. if len(prevSummaryIds) > 0 {
  1074. amountCond := `a.id IN ? ` // 查询条件为ID在给定的摘要ID列表中
  1075. amountPars := make([]interface{}, 0)
  1076. amountPars = append(amountPars, prevSummaryIds) // 将摘要ID列表添加到参数列表
  1077. if req.SellerIds != "" {
  1078. sellerIds := strings.Split(req.SellerIds, ",")
  1079. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1080. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) ` // 根据卖家ID和发票/支付状态筛选时间范围
  1081. amountPars = append(amountPars, sellerIds, prevSt, prevEd, sellerIds, prevSt, prevEd) // 将卖家ID列表添加到参数列表
  1082. } else {
  1083. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1084. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))` // 根据发票/支付状态筛选时间范围
  1085. amountPars = append(amountPars, prevSt, prevEd, prevSt, prevEd)
  1086. }
  1087. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars) // 获取合同摘要收入金额数据
  1088. if e != nil {
  1089. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1090. return
  1091. }
  1092. var amountSum float64
  1093. //historydataList = append(historydataList, results...)
  1094. for _, result := range results {
  1095. amountSum += result.Amount // 累计收入金额
  1096. }
  1097. prevAmountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64) // 将累计金额转换为浮点数
  1098. historyAccumulate += prevAmountTotal // 累计历史金额
  1099. partHistoryAccumulate += prevAmountTotal // 累计部分历史金额
  1100. }
  1101. if i == j || i == numMonth {
  1102. if req.ListParam == "4" {
  1103. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate) // 将累计金额添加到总金额切片中
  1104. if prevStartDateTime.Month() == 12 {
  1105. historyAccumulate = 0 // 如果是去年的12月份,则将历史金额清零
  1106. }
  1107. } else if req.ListParam == "0" {
  1108. prevTotalMoneySlice = append(prevTotalMoneySlice, prevAmountTotal) // 将部分历史金额添加到总金额切片中
  1109. } else if i > 0 || i == numMonth {
  1110. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate) // 将部分历史金额添加到总金额切片中
  1111. fmt.Println("partHistoryAccumulate:", partHistoryAccumulate)
  1112. partHistoryAccumulate = 0.0 // 清零部分历史金额
  1113. }
  1114. }
  1115. } else if prevEndDateTime.Before(historyTime) || prevEndDateTime.Equal(historyTime) {
  1116. // 全部走旧查询
  1117. fmt.Println("prevSt:", prevSt)
  1118. fmt.Println("prevEd:", prevEd)
  1119. prevHistoryCond += ` AND (invoice_time BETWEEN ? AND ?)` // 查询条件加入旧的时间范围
  1120. prevHistoryPars = append(prevHistoryPars, prevSt, prevEd) // 添加时间参数到参数列表
  1121. // 开票到款金额合计(换算后)
  1122. var amountTotal float64
  1123. results, e := fms.GetIncomeHistory(prevHistoryCond, prevHistoryPars) // 获取历史收入数据
  1124. if e != nil {
  1125. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1126. return
  1127. }
  1128. //historydataList = append(historydataList, results...)
  1129. var amountSum float64
  1130. for _, result := range results {
  1131. amountSum += result.Amount // 累计收入金额
  1132. }
  1133. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64) // 将累计金额转换为浮点数
  1134. historyAccumulate += amountTotal // 累计历史金额
  1135. partHistoryAccumulate += amountTotal // 累计部分历史金额
  1136. if i == j || i == numMonth {
  1137. if req.ListParam == "4" {
  1138. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate) // 将累计金额添加到总金额切片中
  1139. if prevStartDateTime.Month() == 12 {
  1140. historyAccumulate = 0 // 如果是去年的12月份,则将历史金额清零
  1141. }
  1142. } else if req.ListParam == "0" {
  1143. prevTotalMoneySlice = append(prevTotalMoneySlice, amountTotal) // 将历史金额添加到总金额切片中
  1144. } else if i > 0 || i == numMonth {
  1145. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate) // 将部分历史金额添加到总金额切片中
  1146. fmt.Println("partHistoryAccumulate:", partHistoryAccumulate)
  1147. partHistoryAccumulate = 0.0 // 清零部分历史金额
  1148. }
  1149. }
  1150. if req.ListParam == "1" && i == j {
  1151. if i == 0 {
  1152. dateSlice = append(dateSlice, startDateTime.AddDate(0, 2, 0).Format("06/01")) // 添加下一个月份的开始日期到日期切片中
  1153. j = j + 2
  1154. } else {
  1155. dateSlice = append(dateSlice, startDateTime.AddDate(0, 3, 0).Format("06/01")) // 添加下一季度的开始日期到日期切片中
  1156. j = j + 3
  1157. }
  1158. } else if req.ListParam == "2" && i == j {
  1159. if i == 0 {
  1160. dateSlice = append(dateSlice, startDateTime.AddDate(0, 5, 0).Format("06/01")) // 添加下五个月份的开始日期到日期切片中
  1161. j = j + 5
  1162. } else {
  1163. dateSlice = append(dateSlice, startDateTime.AddDate(0, 6, 0).Format("06/01")) // 添加下半年的开始日期到日期切片中
  1164. j = j + 6
  1165. }
  1166. } else if req.ListParam == "3" && i == j {
  1167. if i == 0 {
  1168. dateSlice = append(dateSlice, startDateTime.AddDate(0, 11, 0).Format("06/01")) // 添加下十一个月份的开始日期到日期切片中
  1169. j = j + 11
  1170. } else {
  1171. dateSlice = append(dateSlice, startDateTime.AddDate(0, 12, 0).Format("06/01")) // 添加下一季度的开始日期到日期切片中
  1172. j = j + 12
  1173. }
  1174. } else if i == j {
  1175. dateSlice = append(dateSlice, startDateTime.Format("06/01")) // 添加当月开始日期到日期切片中
  1176. j++
  1177. }
  1178. }
  1179. if req.ListParam == "1" && i == j {
  1180. if i == 0 {
  1181. dateSlice = append(dateSlice, startDateTime.AddDate(0, 2, 0).Format("06/01")) // 添加下一个月份的开始日期到日期切片中
  1182. j = j + 2
  1183. } else {
  1184. dateSlice = append(dateSlice, startDateTime.AddDate(0, 3, 0).Format("06/01")) // 添加下一季度的开始日期到日期切片中
  1185. j = j + 3
  1186. }
  1187. } else if req.ListParam == "2" && i == j {
  1188. if i == 0 {
  1189. dateSlice = append(dateSlice, startDateTime.AddDate(0, 5, 0).Format("06/01")) // 添加下五个月份的开始日期到日期切片中
  1190. j = j + 5
  1191. } else {
  1192. dateSlice = append(dateSlice, startDateTime.AddDate(0, 6, 0).Format("06/01")) // 添加下半年的开始日期到日期切片中
  1193. j = j + 6
  1194. }
  1195. } else if req.ListParam == "3" && i == j {
  1196. if i == 0 {
  1197. dateSlice = append(dateSlice, startDateTime.AddDate(0, 11, 0).Format("06/01"))
  1198. j = j + 11
  1199. } else {
  1200. dateSlice = append(dateSlice, startDateTime.AddDate(0, 12, 0).Format("06/01"))
  1201. j = j + 12
  1202. }
  1203. } else if i == j {
  1204. dateSlice = append(dateSlice, startDateTime.Format("06/01"))
  1205. j++
  1206. }
  1207. }
  1208. }
  1209. fmt.Println("prevTotalMoneySlice:", len(prevTotalMoneySlice))
  1210. fmt.Println("totalMoneySlice:", len(totalMoneySlice))
  1211. if req.CompanyType != 3 {
  1212. //计算同比值
  1213. for i := range prevTotalMoneySlice {
  1214. var yoy float64
  1215. var yoyStr string
  1216. //fmt.Println("1:", prevTotalMoneySlice[i])
  1217. //fmt.Println("2:", totalMoneySlice[i])
  1218. //fmt.Println("3:", totalMoneySlice[i]-prevTotalMoneySlice[i])
  1219. totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", totalMoneySlice[i]), 64)
  1220. if prevTotalMoneySlice[i] != 0 && totalMoneySlice[i] != 0 {
  1221. yoy = (totalMoneySlice[i] - prevTotalMoneySlice[i]) / prevTotalMoneySlice[i]
  1222. yoyStr = fmt.Sprintf("%.4f", yoy)
  1223. if i == len(prevTotalMoneySlice)-1 && i > 0 && req.ListParam == "3" {
  1224. fmt.Println("totalMoneySlice[i-1]:", totalMoneySlice[i-1])
  1225. yoy = (totalMoneySlice[i] - totalMoneySlice[i-1]) / totalMoneySlice[i-1]
  1226. yoyStr = fmt.Sprintf("%.4f", yoy)
  1227. }
  1228. }
  1229. yoySlice = append(yoySlice, yoyStr)
  1230. }
  1231. } else {
  1232. // 当筛选条件是”月度“时,并且客户是”未续约“客户,展示柱形图和曲线图
  1233. // 当筛选条件是”季度“、”半年度“、”年度“、”月度统计“时,并且客户是”未续约“时,仅展示柱形图,无曲线图
  1234. // 未续约收入金额=去年同期总收入金额(新客户+老客户)-当期老客户收入金额
  1235. // 移动平均值:若是10月份,计算8月,9月,10月,这三个月的收入金额平均值
  1236. for i := range prevTotalMoneySlice {
  1237. totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", prevTotalMoneySlice[i]-totalMoneySlice[i]), 64)
  1238. var yoy float64
  1239. var yoyStr string
  1240. if i > 1 && req.ListParam == "0" {
  1241. // 前俩月没有
  1242. yoy = (totalMoneySlice[i] + totalMoneySlice[i-1] + totalMoneySlice[i-2]) / 3
  1243. yoyStr = fmt.Sprintf("%.4f", yoy)
  1244. yoySlice = append(yoySlice, yoyStr)
  1245. } else {
  1246. yoySlice = append(yoySlice, "")
  1247. }
  1248. }
  1249. }
  1250. incomeChart.Title = "开票到款统计图"
  1251. incomeChart.Date = dateSlice[:len(totalMoneySlice)]
  1252. incomeChart.TotalMoney = totalMoneySlice
  1253. incomeChart.PrevTotalMoney = prevTotalMoneySlice
  1254. incomeChart.Yoy = yoySlice
  1255. //redisJsonData, err := json.Marshal(incomeChart)
  1256. //if err == nil {
  1257. // global.Redis.SetEX(context.TODO(), key, string(redisJsonData), time.Minute*30)
  1258. //}
  1259. //} else {
  1260. // err = json.Unmarshal([]byte(redisJsonData), &incomeChart)
  1261. // if err != nil {
  1262. // fmt.Println("近两年的收入统计数据,json转换失败")
  1263. // }
  1264. //}
  1265. return
  1266. }
  1267. // ExportIncomeList 导出业务收入统计列表
  1268. func ExportIncomeList(c *gin.Context, list []*fms.IncomeSummaryItem) {
  1269. // 生成Excel文件
  1270. xlsxFile := xlsx.NewFile()
  1271. style := xlsx.NewStyle()
  1272. alignment := xlsx.Alignment{
  1273. Horizontal: "center",
  1274. Vertical: "center",
  1275. WrapText: true,
  1276. }
  1277. style.Alignment = alignment
  1278. style.ApplyAlignment = true
  1279. sheetName := "业务收入统计表"
  1280. sheet, err := xlsxFile.AddSheet(sheetName)
  1281. if err != nil {
  1282. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1283. return
  1284. }
  1285. // 数据表头
  1286. rowTitle := []string{"开票日期", "新客户(1)", "客户名称", "金额", "销售"}
  1287. titleRow := sheet.AddRow()
  1288. for i := range rowTitle {
  1289. v := titleRow.AddCell()
  1290. v.SetString(rowTitle[i])
  1291. v.SetStyle(style)
  1292. }
  1293. incomeSummaryItemList := make(fms.IncomeSummaryItemList, 0)
  1294. incomeSummaryItemList = list
  1295. sort.Sort(incomeSummaryItemList)
  1296. // 填充数据
  1297. for _, v := range incomeSummaryItemList {
  1298. dataRow := sheet.AddRow()
  1299. dataRow.AddCell().SetString(v.InvoiceDate.Format(utils.FormatDate)) // 开票日期
  1300. newCompany := 0
  1301. if v.ContractType == 1 {
  1302. newCompany = 1
  1303. }
  1304. dataRow.AddCell().SetString(strconv.Itoa(newCompany)) // 新客户
  1305. dataRow.AddCell().SetString(v.CompanyName) // 客户名称
  1306. dataRow.AddCell().SetString(fmt.Sprint(v.Amount)) // 金额
  1307. dataRow.AddCell().SetString(v.SellerName) // 销售员
  1308. }
  1309. // 输出文件
  1310. var buffer bytes.Buffer
  1311. _ = xlsxFile.Write(&buffer)
  1312. content := bytes.NewReader(buffer.Bytes())
  1313. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1314. fileName := sheetName + randStr + ".xlsx"
  1315. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1316. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1317. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1318. }
  1319. // List
  1320. // @Title 未开票统计列表
  1321. // @Description 未开票统计列表
  1322. // @Param Keyword query string false "关键词"
  1323. // @Param SellGroupId query int false "销售组别ID"
  1324. // @Param ServiceType query int false "套餐类型"
  1325. // @Param StartDate query string false "合同开始日期"
  1326. // @Param EndDate query string false "合同结束日期"
  1327. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  1328. // @Param HasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
  1329. // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
  1330. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  1331. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  1332. // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'start_date':开票日 、 'end_date':到款日"
  1333. // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
  1334. // @Success 200 {object} fms.ContractRegisterItem
  1335. // @router /census/invoice_payment/not_invoice/list [get]
  1336. func (ct *InvoicePaymentController) NotInvoiceList(c *gin.Context) {
  1337. var req fms.InvoicePaymentCensusListReq
  1338. if e := c.BindQuery(&req); e != nil {
  1339. err, ok := e.(validator.ValidationErrors)
  1340. if !ok {
  1341. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1342. return
  1343. }
  1344. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1345. return
  1346. }
  1347. cond := `1 = 1`
  1348. pars := make([]interface{}, 0)
  1349. noSummaryCond := `1 = 1`
  1350. noSummaryPars := make([]interface{}, 0)
  1351. // 客户姓名/合同编号
  1352. if req.Keyword != "" {
  1353. kw := "%" + req.Keyword + "%"
  1354. cond += ` AND (b.company_name LIKE ? OR b.contract_code LIKE ?)`
  1355. pars = append(pars, kw, kw)
  1356. noSummaryCond += ` AND (b.company_name LIKE ? OR b.contract_code LIKE ?)`
  1357. noSummaryPars = append(noSummaryPars, kw, kw)
  1358. }
  1359. if req.SellerIds != "" {
  1360. sellerIds := strings.Split(req.SellerIds, ",")
  1361. cond += ` AND (b.seller_id in ? OR b.rai_seller_id in ?)`
  1362. pars = append(pars, sellerIds, sellerIds)
  1363. noSummaryCond += ` AND (b.seller_id in ? OR b.rai_seller_id in ?)`
  1364. noSummaryPars = append(noSummaryPars, sellerIds, sellerIds)
  1365. }
  1366. // 套餐筛选
  1367. if req.ServiceTypes != "" {
  1368. serviceTypes := strings.Split(req.ServiceTypes, ",")
  1369. tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  1370. if e != nil {
  1371. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  1372. return
  1373. }
  1374. if len(tempRegisterIds) > 0 {
  1375. cond += ` AND a.register_id IN ?`
  1376. pars = append(pars, tempRegisterIds)
  1377. noSummaryCond += ` AND b.register_id IN ? `
  1378. noSummaryPars = append(noSummaryPars, tempRegisterIds)
  1379. } else {
  1380. cond += ` AND 1 = 2`
  1381. noSummaryCond += ` AND 1 = 2`
  1382. }
  1383. }
  1384. if req.ListParam == 1 {
  1385. cond += ` AND a.service_product_id = 1 `
  1386. noSummaryCond += ` AND b.product_ids = '1' `
  1387. } else if req.ListParam == 2 {
  1388. cond += ` AND a.service_product_id = 2 `
  1389. noSummaryCond += ` AND b.product_ids = '2' `
  1390. }
  1391. page := new(base.Page)
  1392. page.SetPageSize(req.PageSize)
  1393. page.SetCurrent(req.Current)
  1394. // 排序
  1395. if req.SortType == "" {
  1396. req.SortType = "asc"
  1397. }
  1398. if req.SortType != "desc" && req.SortType != "asc" {
  1399. resp.Fail("排序类型不正确", c)
  1400. return
  1401. }
  1402. if req.SortParam == "" {
  1403. page.AddOrderItem(base.OrderItem{Column: "e.start_date", Asc: true})
  1404. } else if req.SortParam == "start_date" {
  1405. if req.SortType == "asc" {
  1406. page.AddOrderItem(base.OrderItem{Column: "e.start_date", Asc: true})
  1407. } else {
  1408. page.AddOrderItem(base.OrderItem{Column: "e.start_date", Asc: false})
  1409. }
  1410. } else if req.SortParam == "end_date" {
  1411. if req.SortType == "asc" {
  1412. page.AddOrderItem(base.OrderItem{Column: "e.end_date", Asc: true})
  1413. } else {
  1414. page.AddOrderItem(base.OrderItem{Column: "e.end_date", Asc: false})
  1415. }
  1416. } else {
  1417. resp.Fail("排序字段不正确", c)
  1418. return
  1419. }
  1420. if req.IsExport == 1 {
  1421. page.SetPageSize(10000)
  1422. page.SetCurrent(1)
  1423. }
  1424. // 先拿到在筛选范围内的合同列表
  1425. cond += ` AND b.contract_amount <> b.invoiced_amount AND b.is_deleted = 0 AND b.contract_amount <> b.payment_amount AND b.contract_status <> 4 `
  1426. registerList, total, e := fms.GetInvoiceCensusPageList(page, cond, pars)
  1427. if e != nil {
  1428. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1429. return
  1430. }
  1431. queryRegisterIds := make([]int, 0)
  1432. for _, v := range registerList {
  1433. queryRegisterIds = append(queryRegisterIds, v.ContractRegisterId)
  1434. }
  1435. fmt.Println("queryRegisterIds:", queryRegisterIds)
  1436. results := new(fms.NotInvoicePaymentCensusResp)
  1437. if len(queryRegisterIds) > 0 {
  1438. // 获取合同的套餐金额信息
  1439. serviceAmountList, e := fms.GetContractServiceAmountByContractRegisterIds(queryRegisterIds)
  1440. if e != nil {
  1441. resp.FailData("获取合同的套餐金额信息失败", "Err:"+e.Error(), c)
  1442. return
  1443. }
  1444. serviceAmountMap := make(map[int]map[int]*fms.ContractServiceAmount, 0)
  1445. for _, v := range serviceAmountList {
  1446. if _, ok := serviceAmountMap[v.ContractRegisterId]; !ok {
  1447. serviceAmountMap[v.ContractRegisterId] = make(map[int]*fms.ContractServiceAmount)
  1448. }
  1449. serviceAmountMap[v.ContractRegisterId][v.ProductId] = v
  1450. }
  1451. var listErr, totalErr, totalGroupErr error
  1452. wg := sync.WaitGroup{}
  1453. // 响应列表
  1454. respList := make([]*fms.NotPaymentCensusItem, 0)
  1455. summaryList := make([]*fms.NotInvoicePaymentSummaryItem, 0)
  1456. wg.Add(1)
  1457. go func() {
  1458. defer wg.Done()
  1459. // 获取汇总数据
  1460. // 这里只能获取到有开票到款过的记录
  1461. summaryCond := cond
  1462. summaryCond += ` AND a.register_id IN ?`
  1463. summaryPars := pars
  1464. summaryPars = append(summaryPars, queryRegisterIds)
  1465. summaryData, e := fms.GetNotInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  1466. if e != nil {
  1467. resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
  1468. return
  1469. }
  1470. //fmt.Println("len(summaryData)", len(summaryData))
  1471. // 有过开票到款记录的合同ids,在后面的查询中去除
  1472. notQueryRegisterIds := make([]int, 0)
  1473. for _, v := range summaryData {
  1474. notQueryRegisterIds = append(notQueryRegisterIds, v.ContractRegisterId)
  1475. }
  1476. summaryList = summaryData
  1477. // 有开票到款过的记录map,用于在后面判断是否有过开票到款,然后补充数据
  1478. NotInvoiceSummaryMap := make(map[int][]*fms.NotInvoicePaymentSummaryItem, 0)
  1479. for _, v := range summaryList {
  1480. // fmt.Println("v2.ContractRegisterId", v.ContractRegisterId)
  1481. NotInvoiceSummaryMap[v.RegisterId] = append(NotInvoiceSummaryMap[v.RegisterId], v)
  1482. }
  1483. // 获取未进行过开票到款的合同数据,其实只用到了合同id和ProductIds用来补充不同的套餐信息
  1484. noSummaryCond += ` AND b.is_deleted = 0 AND b.contract_status <> 4 `
  1485. if len(notQueryRegisterIds) > 0 {
  1486. noSummaryCond += ` AND b.contract_register_id IN ? AND b.contract_register_id NOT IN ?`
  1487. noSummaryPars = append(noSummaryPars, queryRegisterIds, notQueryRegisterIds)
  1488. } else {
  1489. noSummaryCond += ` AND b.contract_register_id IN ? `
  1490. noSummaryPars = append(noSummaryPars, queryRegisterIds)
  1491. }
  1492. noSummaryData, e := fms.GetNoInvoicePaymentCensusData(noSummaryCond, noSummaryPars)
  1493. if e != nil {
  1494. resp.FailMsg("获取失败", "GetNoInvoicePaymentCensusData, Err: "+e.Error(), c)
  1495. return
  1496. }
  1497. //fmt.Println("len(noSummaryData)", len(noSummaryData))
  1498. // 补充为完整的list,包含有汇总记录的和没有汇总记录的
  1499. summaryList = append(summaryList, noSummaryData...)
  1500. //fmt.Println("len(NotInvoiceSummaryMap):", len(NotInvoiceSummaryMap))
  1501. // 遍历列表,补充数据
  1502. for _, v := range summaryList {
  1503. // fmt.Println("ProductIds:", v.ProductIds)
  1504. // fmt.Println("ContractRegisterId:", v.ContractRegisterId)
  1505. // fmt.Println("ServiceProductId:", v.ServiceProductId)
  1506. // fmt.Println("RegisterId:", v.RegisterId)
  1507. fmt.Println("len(NotInvoiceSummaryMap[v.RegisterId]):", len(NotInvoiceSummaryMap[v.ContractRegisterId]))
  1508. if (v.ProductIds == "1,2" || v.ProductIds == "2,1") && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 1 {
  1509. // 套餐是ficc权益都有的,但是只有一个套餐有过开票到款,手动补充另一个套餐的信息
  1510. if v.ServiceProductId == 1 {
  1511. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1512. item := fms.NotInvoicePaymentSummaryItem{
  1513. NotInvoicedAmountOriginTotal: serviceAmount[2].ServiceAmount,
  1514. ServiceProductId: 2,
  1515. }
  1516. item.SellerId = v.SellerId
  1517. item.SellerName = v.SellerName
  1518. item.RaiSellerId = v.RaiSellerId
  1519. item.RaiSellerName = v.RaiSellerName
  1520. item.RMBRate = v.RMBRate
  1521. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item)
  1522. }
  1523. } else {
  1524. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1525. item := fms.NotInvoicePaymentSummaryItem{
  1526. NotInvoicedAmountOriginTotal: serviceAmount[1].ServiceAmount,
  1527. ServiceProductId: 1,
  1528. }
  1529. item.SellerId = v.SellerId
  1530. item.SellerName = v.SellerName
  1531. item.RaiSellerId = v.RaiSellerId
  1532. item.RaiSellerName = v.RaiSellerName
  1533. item.RMBRate = v.RMBRate
  1534. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item)
  1535. }
  1536. }
  1537. } else if (v.ProductIds == "1,2" || v.ProductIds == "2,1") && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1538. // 套餐是ficc权益都有的,但是都没进行过开票到款,补充两个套餐的内容,直接用合同金额当作未开票金额即可
  1539. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1540. item1 := fms.NotInvoicePaymentSummaryItem{
  1541. NotInvoicedAmountOriginTotal: serviceAmount[2].ServiceAmount,
  1542. ServiceProductId: 2,
  1543. }
  1544. item1.SellerId = v.SellerId
  1545. item1.SellerName = v.SellerName
  1546. item1.RaiSellerId = v.RaiSellerId
  1547. item1.RaiSellerName = v.RaiSellerName
  1548. item1.RMBRate = v.RMBRate
  1549. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item1)
  1550. item2 := fms.NotInvoicePaymentSummaryItem{
  1551. NotInvoicedAmountOriginTotal: serviceAmount[1].ServiceAmount,
  1552. ServiceProductId: 1,
  1553. }
  1554. item2.SellerId = v.SellerId
  1555. item2.SellerName = v.SellerName
  1556. item2.RaiSellerId = v.RaiSellerId
  1557. item2.RaiSellerName = v.RaiSellerName
  1558. item2.RMBRate = v.RMBRate
  1559. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item2)
  1560. }
  1561. } else if v.ProductIds == "1" && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1562. // 只有ficc套餐,但是未进行过开票到款,手动补充信息
  1563. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1564. item1 := fms.NotInvoicePaymentSummaryItem{
  1565. NotInvoicedAmountOriginTotal: serviceAmount[1].ServiceAmount,
  1566. ServiceProductId: 1,
  1567. }
  1568. item1.SellerId = v.SellerId
  1569. item1.SellerName = v.SellerName
  1570. item1.RaiSellerId = v.RaiSellerId
  1571. item1.RaiSellerName = v.RaiSellerName
  1572. item1.RMBRate = v.RMBRate
  1573. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item1)
  1574. }
  1575. } else if v.ProductIds == "2" && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1576. // 只有权益套餐,但是未进行过开票到款,手动补充信息
  1577. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1578. item2 := fms.NotInvoicePaymentSummaryItem{
  1579. NotInvoicedAmountOriginTotal: serviceAmount[2].ServiceAmount,
  1580. ServiceProductId: 2,
  1581. }
  1582. item2.SellerId = v.SellerId
  1583. item2.SellerName = v.SellerName
  1584. item2.RaiSellerId = v.RaiSellerId
  1585. item2.RaiSellerName = v.RaiSellerName
  1586. item2.RMBRate = v.RMBRate
  1587. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item2)
  1588. }
  1589. }
  1590. }
  1591. // 重组汇总数据
  1592. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  1593. if e != nil {
  1594. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  1595. return
  1596. }
  1597. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  1598. for i := range sellerList {
  1599. sellerMap[sellerList[i].SellerId] = sellerList[i]
  1600. }
  1601. sellerTypeMap := map[int]string{2: "FICC销售", 5: "权益销售"}
  1602. // 货币列表
  1603. currencyOB := new(fms.CurrencyUnit)
  1604. currencyCond := `enable = 1`
  1605. currencyPars := make([]interface{}, 0)
  1606. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1607. if e != nil {
  1608. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  1609. return
  1610. }
  1611. unitMap := make(map[string]string)
  1612. for i := range currencyList {
  1613. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1614. }
  1615. for registerId, list := range NotInvoiceSummaryMap {
  1616. for i, v := range list {
  1617. // fmt.Println("v.ContractRegisterId", v.ContractRegisterId)
  1618. // fmt.Println("v.ServiceProductId:", v.ServiceProductId)
  1619. // fmt.Println("v.NotInvoicedAmountTotal:", v.NotInvoicedAmountTotal)
  1620. // fmt.Println("registerId:",registerId)
  1621. if v.NotInvoicedAmountOriginTotal == 0 {
  1622. if v.InvoiceAmountTotal > v.PaymentAmountTotal {
  1623. // 有合规登记或补录合同过的,有serviceAmountMap信息
  1624. if _, ok := serviceAmountMap[registerId]; ok {
  1625. if _, ok2 := serviceAmountMap[registerId][v.ServiceProductId]; ok2 {
  1626. list[i].NotInvoicedAmountOriginTotal = serviceAmountMap[registerId][v.ServiceProductId].ServiceAmount - v.InvoiceAmountTotal
  1627. }
  1628. } else {
  1629. // 预登记没有合同套餐金额信息
  1630. list[i].NotInvoicedAmountOriginTotal = v.InvoiceAmountTotal - v.PaymentAmountTotal
  1631. }
  1632. } else {
  1633. if _, ok := serviceAmountMap[registerId]; ok {
  1634. // 有合规登记或补录合同过的,有serviceAmountMap信息
  1635. if _, ok2 := serviceAmountMap[registerId][v.ServiceProductId]; ok2 {
  1636. list[i].NotInvoicedAmountOriginTotal = serviceAmountMap[registerId][v.ServiceProductId].ServiceAmount - v.PaymentAmountTotal
  1637. }
  1638. } else {
  1639. // 预登记没有合同套餐金额信息
  1640. list[i].NotInvoicedAmountOriginTotal = v.PaymentAmountTotal - v.InvoiceAmountTotal
  1641. }
  1642. }
  1643. }
  1644. list[i].NotInvoicedAmountTotal = v.NotInvoicedAmountOriginTotal / v.RMBRate
  1645. list[i].NotInvoicedAmountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", v.NotInvoicedAmountTotal), 64)
  1646. // 补充销售信息
  1647. if v.SellerId > 0 && v.RaiSellerId > 0 {
  1648. if v.ServiceProductId == 1 {
  1649. if seller, ok := sellerMap[v.SellerId]; ok {
  1650. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1651. v.SellerGroupId = seller.GroupId
  1652. v.SellerGroupName = seller.GroupName
  1653. }
  1654. } else {
  1655. if seller, ok := sellerMap[v.RaiSellerId]; ok {
  1656. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1657. v.RaiSellerGroupId = seller.GroupId
  1658. v.RaiSellerGroupName = seller.GroupName
  1659. }
  1660. }
  1661. } else if v.SellerId > 0 && v.RaiSellerId == 0 {
  1662. if seller, ok := sellerMap[v.SellerId]; ok {
  1663. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1664. v.SellerGroupId = seller.GroupId
  1665. v.SellerGroupName = seller.GroupName
  1666. }
  1667. } else if v.SellerId == 0 && v.RaiSellerId > 0 {
  1668. if seller, ok := sellerMap[v.RaiSellerId]; ok {
  1669. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1670. v.RaiSellerGroupId = seller.GroupId
  1671. v.RaiSellerGroupName = seller.GroupName
  1672. }
  1673. }
  1674. }
  1675. }
  1676. // 响应列表
  1677. for i := range registerList {
  1678. v := new(fms.NotPaymentCensusItem)
  1679. v.SummaryId = registerList[i].SummaryId
  1680. v.ContractRegisterId = registerList[i].ContractRegisterId
  1681. v.CompanyName = registerList[i].CompanyName
  1682. v.NewCompany = registerList[i].NewCompany
  1683. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  1684. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  1685. v.ContractType = registerList[i].ContractType
  1686. v.ContractCode = registerList[i].ContractCode
  1687. v.ContractAmount = registerList[i].ContractAmount
  1688. v.UnitName = unitMap[registerList[i].CurrencyUnit]
  1689. v.ProductIds = registerList[i].ProductIds
  1690. //if registerList[i].InvoicedAmount != 0 {
  1691. // v.NotInvoiceTotal = registerList[i].ContractAmount - registerList[i].InvoicedAmount
  1692. //} else {
  1693. // v.NotInvoiceTotal = registerList[i].ContractAmount - registerList[i].PaymentAmount
  1694. //}
  1695. v.NotInvoiceList = NotInvoiceSummaryMap[registerList[i].ContractRegisterId]
  1696. respList = append(respList, v)
  1697. }
  1698. }()
  1699. // 开票到款金额合计(换算后)V2
  1700. var invoiceTotal, contractAmount float64
  1701. wg.Add(1)
  1702. go func() {
  1703. defer wg.Done()
  1704. registerList, e := fms.GetInvoiceCensusList(cond, pars)
  1705. if e != nil {
  1706. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1707. return
  1708. }
  1709. contractIdSumMap := make(map[int]int)
  1710. for _, v := range registerList {
  1711. if v.InvoicedAmount >= v.PaymentAmount {
  1712. invoiceTotal += v.InvoicedAmount
  1713. } else if v.InvoicedAmount == 0 {
  1714. invoiceTotal += v.PaymentAmount
  1715. }
  1716. rate := v.RMBRate
  1717. if rate == 0.0 {
  1718. rate = 1.0
  1719. }
  1720. if _, ok := contractIdSumMap[v.ContractRegisterId]; !ok {
  1721. contractIdSumMap[v.ContractRegisterId] = 1
  1722. contractAmount += v.ContractAmount / rate
  1723. }
  1724. }
  1725. }()
  1726. // 分币种金额统计
  1727. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1728. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1729. contractAmountCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1730. wg.Add(1)
  1731. go func() {
  1732. defer wg.Done()
  1733. currencyOB := new(fms.CurrencyUnit)
  1734. currencyCond := `enable = 1`
  1735. currencyPars := make([]interface{}, 0)
  1736. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1737. if e != nil {
  1738. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  1739. return
  1740. }
  1741. unitMap := make(map[string]string)
  1742. for i := range currencyList {
  1743. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1744. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1745. Name: currencyList[i].Name,
  1746. UnitName: currencyList[i].UnitName,
  1747. Code: currencyList[i].Code,
  1748. FlagImg: currencyList[i].FlagImg,
  1749. })
  1750. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1751. Name: currencyList[i].Name,
  1752. UnitName: currencyList[i].UnitName,
  1753. Code: currencyList[i].Code,
  1754. FlagImg: currencyList[i].FlagImg,
  1755. })
  1756. contractAmountCurrencyTotals = append(contractAmountCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1757. Name: currencyList[i].Name,
  1758. UnitName: currencyList[i].UnitName,
  1759. Code: currencyList[i].Code,
  1760. FlagImg: currencyList[i].FlagImg,
  1761. })
  1762. }
  1763. registerList, e := fms.GetInvoiceCensusList(cond, pars)
  1764. if e != nil {
  1765. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1766. return
  1767. }
  1768. invoiceSumMap := make(map[string]float64)
  1769. contractSumMap := make(map[string]float64)
  1770. contractIdSumMap := make(map[int]int)
  1771. for _, v := range registerList {
  1772. if v.InvoiceOrigin >= v.PaymentOrigin {
  1773. invoiceSumMap[v.CurrencyUnit] += v.InvoicedAmount
  1774. } else {
  1775. invoiceSumMap[v.CurrencyUnit] += v.PaymentAmount
  1776. }
  1777. if _, ok := contractIdSumMap[v.ContractRegisterId]; !ok {
  1778. contractIdSumMap[v.ContractRegisterId] = 1
  1779. contractSumMap[v.CurrencyUnit] += v.ContractAmount
  1780. }
  1781. }
  1782. for _, v := range contractAmountCurrencyTotals {
  1783. v.Amount = contractSumMap[v.Code] - invoiceSumMap[v.Code]
  1784. v.Amount, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", v.Amount), 64)
  1785. }
  1786. }()
  1787. wg.Wait()
  1788. if listErr != nil {
  1789. resp.FailMsg("获取失败", listErr.Error(), c)
  1790. return
  1791. }
  1792. if totalErr != nil {
  1793. resp.FailMsg("获取失败", totalErr.Error(), c)
  1794. return
  1795. }
  1796. if totalGroupErr != nil {
  1797. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  1798. return
  1799. }
  1800. results.DataList = respList
  1801. results.InvoiceTotal = invoiceTotal
  1802. results.NotInvoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", contractAmount-invoiceTotal), 64)
  1803. results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  1804. results.PaymentCurrencyTotal = paymentCurrencyTotals
  1805. results.NotInvoiceCurrencyTotal = contractAmountCurrencyTotals
  1806. fmt.Println("NotInvoiceTotal:", contractAmount-invoiceTotal)
  1807. fmt.Println("contractAmount:", contractAmount)
  1808. fmt.Println("invoiceTotal:", invoiceTotal)
  1809. }
  1810. // 是否导出
  1811. if req.IsExport == 1 {
  1812. ExportNotInvoiceCensusList(c, results)
  1813. return
  1814. }
  1815. page.SetTotal(total)
  1816. baseData := new(base.BaseData)
  1817. baseData.SetPage(page)
  1818. baseData.SetList(results)
  1819. resp.OkData("获取成功", baseData, c)
  1820. }
  1821. // List
  1822. // @Title 开票未到款统计列表
  1823. // @Description 开票未到款统计列表
  1824. // @Param Keyword query string false "关键词"
  1825. // @Param SellGroupId query int false "销售组别ID"
  1826. // @Param ServiceType query int false "套餐类型"
  1827. // @Param StartDate query string false "合同开始日期"
  1828. // @Param EndDate query string false "合同结束日期"
  1829. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  1830. // @Param HasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
  1831. // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
  1832. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  1833. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  1834. // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'invoice_time':开票日 、 'payment_date':到款日"
  1835. // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
  1836. // @Success 200 {object} fms.ContractRegisterItem
  1837. // @router /census/invoice_payment/not_payment/list [get]
  1838. func (ct *InvoicePaymentController) NotPaymentList(c *gin.Context) {
  1839. var req fms.InvoicePaymentCensusListReq
  1840. if e := c.BindQuery(&req); e != nil {
  1841. err, ok := e.(validator.ValidationErrors)
  1842. if !ok {
  1843. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1844. return
  1845. }
  1846. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1847. return
  1848. }
  1849. cond := `1 = 1`
  1850. pars := make([]interface{}, 0)
  1851. // 客户姓名/销售
  1852. if req.Keyword != "" {
  1853. kw := "%" + req.Keyword + "%"
  1854. cond += ` AND (b.company_name LIKE ? OR b.contract_code LIKE ?)`
  1855. pars = append(pars, kw, kw)
  1856. }
  1857. if req.SellerIds != "" {
  1858. sellerIds := strings.Split(req.SellerIds, ",")
  1859. cond += ` AND (c.seller_id in ?)`
  1860. pars = append(pars, sellerIds)
  1861. }
  1862. // 套餐筛选
  1863. if req.ServiceTypes != "" {
  1864. serviceTypes := strings.Split(req.ServiceTypes, ",")
  1865. tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  1866. if e != nil {
  1867. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  1868. return
  1869. }
  1870. if len(tempRegisterIds) > 0 {
  1871. cond += ` AND a.register_id IN ?`
  1872. pars = append(pars, tempRegisterIds)
  1873. } else {
  1874. cond += ` AND 1 = 2`
  1875. }
  1876. }
  1877. if req.ListParam == 1 {
  1878. cond += ` AND a.service_product_id = 1 `
  1879. } else if req.ListParam == 2 {
  1880. cond += ` AND a.service_product_id = 2 `
  1881. }
  1882. page := new(base.Page)
  1883. page.SetPageSize(req.PageSize)
  1884. page.SetCurrent(req.Current)
  1885. // 排序
  1886. if req.SortType == "" {
  1887. req.SortType = "asc"
  1888. }
  1889. if req.SortType != "desc" && req.SortType != "asc" {
  1890. resp.Fail("排序类型不正确", c)
  1891. return
  1892. }
  1893. if req.SortType == "asc" {
  1894. page.AddOrderItem(base.OrderItem{Column: "e.invoice_time", Asc: true})
  1895. page.AddOrderItem(base.OrderItem{Column: "e.modify_time", Asc: false})
  1896. } else {
  1897. page.AddOrderItem(base.OrderItem{Column: "e.invoice_time", Asc: false})
  1898. page.AddOrderItem(base.OrderItem{Column: "e.modify_time", Asc: false})
  1899. }
  1900. if req.IsExport == 1 {
  1901. page.SetPageSize(10000)
  1902. page.SetCurrent(1)
  1903. }
  1904. cond += ` AND b.payment_amount <> b.invoiced_amount AND b.is_deleted = 0 AND b.contract_status <> 4 `
  1905. registerList, total, e := fms.GetNoPaymentCensusPageList(page, cond, pars)
  1906. if e != nil {
  1907. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1908. return
  1909. }
  1910. queryRegisterIds := make([]int, 0)
  1911. for i := range registerList {
  1912. queryRegisterIds = append(queryRegisterIds, registerList[i].ContractRegisterId)
  1913. }
  1914. fmt.Println("queryRegisterIds:", queryRegisterIds)
  1915. // fmt.Println("queryRegisterIds:",queryRegisterIds)
  1916. results := new(fms.NotInvoicePaymentCensusResp)
  1917. if len(queryRegisterIds) > 0 {
  1918. // 获取汇总数据IDs, 用于查询合计数据
  1919. summaryIdsCond := cond
  1920. summaryIdsPars := pars
  1921. if req.SellerIds != "" {
  1922. sellerIds := strings.Split(req.SellerIds, ",")
  1923. summaryIdsCond += ` AND c.seller_id in ? AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  1924. summaryIdsPars = append(summaryIdsPars, sellerIds)
  1925. } else {
  1926. summaryIdsCond += ` AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  1927. summaryIdsPars = append(summaryIdsPars)
  1928. }
  1929. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(summaryIdsCond, summaryIdsPars)
  1930. if e != nil {
  1931. resp.FailMsg("获取失败", "获取商品到款汇总IDs失败, Err: "+e.Error(), c)
  1932. return
  1933. }
  1934. // fmt.Println("summaryIds:",summaryIds)
  1935. var listErr, totalErr, totalGroupErr error
  1936. wg := sync.WaitGroup{}
  1937. // 响应列表
  1938. respList := make([]*fms.NotPaymentCensusItem, 0)
  1939. summaryList := make([]*fms.InvoicePaymentSummaryItem, 0)
  1940. wg.Add(1)
  1941. go func() {
  1942. defer wg.Done()
  1943. // 获取汇总数据
  1944. summaryCond := cond
  1945. summaryCond += ` AND a.register_id IN ?`
  1946. summaryPars := pars
  1947. summaryPars = append(summaryPars, queryRegisterIds)
  1948. if req.SellerIds != "" {
  1949. sellerIds := strings.Split(req.SellerIds, ",")
  1950. summaryCond += ` AND c.seller_id in ? AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  1951. summaryPars = append(summaryPars, sellerIds)
  1952. } else {
  1953. summaryCond += ` AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  1954. summaryPars = append(summaryPars)
  1955. }
  1956. summaryData, e := fms.GetInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  1957. if e != nil {
  1958. resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
  1959. return
  1960. }
  1961. summaryList = summaryData
  1962. // summaryIds := make([]int, 0)
  1963. //
  1964. // for i := range summaryList {
  1965. // //summaryIds = append(summaryIds, summaryList[i].SummaryId)
  1966. //
  1967. // }
  1968. // 货币列表
  1969. currencyOB := new(fms.CurrencyUnit)
  1970. currencyCond := `enable = 1`
  1971. currencyPars := make([]interface{}, 0)
  1972. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1973. if e != nil {
  1974. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  1975. return
  1976. }
  1977. unitMap := make(map[string]string)
  1978. for i := range currencyList {
  1979. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1980. }
  1981. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  1982. if e != nil {
  1983. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  1984. return
  1985. }
  1986. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  1987. for i := range sellerList {
  1988. sellerMap[sellerList[i].SellerId] = sellerList[i]
  1989. }
  1990. sellerTypeMap := map[int]int{crm.SellerDepartmentId: 1, crm.RaiSellerDepartmentId: 2}
  1991. // 重组汇总数据
  1992. summaryMap := make(map[int][]*fms.NotPaymentCensusInfo)
  1993. for i := range summaryList {
  1994. v := new(fms.NotPaymentCensusInfo)
  1995. v.InvoiceId = summaryList[i].InvoiceId
  1996. v.InvoiceDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].InvoiceDate)
  1997. v.InvoiceAmount = summaryList[i].InvoiceAmount
  1998. v.InvoiceOriginAmount = summaryList[i].InvoiceOriginAmount
  1999. v.SellerId = summaryList[i].SellerId
  2000. v.SellerName = summaryList[i].SellerName
  2001. v.SellerGroupId = summaryList[i].SellerGroupId
  2002. v.SellerGroupName = summaryList[i].SellerGroupName
  2003. if seller, ok := sellerMap[summaryList[i].SellerId]; ok {
  2004. v.SellerType = sellerTypeMap[seller.DepartmentId]
  2005. }
  2006. v.PaymentId = summaryList[i].PaymentId
  2007. v.PaymentDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].PaymentDate)
  2008. v.PaymentAmount = summaryList[i].PaymentAmount
  2009. v.PaymentOriginAmount = summaryList[i].PaymentOriginAmount
  2010. v.PayType = summaryList[i].PayType
  2011. v.NotPaymentOriginAmount = summaryList[i].InvoiceOriginAmount - summaryList[i].PaymentOriginAmount
  2012. v.NotPaymentAmount = summaryList[i].InvoiceAmount - summaryList[i].PaymentAmount
  2013. v.ServiceProductId = summaryList[i].ServiceProductId
  2014. v.UnitName = unitMap[summaryList[i].CurrencyUnit]
  2015. summaryMap[summaryList[i].SummaryId] = append(summaryMap[summaryList[i].SummaryId], v)
  2016. }
  2017. // 响应列表
  2018. for i := range registerList {
  2019. v := new(fms.NotPaymentCensusItem)
  2020. v.SummaryId = registerList[i].SummaryId
  2021. v.ContractRegisterId = registerList[i].ContractRegisterId
  2022. v.CompanyName = registerList[i].CompanyName
  2023. v.NewCompany = registerList[i].NewCompany
  2024. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  2025. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  2026. v.InvoicePaymentList = summaryMap[registerList[i].SummaryId]
  2027. v.ContractType = registerList[i].ContractType
  2028. v.ContractCode = registerList[i].ContractCode
  2029. v.ContractAmount = registerList[i].ContractAmount
  2030. v.UnitName = unitMap[registerList[i].CurrencyUnit]
  2031. v.ProductIds = registerList[i].ProductIds
  2032. v.NotInvoiceTotal = registerList[i].ContractAmount - registerList[i].InvoicedAmount
  2033. respList = append(respList, v)
  2034. }
  2035. }()
  2036. // 开票到款金额合计(换算后)
  2037. var invoiceTotal, paymentTotal float64
  2038. wg.Add(1)
  2039. go func() {
  2040. defer wg.Done()
  2041. if len(summaryIds) == 0 {
  2042. return
  2043. }
  2044. amountTotalCond := `a.id IN ?`
  2045. amountTotalPars := make([]interface{}, 0)
  2046. amountTotalPars = append(amountTotalPars, summaryIds)
  2047. invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
  2048. if e != nil {
  2049. totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
  2050. return
  2051. }
  2052. invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
  2053. paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
  2054. if e != nil {
  2055. totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
  2056. return
  2057. }
  2058. paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
  2059. }()
  2060. // 分币种金额统计
  2061. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2062. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2063. notpaymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2064. // contractAmountCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2065. wg.Add(1)
  2066. go func() {
  2067. defer wg.Done()
  2068. currencyOB := new(fms.CurrencyUnit)
  2069. currencyCond := `enable = 1`
  2070. currencyPars := make([]interface{}, 0)
  2071. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  2072. if e != nil {
  2073. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  2074. return
  2075. }
  2076. unitMap := make(map[string]string)
  2077. for i := range currencyList {
  2078. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  2079. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2080. Name: currencyList[i].Name,
  2081. UnitName: currencyList[i].UnitName,
  2082. Code: currencyList[i].Code,
  2083. FlagImg: currencyList[i].FlagImg,
  2084. })
  2085. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2086. Name: currencyList[i].Name,
  2087. UnitName: currencyList[i].UnitName,
  2088. Code: currencyList[i].Code,
  2089. FlagImg: currencyList[i].FlagImg,
  2090. })
  2091. notpaymentCurrencyTotals = append(notpaymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2092. Name: currencyList[i].Name,
  2093. UnitName: currencyList[i].UnitName,
  2094. Code: currencyList[i].Code,
  2095. FlagImg: currencyList[i].FlagImg,
  2096. })
  2097. }
  2098. if len(summaryIds) == 0 {
  2099. return
  2100. }
  2101. totalGroupCond := `a.id IN ?`
  2102. totalGroupPars := make([]interface{}, 0)
  2103. totalGroupPars = append(totalGroupPars, summaryIds)
  2104. invoiceSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 1)
  2105. if e != nil {
  2106. totalGroupErr = fmt.Errorf("获取汇总货币合计开票金额失败, Err: %s", e.Error())
  2107. return
  2108. }
  2109. paymentSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 2)
  2110. if e != nil {
  2111. totalGroupErr = fmt.Errorf("获取汇总货币合计到款金额失败, Err: %s", e.Error())
  2112. return
  2113. }
  2114. invoiceSumMap := make(map[string]float64)
  2115. paymentSumMap := make(map[string]float64)
  2116. //contractSumMap := make(map[string]float64)
  2117. for i := range invoiceSumGroup {
  2118. invoiceSumMap[invoiceSumGroup[i].CurrencyUnit] = invoiceSumGroup[i].OriginAmountTotal
  2119. continue
  2120. }
  2121. for i := range paymentSumGroup {
  2122. paymentSumMap[paymentSumGroup[i].CurrencyUnit] = paymentSumGroup[i].OriginAmountTotal
  2123. continue
  2124. }
  2125. for i := range invoiceCurrencyTotals {
  2126. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
  2127. invoiceCurrencyTotals[i].Amount = a
  2128. }
  2129. for i := range paymentCurrencyTotals {
  2130. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  2131. paymentCurrencyTotals[i].Amount = a
  2132. }
  2133. for i := range notpaymentCurrencyTotals {
  2134. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]-paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  2135. notpaymentCurrencyTotals[i].Amount = a
  2136. }
  2137. }()
  2138. wg.Wait()
  2139. if listErr != nil {
  2140. resp.FailMsg("获取失败", listErr.Error(), c)
  2141. return
  2142. }
  2143. if totalErr != nil {
  2144. resp.FailMsg("获取失败", totalErr.Error(), c)
  2145. return
  2146. }
  2147. if totalGroupErr != nil {
  2148. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  2149. return
  2150. }
  2151. results.DataList = respList
  2152. results.InvoiceTotal = invoiceTotal
  2153. results.PaymentTotal = paymentTotal
  2154. results.NotPaymentTotal = invoiceTotal - paymentTotal
  2155. results.NotPaymentCurrencyTotal = notpaymentCurrencyTotals
  2156. }
  2157. // 是否导出
  2158. if req.IsExport == 1 {
  2159. ExportNotPaymentCensusList(c, results)
  2160. return
  2161. }
  2162. page.SetTotal(total)
  2163. baseData := new(base.BaseData)
  2164. baseData.SetPage(page)
  2165. baseData.SetList(results)
  2166. resp.OkData("获取成功", baseData, c)
  2167. }
  2168. // ExportNotInvoiceCensusList 导出未开票统计列表
  2169. func ExportNotInvoiceCensusList(c *gin.Context, results *fms.NotInvoicePaymentCensusResp) {
  2170. list := results.DataList
  2171. if len(list) == 0 {
  2172. resp.Fail("列表数据为空", c)
  2173. return
  2174. }
  2175. // 生成Excel文件
  2176. xlsxFile := xlsx.NewFile()
  2177. style := xlsx.NewStyle()
  2178. alignment := xlsx.Alignment{
  2179. Horizontal: "center",
  2180. Vertical: "center",
  2181. WrapText: true,
  2182. }
  2183. style.Alignment = alignment
  2184. style.ApplyAlignment = true
  2185. sheetName := "未开票统计表"
  2186. sheet, err := xlsxFile.AddSheet(sheetName)
  2187. if err != nil {
  2188. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  2189. return
  2190. }
  2191. // 前三行-开票金额合计
  2192. rowA := sheet.AddRow()
  2193. cellAA := rowA.AddCell()
  2194. cellAA.SetString(fmt.Sprintf("未开票合计金额(换算后):%.2f(元)", results.NotInvoiceTotal))
  2195. rowBData := "未开票金额:"
  2196. for _, v := range results.NotInvoiceCurrencyTotal {
  2197. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  2198. }
  2199. rowB := sheet.AddRow()
  2200. rowB.AddCell().SetString(rowBData)
  2201. sheet.AddRow()
  2202. // 数据表头
  2203. rowTitle := []string{"序号", "客户名称", "合同编号", "合同开始时间", "合同结束时间", "合同金额", "金额单位", "未开票金额", "未开票换算金额", "套餐类型", "销售", "销售组别", "销售类型"}
  2204. titleRow := sheet.AddRow()
  2205. for i := range rowTitle {
  2206. v := titleRow.AddCell()
  2207. v.SetString(rowTitle[i])
  2208. v.SetStyle(style)
  2209. }
  2210. incomeSummaryItemList := make([]*fms.NotPaymentCensusItem, 0)
  2211. incomeSummaryItemList = list
  2212. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  2213. if e != nil {
  2214. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  2215. return
  2216. }
  2217. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  2218. for i := range sellerList {
  2219. sellerMap[sellerList[i].SellerId] = sellerList[i]
  2220. }
  2221. sellerTypeMap := map[int]string{2: "FICC销售", 5: "权益销售"}
  2222. serviceProductIdMap := map[int]string{
  2223. 1: "FICC套餐",
  2224. 2: "权益套餐",
  2225. }
  2226. // 填充数据
  2227. for i, v := range incomeSummaryItemList {
  2228. dataRow := sheet.AddRow()
  2229. dataRow2 := sheet.AddRow()
  2230. cell := dataRow.AddCell()
  2231. cell.VMerge = 1
  2232. cell.SetString(strconv.Itoa(i + 1)) //序号
  2233. dataRow2.AddCell().SetString("")
  2234. cell2 := dataRow.AddCell()
  2235. cell2.VMerge = 1
  2236. cell2.SetString(v.CompanyName) // 客户名称
  2237. dataRow2.AddCell().SetString("")
  2238. cell3 := dataRow.AddCell()
  2239. cell3.VMerge = 1
  2240. cell3.SetString(v.ContractCode) // 合同编号
  2241. dataRow2.AddCell().SetString("")
  2242. cell4 := dataRow.AddCell()
  2243. cell4.VMerge = 1
  2244. cell4.SetString(v.StartDate) // 合同开始时间
  2245. dataRow2.AddCell().SetString("")
  2246. cell5 := dataRow.AddCell()
  2247. cell5.VMerge = 1
  2248. cell5.SetString(v.EndDate) // 合同结束时间
  2249. dataRow2.AddCell().SetString("")
  2250. cell6 := dataRow.AddCell()
  2251. cell6.VMerge = 1
  2252. cell6.SetString(fmt.Sprintf("%.2f", v.ContractAmount)) // 合同金额
  2253. dataRow2.AddCell().SetString("")
  2254. cell7 := dataRow.AddCell()
  2255. cell7.VMerge = 1
  2256. cell7.SetString(v.UnitName) // 金额单位
  2257. dataRow2.AddCell().SetString("")
  2258. for j, item := range v.NotInvoiceList {
  2259. if j == 1 {
  2260. dataRow2.AddCell().SetString(fmt.Sprintf("%.2f", item.NotInvoicedAmountTotal)) // 未开票金额
  2261. dataRow2.AddCell().SetString(serviceProductIdMap[item.ServiceProductId]) // 套餐类型
  2262. if item.SellerId > 0 && item.RaiSellerId > 0 {
  2263. if item.ServiceProductId == 1 {
  2264. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2265. if seller, ok := sellerMap[item.SellerId]; ok {
  2266. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2267. }
  2268. dataRow2.AddCell().SetString(item.SellerName) // 销售
  2269. dataRow2.AddCell().SetString(item.SellerGroupName) // 销售组别
  2270. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2271. } else {
  2272. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2273. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2274. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2275. }
  2276. dataRow2.AddCell().SetString(item.RaiSellerName) // 销售
  2277. dataRow2.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2278. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2279. }
  2280. } else if item.SellerId > 0 && item.RaiSellerId == 0 {
  2281. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2282. if seller, ok := sellerMap[item.SellerId]; ok {
  2283. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2284. }
  2285. dataRow2.AddCell().SetString(item.SellerName) // 销售
  2286. dataRow2.AddCell().SetString(item.SellerGroupName) // 销售组别
  2287. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2288. } else if item.SellerId == 0 && item.RaiSellerId > 0 {
  2289. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2290. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2291. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2292. }
  2293. dataRow2.AddCell().SetString(item.RaiSellerName) // 销售
  2294. dataRow2.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2295. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2296. }
  2297. } else {
  2298. dataRow.AddCell().SetString(fmt.Sprintf("%.2f", item.NotInvoicedAmountOriginTotal)) // 未开票金额
  2299. dataRow.AddCell().SetString(fmt.Sprintf("%.2f", item.NotInvoicedAmountTotal)) // 未开票换算金额
  2300. dataRow.AddCell().SetString(serviceProductIdMap[item.ServiceProductId]) // 套餐类型
  2301. if item.SellerId > 0 && item.RaiSellerId > 0 {
  2302. if item.ServiceProductId == 1 {
  2303. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2304. if seller, ok := sellerMap[item.SellerId]; ok {
  2305. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2306. }
  2307. dataRow.AddCell().SetString(item.SellerName) // 销售
  2308. dataRow.AddCell().SetString(item.SellerGroupName) // 销售组别
  2309. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2310. } else {
  2311. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2312. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2313. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2314. }
  2315. dataRow.AddCell().SetString(item.RaiSellerName) // 销售
  2316. dataRow.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2317. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2318. }
  2319. } else if item.SellerId > 0 && item.RaiSellerId == 0 {
  2320. if seller, ok := sellerMap[item.SellerId]; ok {
  2321. item.SellerGroupName = seller.GroupName
  2322. }
  2323. if seller, ok := sellerMap[item.SellerId]; ok {
  2324. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2325. }
  2326. dataRow.AddCell().SetString(item.SellerName) // 销售
  2327. dataRow.AddCell().SetString(item.SellerGroupName) // 销售组别
  2328. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2329. } else if item.SellerId == 0 && item.RaiSellerId > 0 {
  2330. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2331. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2332. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2333. }
  2334. dataRow.AddCell().SetString(item.RaiSellerName) // 销售
  2335. dataRow.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2336. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2337. }
  2338. }
  2339. }
  2340. }
  2341. // 输出文件
  2342. var buffer bytes.Buffer
  2343. _ = xlsxFile.Write(&buffer)
  2344. content := bytes.NewReader(buffer.Bytes())
  2345. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2346. fileName := sheetName + randStr + ".xlsx"
  2347. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  2348. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2349. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  2350. }
  2351. // ExportNotPaymentCensusList 导出开票未到款统计列表
  2352. func ExportNotPaymentCensusList(c *gin.Context, results *fms.NotInvoicePaymentCensusResp) {
  2353. list := results.DataList
  2354. if len(list) == 0 {
  2355. resp.Fail("列表数据为空", c)
  2356. return
  2357. }
  2358. // 生成Excel文件
  2359. xlsxFile := xlsx.NewFile()
  2360. style := xlsx.NewStyle()
  2361. alignment := xlsx.Alignment{
  2362. Horizontal: "center",
  2363. Vertical: "center",
  2364. WrapText: true,
  2365. }
  2366. style.Alignment = alignment
  2367. style.ApplyAlignment = true
  2368. sheet, err := xlsxFile.AddSheet("开票未到款统计")
  2369. if err != nil {
  2370. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  2371. return
  2372. }
  2373. _ = sheet.SetColWidth(1, 1, 30)
  2374. _ = sheet.SetColWidth(3, 3, 30)
  2375. // 前三行-开票金额合计
  2376. rowA := sheet.AddRow()
  2377. cellAA := rowA.AddCell()
  2378. cellAA.SetString(fmt.Sprintf("开票未到款合计金额(换算后):%.2f(元)", results.NotPaymentTotal))
  2379. rowBData := "开票未到款金额:"
  2380. for _, v := range results.NotPaymentCurrencyTotal {
  2381. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  2382. }
  2383. rowB := sheet.AddRow()
  2384. rowB.AddCell().SetString(rowBData)
  2385. sheet.AddRow()
  2386. // 表头, 套餐动态获取
  2387. rowTitle := []string{"序号", "客户名称", "合同编号", "合同起始日期", "合同结束日期", "套餐类型", "开票日", "开票金额", "金额单位", "开票换算金额", "开票销售",
  2388. "销售组别", "销售类型"}
  2389. titleRow := sheet.AddRow()
  2390. for i := range rowTitle {
  2391. v := titleRow.AddCell()
  2392. v.SetString(rowTitle[i])
  2393. v.SetStyle(style)
  2394. }
  2395. serviceProductIdMap := map[int]string{
  2396. 1: "FICC套餐",
  2397. 2: "权益套餐",
  2398. }
  2399. sellerTypeMap := map[int]string{1: "FICC销售", 2: "权益销售"}
  2400. for k, v := range list {
  2401. dataRow := sheet.AddRow()
  2402. // 前四个单元格根据每行开票到款条数向下合并
  2403. l := len(v.InvoicePaymentList)
  2404. mergeRowNum := l - 1
  2405. // 序号
  2406. sortNum := k + 1
  2407. colA := dataRow.AddCell()
  2408. colA.VMerge = mergeRowNum
  2409. colA.SetString(fmt.Sprint(sortNum))
  2410. // 客户名称
  2411. colB := dataRow.AddCell()
  2412. colB.VMerge = mergeRowNum
  2413. colB.SetString(v.CompanyName)
  2414. // 合同编号
  2415. colC := dataRow.AddCell()
  2416. colC.VMerge = mergeRowNum
  2417. colC.SetString(v.ContractCode)
  2418. // 合同有效期
  2419. colD := dataRow.AddCell()
  2420. colD.VMerge = mergeRowNum
  2421. colD.SetString(v.StartDate)
  2422. colF := dataRow.AddCell()
  2423. colF.VMerge = mergeRowNum
  2424. colF.SetString(v.EndDate)
  2425. // 套餐类型
  2426. colE := dataRow.AddCell()
  2427. colE.VMerge = mergeRowNum
  2428. colE.SetString(serviceProductIdMap[v.InvoicePaymentList[0].ServiceProductId])
  2429. // 开票到款信息
  2430. for _, v2 := range v.InvoicePaymentList {
  2431. rowData := []string{
  2432. v2.InvoiceDate, // 开票日
  2433. fmt.Sprint(v2.NotPaymentOriginAmount), // 开票原始金额
  2434. v2.UnitName, // 开票金额
  2435. fmt.Sprint(v2.NotPaymentAmount), // 开票换算金额
  2436. v2.SellerName, // 销售
  2437. v2.SellerGroupName, // 组别
  2438. sellerTypeMap[v2.SellerType], // 销售类型
  2439. }
  2440. for i := range rowData {
  2441. dataRow.AddCell().SetString(rowData[i])
  2442. }
  2443. }
  2444. }
  2445. // 输出文件
  2446. var buffer bytes.Buffer
  2447. _ = xlsxFile.Write(&buffer)
  2448. content := bytes.NewReader(buffer.Bytes())
  2449. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2450. fileName := "商品到款统计_" + randStr + ".xlsx"
  2451. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  2452. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2453. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  2454. }