invoice_payment.go 95 KB

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