invoice_payment.go 104 KB

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