invoice_payment.go 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794
  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. }
  1126. if req.SellerIds != "" {
  1127. sellerIds := strings.Split(req.SellerIds, ",")
  1128. cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  1129. pars = append(pars, sellerIds, sellerIds)
  1130. prevCond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  1131. prevPars = append(prevPars, sellerIds, sellerIds)
  1132. histrtyCond += ` AND seller_id in ? `
  1133. prevHistoryCond += ` AND seller_id in ? `
  1134. historyPars = append(historyPars, sellerIds)
  1135. prevHistoryPars = append(prevHistoryPars, sellerIds)
  1136. }
  1137. //fmt.Println("i:",i)
  1138. //fmt.Println("j:",j)
  1139. {
  1140. //本期
  1141. st := fmt.Sprint(startDate, " 00:00:00")
  1142. ed := fmt.Sprint(endDate, " 23:59:59")
  1143. //校验日期,分段查询
  1144. if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
  1145. //全部走新查询
  1146. //fmt.Println("新查询")
  1147. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1148. pars = append(pars, st, ed, st, ed)
  1149. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1150. if e != nil {
  1151. return
  1152. }
  1153. // 开票到款金额合计(换算后)
  1154. var amountTotal float64
  1155. if len(summaryIds) > 0 {
  1156. amountCond := `a.id IN ? `
  1157. amountPars := make([]interface{}, 0)
  1158. amountPars = append(amountPars, summaryIds)
  1159. if req.SellerIds != "" {
  1160. sellerIds := strings.Split(req.SellerIds, ",")
  1161. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1162. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1163. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  1164. } else {
  1165. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1166. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1167. amountPars = append(amountPars, st, ed, st, ed)
  1168. }
  1169. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1170. if e != nil {
  1171. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1172. return
  1173. }
  1174. //dataList = append(dataList, results...)
  1175. var amountSum float64
  1176. for _, result := range results {
  1177. incomeChart.DataList = append(incomeChart.DataList, result)
  1178. amountSum += result.Amount
  1179. fmt.Println("result.Amount:", result.Amount)
  1180. }
  1181. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1182. accumulate += amountTotal
  1183. partAccumulate += amountTotal
  1184. }
  1185. if i == j || i == numMonth {
  1186. if req.ListParam == "4" {
  1187. totalMoneySlice = append(totalMoneySlice, accumulate)
  1188. if startDateTime.Month() == 12 {
  1189. accumulate = 0
  1190. }
  1191. } else if req.ListParam == "0" {
  1192. totalMoneySlice = append(totalMoneySlice, amountTotal)
  1193. } else if i > 0 || i == numMonth {
  1194. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  1195. fmt.Println("partAccumulate:", partAccumulate)
  1196. partAccumulate = 0.0
  1197. }
  1198. }
  1199. } else if endDateTime.Before(historyTime) || endDateTime.Equal(historyTime) {
  1200. //全部走旧查询
  1201. //fmt.Println("旧查询")
  1202. //fmt.Println("st:",st)
  1203. //fmt.Println("ed:",ed)
  1204. histrtyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1205. historyPars = append(historyPars, st, ed)
  1206. //fmt.Println("st:",st)
  1207. //fmt.Println("ed:",ed)
  1208. // 开票到款金额合计(换算后)
  1209. var amountTotal float64
  1210. results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
  1211. if e != nil {
  1212. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1213. return
  1214. }
  1215. var amountSum float64
  1216. //dataList = append(dataList, results...)
  1217. for _, result := range results {
  1218. incomeChart.DataList = append(incomeChart.DataList, result)
  1219. amountSum += result.Amount
  1220. }
  1221. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1222. accumulate += amountTotal
  1223. partAccumulate += amountTotal
  1224. if i == j || i == numMonth {
  1225. if req.ListParam == "4" {
  1226. totalMoneySlice = append(totalMoneySlice, accumulate)
  1227. if startDateTime.Month() == 12 {
  1228. accumulate = 0
  1229. }
  1230. } else if req.ListParam == "0" {
  1231. totalMoneySlice = append(totalMoneySlice, amountTotal)
  1232. } else if i > 0 || i == numMonth {
  1233. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  1234. partAccumulate = 0.0
  1235. }
  1236. }
  1237. //fmt.Println("partAccumulate:",partAccumulate)
  1238. }
  1239. }
  1240. { // 去年同期,用于计算同比值
  1241. prevSt := fmt.Sprint(prevStartDate, " 00:00:00") // 格式化上一年同一天的开始时间
  1242. prevEd := fmt.Sprint(prevEndDate, " 23:59:59") // 格式化上一年同一天的结束时间
  1243. // 校验日期,分段查询
  1244. if prevStartDateTime.After(historyTime) || prevStartDateTime.Equal(historyTime) {
  1245. // 全部走新查询
  1246. prevCond += ` AND ((b.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))` // 查询条件加入新的时间范围
  1247. prevPars = append(prevPars, prevSt, prevEd, prevSt, prevEd) // 添加时间参数到参数列表
  1248. prevSummaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(prevCond, prevPars) // 获取摘要ID列表
  1249. if e != nil {
  1250. return
  1251. }
  1252. // 开票到款金额合计(换算后)
  1253. var prevAmountTotal float64
  1254. if len(prevSummaryIds) > 0 {
  1255. amountCond := `a.id IN ? ` // 查询条件为ID在给定的摘要ID列表中
  1256. amountPars := make([]interface{}, 0)
  1257. amountPars = append(amountPars, prevSummaryIds) // 将摘要ID列表添加到参数列表
  1258. if req.SellerIds != "" {
  1259. sellerIds := strings.Split(req.SellerIds, ",")
  1260. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1261. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) ` // 根据卖家ID和发票/支付状态筛选时间范围
  1262. amountPars = append(amountPars, sellerIds, prevSt, prevEd, sellerIds, prevSt, prevEd) // 将卖家ID列表添加到参数列表
  1263. } else {
  1264. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1265. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))` // 根据发票/支付状态筛选时间范围
  1266. amountPars = append(amountPars, prevSt, prevEd)
  1267. }
  1268. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars) // 获取合同摘要收入金额数据
  1269. if e != nil {
  1270. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1271. return
  1272. }
  1273. var amountSum float64
  1274. //historydataList = append(historydataList, results...)
  1275. for _, result := range results {
  1276. amountSum += result.Amount // 累计收入金额
  1277. }
  1278. prevAmountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64) // 将累计金额转换为浮点数
  1279. historyAccumulate += prevAmountTotal // 累计历史金额
  1280. partHistoryAccumulate += prevAmountTotal // 累计部分历史金额
  1281. }
  1282. if i == j || i == numMonth {
  1283. if req.ListParam == "4" {
  1284. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate) // 将累计金额添加到总金额切片中
  1285. if prevStartDateTime.Month() == 12 {
  1286. historyAccumulate = 0 // 如果是去年的12月份,则将历史金额清零
  1287. }
  1288. } else if req.ListParam == "0" {
  1289. prevTotalMoneySlice = append(prevTotalMoneySlice, prevAmountTotal) // 将部分历史金额添加到总金额切片中
  1290. } else if i > 0 || i == numMonth {
  1291. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate) // 将部分历史金额添加到总金额切片中
  1292. fmt.Println("partHistoryAccumulate:", partHistoryAccumulate)
  1293. partHistoryAccumulate = 0.0 // 清零部分历史金额
  1294. }
  1295. }
  1296. } else if prevEndDateTime.Before(historyTime) || prevEndDateTime.Equal(historyTime) {
  1297. // 全部走旧查询
  1298. fmt.Println("prevSt:", prevSt)
  1299. fmt.Println("prevEd:", prevEd)
  1300. prevHistoryCond += ` AND (invoice_time BETWEEN ? AND ?)` // 查询条件加入旧的时间范围
  1301. prevHistoryPars = append(prevHistoryPars, prevSt, prevEd) // 添加时间参数到参数列表
  1302. // 开票到款金额合计(换算后)
  1303. var amountTotal float64
  1304. results, e := fms.GetIncomeHistory(prevHistoryCond, prevHistoryPars) // 获取历史收入数据
  1305. if e != nil {
  1306. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1307. return
  1308. }
  1309. //historydataList = append(historydataList, results...)
  1310. var amountSum float64
  1311. for _, result := range results {
  1312. amountSum += result.Amount // 累计收入金额
  1313. }
  1314. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64) // 将累计金额转换为浮点数
  1315. historyAccumulate += amountTotal // 累计历史金额
  1316. partHistoryAccumulate += amountTotal // 累计部分历史金额
  1317. if i == j || i == numMonth {
  1318. if req.ListParam == "4" {
  1319. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate) // 将累计金额添加到总金额切片中
  1320. if prevStartDateTime.Month() == 12 {
  1321. historyAccumulate = 0 // 如果是去年的12月份,则将历史金额清零
  1322. }
  1323. } else if req.ListParam == "0" {
  1324. prevTotalMoneySlice = append(prevTotalMoneySlice, amountTotal) // 将历史金额添加到总金额切片中
  1325. } else if i > 0 || i == numMonth {
  1326. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate) // 将部分历史金额添加到总金额切片中
  1327. fmt.Println("partHistoryAccumulate:", partHistoryAccumulate)
  1328. partHistoryAccumulate = 0.0 // 清零部分历史金额
  1329. }
  1330. }
  1331. if req.ListParam == "1" && i == j {
  1332. if i == 0 {
  1333. dateSlice = append(dateSlice, startDateTime.AddDate(0, 2, 0).Format("06/01")) // 添加下一个月份的开始日期到日期切片中
  1334. j = j + 2
  1335. } else {
  1336. dateSlice = append(dateSlice, startDateTime.AddDate(0, 3, 0).Format("06/01")) // 添加下一季度的开始日期到日期切片中
  1337. j = j + 3
  1338. }
  1339. } else if req.ListParam == "2" && i == j {
  1340. if i == 0 {
  1341. dateSlice = append(dateSlice, startDateTime.AddDate(0, 5, 0).Format("06/01")) // 添加下五个月份的开始日期到日期切片中
  1342. j = j + 5
  1343. } else {
  1344. dateSlice = append(dateSlice, startDateTime.AddDate(0, 6, 0).Format("06/01")) // 添加下半年的开始日期到日期切片中
  1345. j = j + 6
  1346. }
  1347. } else if req.ListParam == "3" && i == j {
  1348. if i == 0 {
  1349. dateSlice = append(dateSlice, startDateTime.AddDate(0, 11, 0).Format("06/01")) // 添加下十一个月份的开始日期到日期切片中
  1350. j = j + 11
  1351. } else {
  1352. dateSlice = append(dateSlice, startDateTime.AddDate(0, 12, 0).Format("06/01")) // 添加下一季度的开始日期到日期切片中
  1353. j = j + 12
  1354. }
  1355. } else if i == j {
  1356. dateSlice = append(dateSlice, startDateTime.Format("06/01")) // 添加当月开始日期到日期切片中
  1357. j++
  1358. }
  1359. }
  1360. if req.ListParam == "1" && i == j {
  1361. if i == 0 {
  1362. dateSlice = append(dateSlice, startDateTime.AddDate(0, 2, 0).Format("06/01")) // 添加下一个月份的开始日期到日期切片中
  1363. j = j + 2
  1364. } else {
  1365. dateSlice = append(dateSlice, startDateTime.AddDate(0, 3, 0).Format("06/01")) // 添加下一季度的开始日期到日期切片中
  1366. j = j + 3
  1367. }
  1368. } else if req.ListParam == "2" && i == j {
  1369. if i == 0 {
  1370. dateSlice = append(dateSlice, startDateTime.AddDate(0, 5, 0).Format("06/01")) // 添加下五个月份的开始日期到日期切片中
  1371. j = j + 5
  1372. } else {
  1373. dateSlice = append(dateSlice, startDateTime.AddDate(0, 6, 0).Format("06/01")) // 添加下半年的开始日期到日期切片中
  1374. j = j + 6
  1375. }
  1376. } else if req.ListParam == "3" && i == j {
  1377. if i == 0 {
  1378. dateSlice = append(dateSlice, startDateTime.AddDate(0, 11, 0).Format("06/01"))
  1379. j = j + 11
  1380. } else {
  1381. dateSlice = append(dateSlice, startDateTime.AddDate(0, 12, 0).Format("06/01"))
  1382. j = j + 12
  1383. }
  1384. } else if i == j {
  1385. dateSlice = append(dateSlice, startDateTime.Format("06/01"))
  1386. j++
  1387. }
  1388. }
  1389. }
  1390. fmt.Println("prevTotalMoneySlice:", len(prevTotalMoneySlice))
  1391. fmt.Println("totalMoneySlice:", len(totalMoneySlice))
  1392. if req.CompanyType != 3 {
  1393. //计算同比值
  1394. for i := range prevTotalMoneySlice {
  1395. var yoy float64
  1396. var yoyStr string
  1397. //fmt.Println("1:", prevTotalMoneySlice[i])
  1398. //fmt.Println("2:", totalMoneySlice[i])
  1399. //fmt.Println("3:", totalMoneySlice[i]-prevTotalMoneySlice[i])
  1400. totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", totalMoneySlice[i]), 64)
  1401. if prevTotalMoneySlice[i] != 0 && totalMoneySlice[i] != 0 {
  1402. yoy = (totalMoneySlice[i] - prevTotalMoneySlice[i]) / prevTotalMoneySlice[i]
  1403. yoyStr = fmt.Sprintf("%.4f", yoy)
  1404. if i == len(prevTotalMoneySlice)-1 && i > 0 && req.ListParam == "3" {
  1405. fmt.Println("totalMoneySlice[i-1]:", totalMoneySlice[i-1])
  1406. yoy = (totalMoneySlice[i] - totalMoneySlice[i-1]) / totalMoneySlice[i-1]
  1407. yoyStr = fmt.Sprintf("%.4f", yoy)
  1408. }
  1409. }
  1410. yoySlice = append(yoySlice, yoyStr)
  1411. }
  1412. } else {
  1413. // 当筛选条件是”月度“时,并且客户是”未续约“客户,展示柱形图和曲线图
  1414. // 当筛选条件是”季度“、”半年度“、”年度“、”月度统计“时,并且客户是”未续约“时,仅展示柱形图,无曲线图
  1415. // 未续约客户收入:去年同期老客户收入金额 减 当期老客户收入金额
  1416. // 移动平均值:若是10月份,计算8月,9月,10月,这三个月的收入金额平均值
  1417. for i := range prevTotalMoneySlice {
  1418. totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", prevTotalMoneySlice[i]-totalMoneySlice[i]), 64)
  1419. var yoy float64
  1420. var yoyStr string
  1421. if i > 1 && req.ListParam == "0" {
  1422. // 前俩月没有
  1423. yoy = (totalMoneySlice[i] + totalMoneySlice[i-1] + totalMoneySlice[i-2]) / 3
  1424. yoyStr = fmt.Sprintf("%.4f", yoy)
  1425. yoySlice = append(yoySlice, yoyStr)
  1426. } else {
  1427. yoySlice = append(yoySlice, "")
  1428. }
  1429. }
  1430. }
  1431. incomeChart.Title = "开票到款统计图"
  1432. incomeChart.Date = dateSlice
  1433. incomeChart.TotalMoney = totalMoneySlice
  1434. incomeChart.PrevTotalMoney = prevTotalMoneySlice
  1435. incomeChart.Yoy = yoySlice
  1436. //redisJsonData, err := json.Marshal(incomeChart)
  1437. //if err == nil {
  1438. // global.Redis.SetEX(context.TODO(), key, string(redisJsonData), time.Minute*30)
  1439. //}
  1440. //} else {
  1441. // err = json.Unmarshal([]byte(redisJsonData), &incomeChart)
  1442. // if err != nil {
  1443. // fmt.Println("近两年的收入统计数据,json转换失败")
  1444. // }
  1445. //}
  1446. return
  1447. }
  1448. // ExportIncomeList 导出业务收入统计列表
  1449. func ExportIncomeList(c *gin.Context, list []*fms.IncomeSummaryItem) {
  1450. // 生成Excel文件
  1451. xlsxFile := xlsx.NewFile()
  1452. style := xlsx.NewStyle()
  1453. alignment := xlsx.Alignment{
  1454. Horizontal: "center",
  1455. Vertical: "center",
  1456. WrapText: true,
  1457. }
  1458. style.Alignment = alignment
  1459. style.ApplyAlignment = true
  1460. sheetName := "业务收入统计表"
  1461. sheet, err := xlsxFile.AddSheet(sheetName)
  1462. if err != nil {
  1463. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1464. return
  1465. }
  1466. // 数据表头
  1467. rowTitle := []string{"开票日期", "新客户(1)", "客户名称", "金额", "销售"}
  1468. titleRow := sheet.AddRow()
  1469. for i := range rowTitle {
  1470. v := titleRow.AddCell()
  1471. v.SetString(rowTitle[i])
  1472. v.SetStyle(style)
  1473. }
  1474. incomeSummaryItemList := make(fms.IncomeSummaryItemList, 0)
  1475. incomeSummaryItemList = list
  1476. sort.Sort(incomeSummaryItemList)
  1477. // 填充数据
  1478. for _, v := range incomeSummaryItemList {
  1479. dataRow := sheet.AddRow()
  1480. dataRow.AddCell().SetString(v.InvoiceDate.Format(utils.FormatDate)) // 开票日期
  1481. newCompany := 0
  1482. if v.ContractType == 1 {
  1483. newCompany = 1
  1484. }
  1485. dataRow.AddCell().SetString(strconv.Itoa(newCompany)) // 新客户
  1486. dataRow.AddCell().SetString(v.CompanyName) // 客户名称
  1487. dataRow.AddCell().SetString(fmt.Sprint(v.Amount)) // 金额
  1488. dataRow.AddCell().SetString(v.SellerName) // 销售员
  1489. }
  1490. // 输出文件
  1491. var buffer bytes.Buffer
  1492. _ = xlsxFile.Write(&buffer)
  1493. content := bytes.NewReader(buffer.Bytes())
  1494. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1495. fileName := sheetName + randStr + ".xlsx"
  1496. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1497. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1498. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1499. }
  1500. // List
  1501. // @Title 未开票统计列表
  1502. // @Description 未开票统计列表
  1503. // @Param Keyword query string false "关键词"
  1504. // @Param SellGroupId query int false "销售组别ID"
  1505. // @Param ServiceType query int false "套餐类型"
  1506. // @Param StartDate query string false "合同开始日期"
  1507. // @Param EndDate query string false "合同结束日期"
  1508. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  1509. // @Param HasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
  1510. // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
  1511. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  1512. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  1513. // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'start_date':开票日 、 'end_date':到款日"
  1514. // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
  1515. // @Success 200 {object} fms.ContractRegisterItem
  1516. // @router /census/invoice_payment/not_invoice/list [get]
  1517. func (ct *InvoicePaymentController) NotInvoiceList(c *gin.Context) {
  1518. var req fms.InvoicePaymentCensusListReq
  1519. if e := c.BindQuery(&req); e != nil {
  1520. err, ok := e.(validator.ValidationErrors)
  1521. if !ok {
  1522. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1523. return
  1524. }
  1525. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1526. return
  1527. }
  1528. cond := `1 = 1`
  1529. pars := make([]interface{}, 0)
  1530. noSummaryCond := `1 = 1`
  1531. noSummaryPars := make([]interface{}, 0)
  1532. // 客户姓名/合同编号
  1533. if req.Keyword != "" {
  1534. kw := "%" + req.Keyword + "%"
  1535. cond += ` AND (b.company_name LIKE ? OR b.contract_code LIKE ?)`
  1536. pars = append(pars, kw, kw)
  1537. noSummaryCond += ` AND (b.company_name LIKE ? OR b.contract_code LIKE ?)`
  1538. noSummaryPars = append(noSummaryPars, kw, kw)
  1539. }
  1540. if req.SellerIds != "" {
  1541. sellerIds := strings.Split(req.SellerIds, ",")
  1542. cond += ` AND (b.seller_id in ? OR b.rai_seller_id in ?)`
  1543. pars = append(pars, sellerIds, sellerIds)
  1544. noSummaryCond += ` AND (b.seller_id in ? OR b.rai_seller_id in ?)`
  1545. noSummaryPars = append(noSummaryPars, sellerIds, sellerIds)
  1546. }
  1547. // 套餐筛选
  1548. if req.ServiceTypes != "" {
  1549. serviceTypes := strings.Split(req.ServiceTypes, ",")
  1550. tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  1551. if e != nil {
  1552. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  1553. return
  1554. }
  1555. if len(tempRegisterIds) > 0 {
  1556. cond += ` AND a.register_id IN ?`
  1557. pars = append(pars, tempRegisterIds)
  1558. noSummaryCond += ` AND b.register_id IN ? `
  1559. noSummaryPars = append(noSummaryPars, tempRegisterIds)
  1560. } else {
  1561. cond += ` AND 1 = 2`
  1562. noSummaryCond += ` AND 1 = 2`
  1563. }
  1564. }
  1565. if req.ListParam == 1 {
  1566. cond += ` AND a.service_product_id = 1 `
  1567. noSummaryCond += ` AND b.product_ids = '1' `
  1568. } else if req.ListParam == 2 {
  1569. cond += ` AND a.service_product_id = 2 `
  1570. noSummaryCond += ` AND b.product_ids = '2' `
  1571. }
  1572. page := new(base.Page)
  1573. page.SetPageSize(req.PageSize)
  1574. page.SetCurrent(req.Current)
  1575. // 排序
  1576. if req.SortType == "" {
  1577. req.SortType = "asc"
  1578. }
  1579. if req.SortType != "desc" && req.SortType != "asc" {
  1580. resp.Fail("排序类型不正确", c)
  1581. return
  1582. }
  1583. if req.SortParam == "" {
  1584. page.AddOrderItem(base.OrderItem{Column: "e.start_date", Asc: true})
  1585. } else if req.SortParam == "start_date" {
  1586. if req.SortType == "asc" {
  1587. page.AddOrderItem(base.OrderItem{Column: "e.start_date", Asc: true})
  1588. } else {
  1589. page.AddOrderItem(base.OrderItem{Column: "e.start_date", Asc: false})
  1590. }
  1591. } else if req.SortParam == "end_date" {
  1592. if req.SortType == "asc" {
  1593. page.AddOrderItem(base.OrderItem{Column: "e.end_date", Asc: true})
  1594. } else {
  1595. page.AddOrderItem(base.OrderItem{Column: "e.end_date", Asc: false})
  1596. }
  1597. } else {
  1598. resp.Fail("排序字段不正确", c)
  1599. return
  1600. }
  1601. if req.IsExport == 1 {
  1602. page.SetPageSize(10000)
  1603. page.SetCurrent(1)
  1604. }
  1605. // 先拿到在筛选范围内的合同列表
  1606. 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 `
  1607. registerList, total, e := fms.GetInvoiceCensusPageList(page, cond, pars)
  1608. if e != nil {
  1609. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1610. return
  1611. }
  1612. queryRegisterIds := make([]int, 0)
  1613. for _, v := range registerList {
  1614. queryRegisterIds = append(queryRegisterIds, v.ContractRegisterId)
  1615. }
  1616. fmt.Println("queryRegisterIds:", queryRegisterIds)
  1617. results := new(fms.NotInvoicePaymentCensusResp)
  1618. if len(queryRegisterIds) > 0 {
  1619. // 获取合同的套餐金额信息
  1620. serviceAmountList, e := fms.GetContractServiceAmountByContractRegisterIds(queryRegisterIds)
  1621. if e != nil {
  1622. resp.FailData("获取合同的套餐金额信息失败", "Err:"+e.Error(), c)
  1623. return
  1624. }
  1625. serviceAmountMap := make(map[int]map[int]*fms.ContractServiceAmount, 0)
  1626. for _, v := range serviceAmountList {
  1627. if _, ok := serviceAmountMap[v.ContractRegisterId]; !ok {
  1628. serviceAmountMap[v.ContractRegisterId] = make(map[int]*fms.ContractServiceAmount)
  1629. }
  1630. serviceAmountMap[v.ContractRegisterId][v.ProductId] = v
  1631. }
  1632. var listErr, totalErr, totalGroupErr error
  1633. wg := sync.WaitGroup{}
  1634. // 响应列表
  1635. respList := make([]*fms.NotPaymentCensusItem, 0)
  1636. summaryList := make([]*fms.NotInvoicePaymentSummaryItem, 0)
  1637. wg.Add(1)
  1638. go func() {
  1639. defer wg.Done()
  1640. // 获取汇总数据
  1641. // 这里只能获取到有开票到款过的记录
  1642. summaryCond := cond
  1643. summaryCond += ` AND a.register_id IN ?`
  1644. summaryPars := pars
  1645. summaryPars = append(summaryPars, queryRegisterIds)
  1646. summaryData, e := fms.GetNotInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  1647. if e != nil {
  1648. resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
  1649. return
  1650. }
  1651. //fmt.Println("len(summaryData)", len(summaryData))
  1652. // 有过开票到款记录的合同ids,在后面的查询中去除
  1653. notQueryRegisterIds := make([]int, 0)
  1654. for _, v := range summaryData {
  1655. notQueryRegisterIds = append(notQueryRegisterIds, v.ContractRegisterId)
  1656. }
  1657. summaryList = summaryData
  1658. // 有开票到款过的记录map,用于在后面判断是否有过开票到款,然后补充数据
  1659. NotInvoiceSummaryMap := make(map[int][]*fms.NotInvoicePaymentSummaryItem, 0)
  1660. for _, v := range summaryList {
  1661. // fmt.Println("v2.ContractRegisterId", v.ContractRegisterId)
  1662. NotInvoiceSummaryMap[v.RegisterId] = append(NotInvoiceSummaryMap[v.RegisterId], v)
  1663. }
  1664. // 获取未进行过开票到款的合同数据,其实只用到了合同id和ProductIds用来补充不同的套餐信息
  1665. noSummaryCond += ` AND b.is_deleted = 0 AND b.contract_status <> 4 `
  1666. if len(notQueryRegisterIds) > 0 {
  1667. noSummaryCond += ` AND b.contract_register_id IN ? AND b.contract_register_id NOT IN ?`
  1668. noSummaryPars = append(noSummaryPars, queryRegisterIds, notQueryRegisterIds)
  1669. } else {
  1670. noSummaryCond += ` AND b.contract_register_id IN ? `
  1671. noSummaryPars = append(noSummaryPars, queryRegisterIds)
  1672. }
  1673. noSummaryData, e := fms.GetNoInvoicePaymentCensusData(noSummaryCond, noSummaryPars)
  1674. if e != nil {
  1675. resp.FailMsg("获取失败", "GetNoInvoicePaymentCensusData, Err: "+e.Error(), c)
  1676. return
  1677. }
  1678. //fmt.Println("len(noSummaryData)", len(noSummaryData))
  1679. // 补充为完整的list,包含有汇总记录的和没有汇总记录的
  1680. summaryList = append(summaryList, noSummaryData...)
  1681. //fmt.Println("len(NotInvoiceSummaryMap):", len(NotInvoiceSummaryMap))
  1682. // 遍历列表,补充数据
  1683. for _, v := range summaryList {
  1684. // fmt.Println("ProductIds:", v.ProductIds)
  1685. // fmt.Println("ContractRegisterId:", v.ContractRegisterId)
  1686. // fmt.Println("ServiceProductId:", v.ServiceProductId)
  1687. // fmt.Println("RegisterId:", v.RegisterId)
  1688. fmt.Println("len(NotInvoiceSummaryMap[v.RegisterId]):", len(NotInvoiceSummaryMap[v.ContractRegisterId]))
  1689. if (v.ProductIds == "1,2" || v.ProductIds == "2,1") && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 1 {
  1690. // 套餐是ficc权益都有的,但是只有一个套餐有过开票到款,手动补充另一个套餐的信息
  1691. if v.ServiceProductId == 1 {
  1692. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1693. item := fms.NotInvoicePaymentSummaryItem{
  1694. NotInvoicedAmountTotal: serviceAmount[2].ServiceAmount,
  1695. ServiceProductId: 2,
  1696. }
  1697. item.SellerId = v.SellerId
  1698. item.SellerName = v.SellerName
  1699. item.RaiSellerId = v.RaiSellerId
  1700. item.RaiSellerName = v.RaiSellerName
  1701. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item)
  1702. }
  1703. } else {
  1704. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1705. item := fms.NotInvoicePaymentSummaryItem{
  1706. NotInvoicedAmountTotal: serviceAmount[1].ServiceAmount,
  1707. ServiceProductId: 1,
  1708. }
  1709. item.SellerId = v.SellerId
  1710. item.SellerName = v.SellerName
  1711. item.RaiSellerId = v.RaiSellerId
  1712. item.RaiSellerName = v.RaiSellerName
  1713. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item)
  1714. }
  1715. }
  1716. } else if (v.ProductIds == "1,2" || v.ProductIds == "2,1") && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1717. // 套餐是ficc权益都有的,但是都没进行过开票到款,补充两个套餐的内容,直接用合同金额当作未开票金额即可
  1718. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1719. item1 := fms.NotInvoicePaymentSummaryItem{
  1720. NotInvoicedAmountTotal: serviceAmount[2].ServiceAmount,
  1721. ServiceProductId: 2,
  1722. }
  1723. item1.SellerId = v.SellerId
  1724. item1.SellerName = v.SellerName
  1725. item1.RaiSellerId = v.RaiSellerId
  1726. item1.RaiSellerName = v.RaiSellerName
  1727. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item1)
  1728. item2 := fms.NotInvoicePaymentSummaryItem{
  1729. NotInvoicedAmountTotal: serviceAmount[1].ServiceAmount,
  1730. ServiceProductId: 1,
  1731. }
  1732. item2.SellerId = v.SellerId
  1733. item2.SellerName = v.SellerName
  1734. item2.RaiSellerId = v.RaiSellerId
  1735. item2.RaiSellerName = v.RaiSellerName
  1736. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item2)
  1737. }
  1738. } else if v.ProductIds == "1" && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1739. // 只有ficc套餐,但是未进行过开票到款,手动补充信息
  1740. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1741. item1 := fms.NotInvoicePaymentSummaryItem{
  1742. NotInvoicedAmountTotal: serviceAmount[1].ServiceAmount,
  1743. ServiceProductId: 1,
  1744. }
  1745. item1.SellerId = v.SellerId
  1746. item1.SellerName = v.SellerName
  1747. item1.RaiSellerId = v.RaiSellerId
  1748. item1.RaiSellerName = v.RaiSellerName
  1749. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item1)
  1750. }
  1751. } else if v.ProductIds == "2" && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1752. // 只有权益套餐,但是未进行过开票到款,手动补充信息
  1753. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1754. item2 := fms.NotInvoicePaymentSummaryItem{
  1755. NotInvoicedAmountTotal: serviceAmount[2].ServiceAmount,
  1756. ServiceProductId: 2,
  1757. }
  1758. item2.SellerId = v.SellerId
  1759. item2.SellerName = v.SellerName
  1760. item2.RaiSellerId = v.RaiSellerId
  1761. item2.RaiSellerName = v.RaiSellerName
  1762. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item2)
  1763. }
  1764. }
  1765. }
  1766. // 重组汇总数据
  1767. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  1768. if e != nil {
  1769. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  1770. return
  1771. }
  1772. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  1773. for i := range sellerList {
  1774. sellerMap[sellerList[i].SellerId] = sellerList[i]
  1775. }
  1776. sellerTypeMap := map[int]string{2: "FICC销售", 5: "权益销售"}
  1777. // 货币列表
  1778. currencyOB := new(fms.CurrencyUnit)
  1779. currencyCond := `enable = 1`
  1780. currencyPars := make([]interface{}, 0)
  1781. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1782. if e != nil {
  1783. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  1784. return
  1785. }
  1786. unitMap := make(map[string]string)
  1787. for i := range currencyList {
  1788. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1789. }
  1790. for registerId, list := range NotInvoiceSummaryMap {
  1791. for _, v := range list {
  1792. // fmt.Println("v.ContractRegisterId", v.ContractRegisterId)
  1793. // fmt.Println("v.ServiceProductId:", v.ServiceProductId)
  1794. // fmt.Println("v.NotInvoicedAmountTotal:", v.NotInvoicedAmountTotal)
  1795. // fmt.Println("registerId:",registerId)
  1796. if v.NotInvoicedAmountTotal == 0 {
  1797. if v.InvoiceAmountTotal > v.PaymentAmountTotal {
  1798. // 有合规登记或补录合同过的,有serviceAmountMap信息
  1799. if _, ok := serviceAmountMap[registerId]; ok {
  1800. if _, ok2 := serviceAmountMap[registerId][v.ServiceProductId]; ok2 {
  1801. v.NotInvoicedAmountTotal = serviceAmountMap[registerId][v.ServiceProductId].ServiceAmount - v.InvoiceAmountTotal
  1802. }
  1803. } else {
  1804. // 预登记没有合同套餐金额信息
  1805. v.NotInvoicedAmountTotal = v.InvoiceAmountTotal - v.PaymentAmountTotal
  1806. }
  1807. } else {
  1808. if _, ok := serviceAmountMap[registerId]; ok {
  1809. // 有合规登记或补录合同过的,有serviceAmountMap信息
  1810. if _, ok2 := serviceAmountMap[registerId][v.ServiceProductId]; ok2 {
  1811. v.NotInvoicedAmountTotal = serviceAmountMap[registerId][v.ServiceProductId].ServiceAmount - v.PaymentAmountTotal
  1812. }
  1813. } else {
  1814. // 预登记没有合同套餐金额信息
  1815. v.NotInvoicedAmountTotal = v.PaymentAmountTotal - v.InvoiceAmountTotal
  1816. }
  1817. }
  1818. }
  1819. // 补充销售信息
  1820. if v.SellerId > 0 && v.RaiSellerId > 0 {
  1821. if v.ServiceProductId == 1 {
  1822. if seller, ok := sellerMap[v.SellerId]; ok {
  1823. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1824. v.SellerGroupId = seller.GroupId
  1825. v.SellerGroupName = seller.GroupName
  1826. }
  1827. } else {
  1828. if seller, ok := sellerMap[v.RaiSellerId]; ok {
  1829. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1830. v.RaiSellerGroupId = seller.GroupId
  1831. v.RaiSellerGroupName = seller.GroupName
  1832. }
  1833. }
  1834. } else if v.SellerId > 0 && v.RaiSellerId == 0 {
  1835. if seller, ok := sellerMap[v.SellerId]; ok {
  1836. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1837. v.SellerGroupId = seller.GroupId
  1838. v.SellerGroupName = seller.GroupName
  1839. }
  1840. } else if v.SellerId == 0 && v.RaiSellerId > 0 {
  1841. if seller, ok := sellerMap[v.RaiSellerId]; ok {
  1842. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1843. v.RaiSellerGroupId = seller.GroupId
  1844. v.RaiSellerGroupName = seller.GroupName
  1845. }
  1846. }
  1847. }
  1848. }
  1849. // 响应列表
  1850. for i := range registerList {
  1851. v := new(fms.NotPaymentCensusItem)
  1852. v.SummaryId = registerList[i].SummaryId
  1853. v.ContractRegisterId = registerList[i].ContractRegisterId
  1854. v.CompanyName = registerList[i].CompanyName
  1855. v.NewCompany = registerList[i].NewCompany
  1856. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  1857. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  1858. v.ContractType = registerList[i].ContractType
  1859. v.ContractCode = registerList[i].ContractCode
  1860. v.ContractAmount = registerList[i].ContractAmount
  1861. v.UnitName = unitMap[registerList[i].CurrencyUnit]
  1862. v.ProductIds = registerList[i].ProductIds
  1863. //if registerList[i].InvoicedAmount != 0 {
  1864. // v.NotInvoiceTotal = registerList[i].ContractAmount - registerList[i].InvoicedAmount
  1865. //} else {
  1866. // v.NotInvoiceTotal = registerList[i].ContractAmount - registerList[i].PaymentAmount
  1867. //}
  1868. v.NotInvoiceList = NotInvoiceSummaryMap[registerList[i].ContractRegisterId]
  1869. respList = append(respList, v)
  1870. }
  1871. }()
  1872. // 开票到款金额合计(换算后)V2
  1873. var invoiceTotal, contractAmount float64
  1874. wg.Add(1)
  1875. go func() {
  1876. defer wg.Done()
  1877. registerList, e := fms.GetInvoiceCensusList(cond, pars)
  1878. if e != nil {
  1879. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1880. return
  1881. }
  1882. contractIdSumMap := make(map[int]int)
  1883. for _, v := range registerList {
  1884. if v.InvoicedAmount >= v.PaymentAmount {
  1885. invoiceTotal += v.InvoicedAmount
  1886. } else if v.InvoicedAmount == 0 {
  1887. invoiceTotal += v.PaymentAmount
  1888. }
  1889. rate := v.RMBRate
  1890. if rate == 0.0 {
  1891. rate = 1.0
  1892. }
  1893. if _, ok := contractIdSumMap[v.ContractRegisterId]; !ok {
  1894. contractIdSumMap[v.ContractRegisterId] = 1
  1895. contractAmount += v.ContractAmount / rate
  1896. }
  1897. }
  1898. }()
  1899. // 分币种金额统计
  1900. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1901. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1902. contractAmountCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1903. wg.Add(1)
  1904. go func() {
  1905. defer wg.Done()
  1906. currencyOB := new(fms.CurrencyUnit)
  1907. currencyCond := `enable = 1`
  1908. currencyPars := make([]interface{}, 0)
  1909. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1910. if e != nil {
  1911. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  1912. return
  1913. }
  1914. unitMap := make(map[string]string)
  1915. for i := range currencyList {
  1916. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1917. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1918. Name: currencyList[i].Name,
  1919. UnitName: currencyList[i].UnitName,
  1920. Code: currencyList[i].Code,
  1921. FlagImg: currencyList[i].FlagImg,
  1922. })
  1923. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1924. Name: currencyList[i].Name,
  1925. UnitName: currencyList[i].UnitName,
  1926. Code: currencyList[i].Code,
  1927. FlagImg: currencyList[i].FlagImg,
  1928. })
  1929. contractAmountCurrencyTotals = append(contractAmountCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1930. Name: currencyList[i].Name,
  1931. UnitName: currencyList[i].UnitName,
  1932. Code: currencyList[i].Code,
  1933. FlagImg: currencyList[i].FlagImg,
  1934. })
  1935. }
  1936. registerList, e := fms.GetInvoiceCensusList(cond, pars)
  1937. if e != nil {
  1938. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1939. return
  1940. }
  1941. invoiceSumMap := make(map[string]float64)
  1942. contractSumMap := make(map[string]float64)
  1943. contractIdSumMap := make(map[int]int)
  1944. for _, v := range registerList {
  1945. if v.InvoiceOrigin >= v.PaymentOrigin {
  1946. invoiceSumMap[v.CurrencyUnit] += v.InvoicedAmount
  1947. } else {
  1948. invoiceSumMap[v.CurrencyUnit] += v.PaymentAmount
  1949. }
  1950. if _, ok := contractIdSumMap[v.ContractRegisterId]; !ok {
  1951. contractIdSumMap[v.ContractRegisterId] = 1
  1952. contractSumMap[v.CurrencyUnit] += v.ContractAmount
  1953. }
  1954. }
  1955. for _, v := range contractAmountCurrencyTotals {
  1956. v.Amount = contractSumMap[v.Code] - invoiceSumMap[v.Code]
  1957. v.Amount, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", v.Amount), 64)
  1958. }
  1959. }()
  1960. wg.Wait()
  1961. if listErr != nil {
  1962. resp.FailMsg("获取失败", listErr.Error(), c)
  1963. return
  1964. }
  1965. if totalErr != nil {
  1966. resp.FailMsg("获取失败", totalErr.Error(), c)
  1967. return
  1968. }
  1969. if totalGroupErr != nil {
  1970. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  1971. return
  1972. }
  1973. results.DataList = respList
  1974. results.InvoiceTotal = invoiceTotal
  1975. results.NotInvoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", contractAmount-invoiceTotal), 64)
  1976. results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  1977. results.PaymentCurrencyTotal = paymentCurrencyTotals
  1978. results.NotInvoiceCurrencyTotal = contractAmountCurrencyTotals
  1979. fmt.Println("NotInvoiceTotal:", contractAmount-invoiceTotal)
  1980. fmt.Println("contractAmount:", contractAmount)
  1981. fmt.Println("invoiceTotal:", invoiceTotal)
  1982. }
  1983. // 是否导出
  1984. if req.IsExport == 1 {
  1985. ExportNotInvoiceCensusList(c, results)
  1986. return
  1987. }
  1988. page.SetTotal(total)
  1989. baseData := new(base.BaseData)
  1990. baseData.SetPage(page)
  1991. baseData.SetList(results)
  1992. resp.OkData("获取成功", baseData, c)
  1993. }
  1994. // List
  1995. // @Title 开票未到款统计列表
  1996. // @Description 开票未到款统计列表
  1997. // @Param Keyword query string false "关键词"
  1998. // @Param SellGroupId query int false "销售组别ID"
  1999. // @Param ServiceType query int false "套餐类型"
  2000. // @Param StartDate query string false "合同开始日期"
  2001. // @Param EndDate query string false "合同结束日期"
  2002. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  2003. // @Param HasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
  2004. // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
  2005. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  2006. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  2007. // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'invoice_time':开票日 、 'payment_date':到款日"
  2008. // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
  2009. // @Success 200 {object} fms.ContractRegisterItem
  2010. // @router /census/invoice_payment/not_payment/list [get]
  2011. func (ct *InvoicePaymentController) NotPaymentList(c *gin.Context) {
  2012. var req fms.InvoicePaymentCensusListReq
  2013. if e := c.BindQuery(&req); e != nil {
  2014. err, ok := e.(validator.ValidationErrors)
  2015. if !ok {
  2016. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  2017. return
  2018. }
  2019. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  2020. return
  2021. }
  2022. cond := `1 = 1`
  2023. pars := make([]interface{}, 0)
  2024. // 客户姓名/销售
  2025. if req.Keyword != "" {
  2026. kw := "%" + req.Keyword + "%"
  2027. cond += ` AND (b.company_name LIKE ? OR b.contract_code LIKE ?)`
  2028. pars = append(pars, kw, kw)
  2029. }
  2030. if req.SellerIds != "" {
  2031. sellerIds := strings.Split(req.SellerIds, ",")
  2032. cond += ` AND (c.seller_id in ?)`
  2033. pars = append(pars, sellerIds)
  2034. }
  2035. // 套餐筛选
  2036. if req.ServiceTypes != "" {
  2037. serviceTypes := strings.Split(req.ServiceTypes, ",")
  2038. tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  2039. if e != nil {
  2040. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  2041. return
  2042. }
  2043. if len(tempRegisterIds) > 0 {
  2044. cond += ` AND a.register_id IN ?`
  2045. pars = append(pars, tempRegisterIds)
  2046. } else {
  2047. cond += ` AND 1 = 2`
  2048. }
  2049. }
  2050. if req.ListParam == 1 {
  2051. cond += ` AND a.service_product_id = 1 `
  2052. } else if req.ListParam == 2 {
  2053. cond += ` AND a.service_product_id = 2 `
  2054. }
  2055. page := new(base.Page)
  2056. page.SetPageSize(req.PageSize)
  2057. page.SetCurrent(req.Current)
  2058. // 排序
  2059. if req.SortType == "" {
  2060. req.SortType = "asc"
  2061. }
  2062. if req.SortType != "desc" && req.SortType != "asc" {
  2063. resp.Fail("排序类型不正确", c)
  2064. return
  2065. }
  2066. if req.SortType == "asc" {
  2067. page.AddOrderItem(base.OrderItem{Column: "e.invoice_time", Asc: true})
  2068. page.AddOrderItem(base.OrderItem{Column: "e.modify_time", Asc: false})
  2069. } else {
  2070. page.AddOrderItem(base.OrderItem{Column: "e.invoice_time", Asc: false})
  2071. page.AddOrderItem(base.OrderItem{Column: "e.modify_time", Asc: false})
  2072. }
  2073. if req.IsExport == 1 {
  2074. page.SetPageSize(10000)
  2075. page.SetCurrent(1)
  2076. }
  2077. cond += ` AND b.payment_amount <> b.invoiced_amount AND b.is_deleted = 0 AND b.contract_status <> 4 `
  2078. registerList, total, e := fms.GetNoPaymentCensusPageList(page, cond, pars)
  2079. if e != nil {
  2080. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  2081. return
  2082. }
  2083. queryRegisterIds := make([]int, 0)
  2084. for i := range registerList {
  2085. queryRegisterIds = append(queryRegisterIds, registerList[i].ContractRegisterId)
  2086. }
  2087. fmt.Println("queryRegisterIds:", queryRegisterIds)
  2088. // fmt.Println("queryRegisterIds:",queryRegisterIds)
  2089. results := new(fms.NotInvoicePaymentCensusResp)
  2090. if len(queryRegisterIds) > 0 {
  2091. // 获取汇总数据IDs, 用于查询合计数据
  2092. summaryIdsCond := cond
  2093. summaryIdsPars := pars
  2094. if req.SellerIds != "" {
  2095. sellerIds := strings.Split(req.SellerIds, ",")
  2096. summaryIdsCond += ` AND c.seller_id in ? AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2097. summaryIdsPars = append(summaryIdsPars, sellerIds)
  2098. } else {
  2099. summaryIdsCond += ` AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2100. summaryIdsPars = append(summaryIdsPars)
  2101. }
  2102. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(summaryIdsCond, summaryIdsPars)
  2103. if e != nil {
  2104. resp.FailMsg("获取失败", "获取商品到款汇总IDs失败, Err: "+e.Error(), c)
  2105. return
  2106. }
  2107. // fmt.Println("summaryIds:",summaryIds)
  2108. var listErr, totalErr, totalGroupErr error
  2109. wg := sync.WaitGroup{}
  2110. // 响应列表
  2111. respList := make([]*fms.NotPaymentCensusItem, 0)
  2112. summaryList := make([]*fms.InvoicePaymentSummaryItem, 0)
  2113. wg.Add(1)
  2114. go func() {
  2115. defer wg.Done()
  2116. // 获取汇总数据
  2117. summaryCond := cond
  2118. summaryCond += ` AND a.register_id IN ?`
  2119. summaryPars := pars
  2120. summaryPars = append(summaryPars, queryRegisterIds)
  2121. if req.SellerIds != "" {
  2122. sellerIds := strings.Split(req.SellerIds, ",")
  2123. summaryCond += ` AND c.seller_id in ? AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2124. summaryPars = append(summaryPars, sellerIds)
  2125. } else {
  2126. summaryCond += ` AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2127. summaryPars = append(summaryPars)
  2128. }
  2129. summaryData, e := fms.GetInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  2130. if e != nil {
  2131. resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
  2132. return
  2133. }
  2134. summaryList = summaryData
  2135. // summaryIds := make([]int, 0)
  2136. //
  2137. // for i := range summaryList {
  2138. // //summaryIds = append(summaryIds, summaryList[i].SummaryId)
  2139. //
  2140. // }
  2141. // 货币列表
  2142. currencyOB := new(fms.CurrencyUnit)
  2143. currencyCond := `enable = 1`
  2144. currencyPars := make([]interface{}, 0)
  2145. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  2146. if e != nil {
  2147. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  2148. return
  2149. }
  2150. unitMap := make(map[string]string)
  2151. for i := range currencyList {
  2152. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  2153. }
  2154. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  2155. if e != nil {
  2156. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  2157. return
  2158. }
  2159. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  2160. for i := range sellerList {
  2161. sellerMap[sellerList[i].SellerId] = sellerList[i]
  2162. }
  2163. sellerTypeMap := map[int]int{crm.SellerDepartmentId: 1, crm.RaiSellerDepartmentId: 2}
  2164. // 重组汇总数据
  2165. summaryMap := make(map[int][]*fms.NotPaymentCensusInfo)
  2166. for i := range summaryList {
  2167. v := new(fms.NotPaymentCensusInfo)
  2168. v.InvoiceId = summaryList[i].InvoiceId
  2169. v.InvoiceDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].InvoiceDate)
  2170. v.InvoiceAmount = summaryList[i].InvoiceAmount
  2171. v.SellerId = summaryList[i].SellerId
  2172. v.SellerName = summaryList[i].SellerName
  2173. v.SellerGroupId = summaryList[i].SellerGroupId
  2174. v.SellerGroupName = summaryList[i].SellerGroupName
  2175. if seller, ok := sellerMap[summaryList[i].SellerId]; ok {
  2176. v.SellerType = sellerTypeMap[seller.DepartmentId]
  2177. }
  2178. v.PaymentId = summaryList[i].PaymentId
  2179. v.PaymentDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].PaymentDate)
  2180. v.PaymentAmount = summaryList[i].PaymentAmount
  2181. v.PayType = summaryList[i].PayType
  2182. v.NotPaymentAmount = summaryList[i].InvoiceAmount - summaryList[i].PaymentAmount
  2183. v.ServiceProductId = summaryList[i].ServiceProductId
  2184. v.UnitName = unitMap[summaryList[i].CurrencyUnit]
  2185. summaryMap[summaryList[i].SummaryId] = append(summaryMap[summaryList[i].SummaryId], v)
  2186. }
  2187. // 响应列表
  2188. for i := range registerList {
  2189. v := new(fms.NotPaymentCensusItem)
  2190. v.SummaryId = registerList[i].SummaryId
  2191. v.ContractRegisterId = registerList[i].ContractRegisterId
  2192. v.CompanyName = registerList[i].CompanyName
  2193. v.NewCompany = registerList[i].NewCompany
  2194. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  2195. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  2196. v.InvoicePaymentList = summaryMap[registerList[i].SummaryId]
  2197. v.ContractType = registerList[i].ContractType
  2198. v.ContractCode = registerList[i].ContractCode
  2199. v.ContractAmount = registerList[i].ContractAmount
  2200. v.UnitName = unitMap[registerList[i].CurrencyUnit]
  2201. v.ProductIds = registerList[i].ProductIds
  2202. v.NotInvoiceTotal = registerList[i].ContractAmount - registerList[i].InvoicedAmount
  2203. respList = append(respList, v)
  2204. }
  2205. }()
  2206. // 开票到款金额合计(换算后)
  2207. var invoiceTotal, paymentTotal float64
  2208. wg.Add(1)
  2209. go func() {
  2210. defer wg.Done()
  2211. if len(summaryIds) == 0 {
  2212. return
  2213. }
  2214. amountTotalCond := `a.id IN ?`
  2215. amountTotalPars := make([]interface{}, 0)
  2216. amountTotalPars = append(amountTotalPars, summaryIds)
  2217. invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
  2218. if e != nil {
  2219. totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
  2220. return
  2221. }
  2222. invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
  2223. paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
  2224. if e != nil {
  2225. totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
  2226. return
  2227. }
  2228. paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
  2229. }()
  2230. // 分币种金额统计
  2231. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2232. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2233. notpaymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2234. // contractAmountCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2235. wg.Add(1)
  2236. go func() {
  2237. defer wg.Done()
  2238. currencyOB := new(fms.CurrencyUnit)
  2239. currencyCond := `enable = 1`
  2240. currencyPars := make([]interface{}, 0)
  2241. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  2242. if e != nil {
  2243. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  2244. return
  2245. }
  2246. unitMap := make(map[string]string)
  2247. for i := range currencyList {
  2248. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  2249. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2250. Name: currencyList[i].Name,
  2251. UnitName: currencyList[i].UnitName,
  2252. Code: currencyList[i].Code,
  2253. FlagImg: currencyList[i].FlagImg,
  2254. })
  2255. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2256. Name: currencyList[i].Name,
  2257. UnitName: currencyList[i].UnitName,
  2258. Code: currencyList[i].Code,
  2259. FlagImg: currencyList[i].FlagImg,
  2260. })
  2261. notpaymentCurrencyTotals = append(notpaymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2262. Name: currencyList[i].Name,
  2263. UnitName: currencyList[i].UnitName,
  2264. Code: currencyList[i].Code,
  2265. FlagImg: currencyList[i].FlagImg,
  2266. })
  2267. }
  2268. if len(summaryIds) == 0 {
  2269. return
  2270. }
  2271. totalGroupCond := `a.id IN ?`
  2272. totalGroupPars := make([]interface{}, 0)
  2273. totalGroupPars = append(totalGroupPars, summaryIds)
  2274. invoiceSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 1)
  2275. if e != nil {
  2276. totalGroupErr = fmt.Errorf("获取汇总货币合计开票金额失败, Err: %s", e.Error())
  2277. return
  2278. }
  2279. paymentSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 2)
  2280. if e != nil {
  2281. totalGroupErr = fmt.Errorf("获取汇总货币合计到款金额失败, Err: %s", e.Error())
  2282. return
  2283. }
  2284. invoiceSumMap := make(map[string]float64)
  2285. paymentSumMap := make(map[string]float64)
  2286. //contractSumMap := make(map[string]float64)
  2287. for i := range invoiceSumGroup {
  2288. invoiceSumMap[invoiceSumGroup[i].CurrencyUnit] = invoiceSumGroup[i].OriginAmountTotal
  2289. continue
  2290. }
  2291. for i := range paymentSumGroup {
  2292. paymentSumMap[paymentSumGroup[i].CurrencyUnit] = paymentSumGroup[i].OriginAmountTotal
  2293. continue
  2294. }
  2295. for i := range invoiceCurrencyTotals {
  2296. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
  2297. invoiceCurrencyTotals[i].Amount = a
  2298. }
  2299. for i := range paymentCurrencyTotals {
  2300. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  2301. paymentCurrencyTotals[i].Amount = a
  2302. }
  2303. for i := range notpaymentCurrencyTotals {
  2304. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]-paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  2305. notpaymentCurrencyTotals[i].Amount = a
  2306. }
  2307. }()
  2308. wg.Wait()
  2309. if listErr != nil {
  2310. resp.FailMsg("获取失败", listErr.Error(), c)
  2311. return
  2312. }
  2313. if totalErr != nil {
  2314. resp.FailMsg("获取失败", totalErr.Error(), c)
  2315. return
  2316. }
  2317. if totalGroupErr != nil {
  2318. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  2319. return
  2320. }
  2321. results.DataList = respList
  2322. results.InvoiceTotal = invoiceTotal
  2323. results.PaymentTotal = paymentTotal
  2324. results.NotPaymentTotal = invoiceTotal - paymentTotal
  2325. results.NotPaymentCurrencyTotal = notpaymentCurrencyTotals
  2326. }
  2327. // 是否导出
  2328. if req.IsExport == 1 {
  2329. ExportNotPaymentCensusList(c, results)
  2330. return
  2331. }
  2332. page.SetTotal(total)
  2333. baseData := new(base.BaseData)
  2334. baseData.SetPage(page)
  2335. baseData.SetList(results)
  2336. resp.OkData("获取成功", baseData, c)
  2337. }
  2338. // ExportNotInvoiceCensusList 导出未开票统计列表
  2339. func ExportNotInvoiceCensusList(c *gin.Context, results *fms.NotInvoicePaymentCensusResp) {
  2340. list := results.DataList
  2341. if len(list) == 0 {
  2342. resp.Fail("列表数据为空", c)
  2343. return
  2344. }
  2345. // 生成Excel文件
  2346. xlsxFile := xlsx.NewFile()
  2347. style := xlsx.NewStyle()
  2348. alignment := xlsx.Alignment{
  2349. Horizontal: "center",
  2350. Vertical: "center",
  2351. WrapText: true,
  2352. }
  2353. style.Alignment = alignment
  2354. style.ApplyAlignment = true
  2355. sheetName := "未开票统计表"
  2356. sheet, err := xlsxFile.AddSheet(sheetName)
  2357. if err != nil {
  2358. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  2359. return
  2360. }
  2361. // 前三行-开票金额合计
  2362. rowA := sheet.AddRow()
  2363. cellAA := rowA.AddCell()
  2364. cellAA.SetString(fmt.Sprintf("未开票合计金额(换算后):%.2f(元)", results.NotInvoiceTotal))
  2365. rowBData := "未开票金额:"
  2366. for _, v := range results.NotInvoiceCurrencyTotal {
  2367. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  2368. }
  2369. rowB := sheet.AddRow()
  2370. rowB.AddCell().SetString(rowBData)
  2371. sheet.AddRow()
  2372. // 数据表头
  2373. rowTitle := []string{"序号", "客户名称", "合同编号", "合同开始时间", "合同结束时间", "合同金额", "金额单位", "未开票金额", "套餐类型", "销售", "销售组别", "销售类型"}
  2374. titleRow := sheet.AddRow()
  2375. for i := range rowTitle {
  2376. v := titleRow.AddCell()
  2377. v.SetString(rowTitle[i])
  2378. v.SetStyle(style)
  2379. }
  2380. incomeSummaryItemList := make([]*fms.NotPaymentCensusItem, 0)
  2381. incomeSummaryItemList = list
  2382. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  2383. if e != nil {
  2384. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  2385. return
  2386. }
  2387. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  2388. for i := range sellerList {
  2389. sellerMap[sellerList[i].SellerId] = sellerList[i]
  2390. }
  2391. sellerTypeMap := map[int]string{2: "FICC销售", 5: "权益销售"}
  2392. serviceProductIdMap := map[int]string{
  2393. 1: "FICC套餐",
  2394. 2: "权益套餐",
  2395. }
  2396. // 填充数据
  2397. for i, v := range incomeSummaryItemList {
  2398. dataRow := sheet.AddRow()
  2399. dataRow2 := sheet.AddRow()
  2400. cell := dataRow.AddCell()
  2401. cell.VMerge = 1
  2402. cell.SetString(strconv.Itoa(i + 1)) //序号
  2403. dataRow2.AddCell().SetString("")
  2404. cell2 := dataRow.AddCell()
  2405. cell2.VMerge = 1
  2406. cell2.SetString(v.CompanyName) // 客户名称
  2407. dataRow2.AddCell().SetString("")
  2408. cell3 := dataRow.AddCell()
  2409. cell3.VMerge = 1
  2410. cell3.SetString(v.ContractCode) // 合同编号
  2411. dataRow2.AddCell().SetString("")
  2412. cell4 := dataRow.AddCell()
  2413. cell4.VMerge = 1
  2414. cell4.SetString(v.StartDate) // 合同开始时间
  2415. dataRow2.AddCell().SetString("")
  2416. cell5 := dataRow.AddCell()
  2417. cell5.VMerge = 1
  2418. cell5.SetString(v.EndDate) // 合同结束时间
  2419. dataRow2.AddCell().SetString("")
  2420. cell6 := dataRow.AddCell()
  2421. cell6.VMerge = 1
  2422. cell6.SetString(fmt.Sprintf("%.2f", v.ContractAmount)) // 合同金额
  2423. dataRow2.AddCell().SetString("")
  2424. cell7 := dataRow.AddCell()
  2425. cell7.VMerge = 1
  2426. cell7.SetString(v.UnitName) // 金额单位
  2427. dataRow2.AddCell().SetString("")
  2428. for j, item := range v.NotInvoiceList {
  2429. if j == 1 {
  2430. dataRow2.AddCell().SetString(fmt.Sprintf("%.2f", item.NotInvoicedAmountTotal)) // 未开票金额
  2431. dataRow2.AddCell().SetString(serviceProductIdMap[item.ServiceProductId]) // 套餐类型
  2432. if item.SellerId > 0 && item.RaiSellerId > 0 {
  2433. if item.ServiceProductId == 1 {
  2434. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2435. if seller, ok := sellerMap[item.SellerId]; ok {
  2436. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2437. }
  2438. dataRow2.AddCell().SetString(item.SellerName) // 销售
  2439. dataRow2.AddCell().SetString(item.SellerGroupName) // 销售组别
  2440. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2441. } else {
  2442. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2443. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2444. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2445. }
  2446. dataRow2.AddCell().SetString(item.RaiSellerName) // 销售
  2447. dataRow2.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2448. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2449. }
  2450. } else if item.SellerId > 0 && item.RaiSellerId == 0 {
  2451. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2452. if seller, ok := sellerMap[item.SellerId]; ok {
  2453. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2454. }
  2455. dataRow2.AddCell().SetString(item.SellerName) // 销售
  2456. dataRow2.AddCell().SetString(item.SellerGroupName) // 销售组别
  2457. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2458. } else if item.SellerId == 0 && item.RaiSellerId > 0 {
  2459. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2460. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2461. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2462. }
  2463. dataRow2.AddCell().SetString(item.RaiSellerName) // 销售
  2464. dataRow2.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2465. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2466. }
  2467. } else {
  2468. dataRow.AddCell().SetString(fmt.Sprintf("%.2f", item.NotInvoicedAmountTotal)) // 未开票金额
  2469. dataRow.AddCell().SetString(serviceProductIdMap[item.ServiceProductId]) // 套餐类型
  2470. if item.SellerId > 0 && item.RaiSellerId > 0 {
  2471. if item.ServiceProductId == 1 {
  2472. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2473. if seller, ok := sellerMap[item.SellerId]; ok {
  2474. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2475. }
  2476. dataRow.AddCell().SetString(item.SellerName) // 销售
  2477. dataRow.AddCell().SetString(item.SellerGroupName) // 销售组别
  2478. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2479. } else {
  2480. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2481. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2482. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2483. }
  2484. dataRow.AddCell().SetString(item.RaiSellerName) // 销售
  2485. dataRow.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2486. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2487. }
  2488. } else if item.SellerId > 0 && item.RaiSellerId == 0 {
  2489. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2490. if seller, ok := sellerMap[item.SellerId]; ok {
  2491. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2492. }
  2493. dataRow.AddCell().SetString(item.SellerName) // 销售
  2494. dataRow.AddCell().SetString(item.SellerGroupName) // 销售组别
  2495. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2496. } else if item.SellerId == 0 && item.RaiSellerId > 0 {
  2497. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2498. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2499. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2500. }
  2501. dataRow.AddCell().SetString(item.RaiSellerName) // 销售
  2502. dataRow.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2503. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2504. }
  2505. }
  2506. }
  2507. }
  2508. // 输出文件
  2509. var buffer bytes.Buffer
  2510. _ = xlsxFile.Write(&buffer)
  2511. content := bytes.NewReader(buffer.Bytes())
  2512. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2513. fileName := sheetName + randStr + ".xlsx"
  2514. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  2515. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2516. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  2517. }
  2518. // ExportNotPaymentCensusList 导出开票未到款统计列表
  2519. func ExportNotPaymentCensusList(c *gin.Context, results *fms.NotInvoicePaymentCensusResp) {
  2520. list := results.DataList
  2521. if len(list) == 0 {
  2522. resp.Fail("列表数据为空", c)
  2523. return
  2524. }
  2525. // 生成Excel文件
  2526. xlsxFile := xlsx.NewFile()
  2527. style := xlsx.NewStyle()
  2528. alignment := xlsx.Alignment{
  2529. Horizontal: "center",
  2530. Vertical: "center",
  2531. WrapText: true,
  2532. }
  2533. style.Alignment = alignment
  2534. style.ApplyAlignment = true
  2535. sheet, err := xlsxFile.AddSheet("开票未到款统计")
  2536. if err != nil {
  2537. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  2538. return
  2539. }
  2540. _ = sheet.SetColWidth(1, 1, 30)
  2541. _ = sheet.SetColWidth(3, 3, 30)
  2542. // 前三行-开票金额合计
  2543. rowA := sheet.AddRow()
  2544. cellAA := rowA.AddCell()
  2545. cellAA.SetString(fmt.Sprintf("开票未到款合计金额(换算后):%.2f(元)", results.NotPaymentTotal))
  2546. rowBData := "开票未到款金额:"
  2547. for _, v := range results.NotPaymentCurrencyTotal {
  2548. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  2549. }
  2550. rowB := sheet.AddRow()
  2551. rowB.AddCell().SetString(rowBData)
  2552. sheet.AddRow()
  2553. // 表头, 套餐动态获取
  2554. rowTitle := []string{"序号", "客户名称", "合同编号", "合同有效期", "套餐类型", "开票日", "开票金额", "金额单位", "开票销售",
  2555. "销售组别", "销售类型"}
  2556. titleRow := sheet.AddRow()
  2557. for i := range rowTitle {
  2558. v := titleRow.AddCell()
  2559. v.SetString(rowTitle[i])
  2560. v.SetStyle(style)
  2561. }
  2562. serviceProductIdMap := map[int]string{
  2563. 1: "FICC套餐",
  2564. 2: "权益套餐",
  2565. }
  2566. sellerTypeMap := map[int]string{1: "FICC销售", 2: "权益销售"}
  2567. for k, v := range list {
  2568. dataRow := sheet.AddRow()
  2569. // 前四个单元格根据每行开票到款条数向下合并
  2570. l := len(v.InvoicePaymentList)
  2571. mergeRowNum := l - 1
  2572. // 序号
  2573. sortNum := k + 1
  2574. colA := dataRow.AddCell()
  2575. colA.VMerge = mergeRowNum
  2576. colA.SetString(fmt.Sprint(sortNum))
  2577. // 客户名称
  2578. colB := dataRow.AddCell()
  2579. colB.VMerge = mergeRowNum
  2580. colB.SetString(v.CompanyName)
  2581. // 合同编号
  2582. colC := dataRow.AddCell()
  2583. colC.VMerge = mergeRowNum
  2584. colC.SetString(v.ContractCode)
  2585. // 合同有效期
  2586. colD := dataRow.AddCell()
  2587. colD.VMerge = mergeRowNum
  2588. colD.SetString(fmt.Sprint(v.StartDate, "至", v.EndDate))
  2589. // 套餐类型
  2590. colE := dataRow.AddCell()
  2591. colE.VMerge = mergeRowNum
  2592. colE.SetString(serviceProductIdMap[v.InvoicePaymentList[0].ServiceProductId])
  2593. // 开票到款信息
  2594. for _, v2 := range v.InvoicePaymentList {
  2595. rowData := []string{
  2596. v2.InvoiceDate, // 开票日
  2597. fmt.Sprint(v2.NotPaymentAmount), // 开票金额
  2598. v2.UnitName, // 开票金额
  2599. v2.SellerName, // 销售
  2600. v2.SellerGroupName, // 组别
  2601. sellerTypeMap[v2.SellerType], // 销售类型
  2602. }
  2603. for i := range rowData {
  2604. dataRow.AddCell().SetString(rowData[i])
  2605. }
  2606. }
  2607. }
  2608. // 输出文件
  2609. var buffer bytes.Buffer
  2610. _ = xlsxFile.Write(&buffer)
  2611. content := bytes.NewReader(buffer.Bytes())
  2612. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2613. fileName := "商品到款统计_" + randStr + ".xlsx"
  2614. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  2615. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2616. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  2617. }