invoice_payment.go 105 KB

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