invoice_payment.go 100 KB

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