invoice_payment.go 97 KB

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