invoice_payment.go 95 KB

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