invoice_payment.go 101 KB

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