invoice_payment.go 104 KB

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