invoice_payment.go 101 KB

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