invoice_payment.go 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799
  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 = 1 `
  1008. historyCond += ` AND new_company = 1 `
  1009. }
  1010. var latestTime time.Time
  1011. invoiceItem, err := fms.GetLatestIncome(cond, pars)
  1012. if err != nil && err != utils.ErrNoRow {
  1013. err = fmt.Errorf("获取最新的开票或到款日期, Err: %s", err.Error())
  1014. return
  1015. }
  1016. latestTime = invoiceItem.InvoiceDate
  1017. if err == utils.ErrNoRow {
  1018. historyItem, e := fms.GetLatestHistoryIncome(historyCond, historyPars)
  1019. if e != nil && e != utils.ErrNoRow {
  1020. err = fmt.Errorf("获取最新的历史开票或到款日期, Err: %s", e.Error())
  1021. return
  1022. }
  1023. latestTime = historyItem.InvoiceDate
  1024. }
  1025. if latestTime.IsZero() {
  1026. latestTime = time.Now()
  1027. }
  1028. latestTime = latestTime.AddDate(0, 0, -latestTime.Day()+1)
  1029. var dateSlice []string
  1030. var totalMoneySlice, prevTotalMoneySlice []float64
  1031. var yoySlice []string
  1032. var yearNum, monthNum int
  1033. var reqStartDate, reqEndDate time.Time
  1034. historyTime, _ := time.Parse(utils.FormatDate, "2023-04-01")
  1035. if req.StartDate != "" && req.EndDate != "" {
  1036. st := fmt.Sprint(req.StartDate, "-01 00:00:00")
  1037. ed := fmt.Sprint(req.EndDate, "-01 23:59:59")
  1038. reqStartDate, _ = time.Parse(utils.FormatDateTime, st)
  1039. reqEndDate, _ = time.Parse(utils.FormatDateTime, ed)
  1040. if reqEndDate.After(latestTime) {
  1041. yearNum = latestTime.Year() - reqStartDate.Year()
  1042. monthNum = int(latestTime.Month() - reqStartDate.Month())
  1043. } else {
  1044. yearNum = reqEndDate.Year() - reqStartDate.Year()
  1045. monthNum = int(reqEndDate.Month() - reqStartDate.Month())
  1046. }
  1047. } else {
  1048. yearNum = latestTime.Year() - 2020
  1049. monthNum = int(latestTime.Month() - 1)
  1050. }
  1051. if yearNum < 0 {
  1052. yearNum = -yearNum
  1053. }
  1054. if monthNum < 0 {
  1055. monthNum = -monthNum
  1056. }
  1057. numMonth := yearNum*12 + monthNum //共存在多少个月
  1058. //if req.ListParam == "1" {
  1059. // numMonth = numMonth / 3
  1060. //} else if req.ListParam == "2" {
  1061. // numMonth = numMonth / 6
  1062. //} else if req.ListParam == "3" {
  1063. // numMonth = numMonth / 12
  1064. //}
  1065. // 累计值
  1066. var accumulate float64
  1067. var partAccumulate float64
  1068. var historyAccumulate float64
  1069. var partHistoryAccumulate float64
  1070. //dataList := make([]*fms.IncomeSummaryItem, 0)
  1071. //historydataList := make([]*fms.IncomeSummaryItem, 0)
  1072. fmt.Println("numMonth:", numMonth)
  1073. fmt.Println("InvoiceDate:", latestTime)
  1074. var j int
  1075. for i := 0; i <= numMonth; i++ {
  1076. //timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
  1077. var endDateTime time.Time
  1078. var prevEndDateTime time.Time
  1079. var prevStartDate, prevEndDate string
  1080. var startDate, endDate string
  1081. //开始日期
  1082. if req.StartDate != "" && req.EndDate != "" {
  1083. startDate = reqStartDate.AddDate(0, i, 0).Format("2006-01")
  1084. prevStartDate = reqStartDate.AddDate(-1, i, 0).Format("2006-01")
  1085. } else {
  1086. startDate = latestTime.AddDate(0, i-numMonth, 0).Format("2006-01")
  1087. prevStartDate = latestTime.AddDate(-1, i-numMonth, 0).Format("2006-01")
  1088. }
  1089. startDate = fmt.Sprint(startDate, "-01")
  1090. prevStartDate = fmt.Sprint(prevStartDate, "-01")
  1091. startDateTime, _ := time.Parse(utils.FormatDate, startDate)
  1092. prevStartDateTime, _ := time.Parse(utils.FormatDate, prevStartDate)
  1093. //结束日期
  1094. if req.StartDate != "" && req.EndDate != "" {
  1095. endDateTime = reqStartDate.AddDate(0, i+1, -1)
  1096. prevEndDateTime = reqStartDate.AddDate(-1, i+1, -1)
  1097. if reqEndDate.After(latestTime) {
  1098. endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
  1099. prevEndDateTime = latestTime.AddDate(-1, i-numMonth+1, -1)
  1100. }
  1101. } else {
  1102. endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
  1103. prevEndDateTime = latestTime.AddDate(-1, i-numMonth+1, -1)
  1104. }
  1105. endDate = endDateTime.Format(utils.FormatDate)
  1106. prevEndDate = prevEndDateTime.Format(utils.FormatDate)
  1107. cond := `1 = 1`
  1108. histrtyCond := `1 = 1`
  1109. pars := make([]interface{}, 0)
  1110. historyPars := make([]interface{}, 0)
  1111. prevCond := `1 = 1`
  1112. prevHistoryCond := `1 = 1`
  1113. prevPars := make([]interface{}, 0)
  1114. prevHistoryPars := make([]interface{}, 0)
  1115. if req.CompanyType == 1 {
  1116. cond += ` AND b.contract_type = 1 `
  1117. prevCond += ` AND b.contract_type = 1 `
  1118. histrtyCond += ` AND new_company = 1 `
  1119. prevHistoryCond += ` AND new_company = 1 `
  1120. } else if req.CompanyType == 2 {
  1121. cond += ` AND b.contract_type IN (2,3,4) `
  1122. prevCond += ` AND b.contract_type IN (2,3,4) `
  1123. histrtyCond += ` AND new_company = 0 `
  1124. prevHistoryCond += ` AND new_company = 0 `
  1125. }
  1126. if req.SellerIds != "" {
  1127. sellerIds := strings.Split(req.SellerIds, ",")
  1128. cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  1129. pars = append(pars, sellerIds, sellerIds)
  1130. prevCond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  1131. prevPars = append(prevPars, sellerIds, sellerIds)
  1132. histrtyCond += ` AND seller_id in ? `
  1133. prevHistoryCond += ` AND seller_id in ? `
  1134. historyPars = append(historyPars, sellerIds)
  1135. prevHistoryPars = append(prevHistoryPars, sellerIds)
  1136. }
  1137. //fmt.Println("i:",i)
  1138. //fmt.Println("j:",j)
  1139. {
  1140. //本期
  1141. st := fmt.Sprint(startDate, " 00:00:00")
  1142. ed := fmt.Sprint(endDate, " 23:59:59")
  1143. //校验日期,分段查询
  1144. if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
  1145. //全部走新查询
  1146. //fmt.Println("新查询")
  1147. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1148. pars = append(pars, st, ed, st, ed)
  1149. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1150. if e != nil {
  1151. return
  1152. }
  1153. // 开票到款金额合计(换算后)
  1154. var amountTotal float64
  1155. if len(summaryIds) > 0 {
  1156. amountCond := `a.id IN ? `
  1157. amountPars := make([]interface{}, 0)
  1158. amountPars = append(amountPars, summaryIds)
  1159. if req.SellerIds != "" {
  1160. sellerIds := strings.Split(req.SellerIds, ",")
  1161. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1162. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1163. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  1164. } else {
  1165. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1166. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1167. amountPars = append(amountPars, st, ed, st, ed)
  1168. }
  1169. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1170. if e != nil {
  1171. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1172. return
  1173. }
  1174. //dataList = append(dataList, results...)
  1175. var amountSum float64
  1176. for _, result := range results {
  1177. incomeChart.DataList = append(incomeChart.DataList, result)
  1178. amountSum += result.Amount
  1179. fmt.Println("result.Amount:", result.Amount)
  1180. }
  1181. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1182. accumulate += amountTotal
  1183. partAccumulate += amountTotal
  1184. }
  1185. if i == j || i == numMonth {
  1186. if req.ListParam == "4" {
  1187. totalMoneySlice = append(totalMoneySlice, accumulate)
  1188. if startDateTime.Month() == 12 {
  1189. accumulate = 0
  1190. }
  1191. } else if req.ListParam == "0" {
  1192. totalMoneySlice = append(totalMoneySlice, amountTotal)
  1193. } else if i > 0 || i == numMonth {
  1194. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  1195. fmt.Println("partAccumulate:", partAccumulate)
  1196. partAccumulate = 0.0
  1197. }
  1198. }
  1199. } else if endDateTime.Before(historyTime) || endDateTime.Equal(historyTime) {
  1200. //全部走旧查询
  1201. //fmt.Println("旧查询")
  1202. //fmt.Println("st:",st)
  1203. //fmt.Println("ed:",ed)
  1204. histrtyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1205. historyPars = append(historyPars, st, ed)
  1206. //fmt.Println("st:",st)
  1207. //fmt.Println("ed:",ed)
  1208. // 开票到款金额合计(换算后)
  1209. var amountTotal float64
  1210. results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
  1211. if e != nil {
  1212. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1213. return
  1214. }
  1215. var amountSum float64
  1216. //dataList = append(dataList, results...)
  1217. for _, result := range results {
  1218. incomeChart.DataList = append(incomeChart.DataList, result)
  1219. amountSum += result.Amount
  1220. }
  1221. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1222. accumulate += amountTotal
  1223. partAccumulate += amountTotal
  1224. if i == j || i == numMonth {
  1225. if req.ListParam == "4" {
  1226. totalMoneySlice = append(totalMoneySlice, accumulate)
  1227. if startDateTime.Month() == 12 {
  1228. accumulate = 0
  1229. }
  1230. } else if req.ListParam == "0" {
  1231. totalMoneySlice = append(totalMoneySlice, amountTotal)
  1232. } else if i > 0 || i == numMonth {
  1233. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  1234. partAccumulate = 0.0
  1235. }
  1236. }
  1237. //fmt.Println("partAccumulate:",partAccumulate)
  1238. }
  1239. }
  1240. { // 去年同期,用于计算同比值
  1241. prevSt := fmt.Sprint(prevStartDate, " 00:00:00") // 格式化上一年同一天的开始时间
  1242. prevEd := fmt.Sprint(prevEndDate, " 23:59:59") // 格式化上一年同一天的结束时间
  1243. // 校验日期,分段查询
  1244. if prevStartDateTime.After(historyTime) || prevStartDateTime.Equal(historyTime) {
  1245. // 全部走新查询
  1246. prevCond += ` AND ((b.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))` // 查询条件加入新的时间范围
  1247. prevPars = append(prevPars, prevSt, prevEd, prevSt, prevEd) // 添加时间参数到参数列表
  1248. prevSummaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(prevCond, prevPars) // 获取摘要ID列表
  1249. if e != nil {
  1250. return
  1251. }
  1252. // 开票到款金额合计(换算后)
  1253. var prevAmountTotal float64
  1254. if len(prevSummaryIds) > 0 {
  1255. amountCond := `a.id IN ? ` // 查询条件为ID在给定的摘要ID列表中
  1256. amountPars := make([]interface{}, 0)
  1257. amountPars = append(amountPars, prevSummaryIds) // 将摘要ID列表添加到参数列表
  1258. if req.SellerIds != "" {
  1259. sellerIds := strings.Split(req.SellerIds, ",")
  1260. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1261. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) ` // 根据卖家ID和发票/支付状态筛选时间范围
  1262. amountPars = append(amountPars, sellerIds, prevSt, prevEd, sellerIds, prevSt, prevEd) // 将卖家ID列表添加到参数列表
  1263. } else {
  1264. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1265. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))` // 根据发票/支付状态筛选时间范围
  1266. amountPars = append(amountPars, prevSt, prevEd)
  1267. }
  1268. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars) // 获取合同摘要收入金额数据
  1269. if e != nil {
  1270. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1271. return
  1272. }
  1273. var amountSum float64
  1274. //historydataList = append(historydataList, results...)
  1275. for _, result := range results {
  1276. amountSum += result.Amount // 累计收入金额
  1277. }
  1278. prevAmountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64) // 将累计金额转换为浮点数
  1279. historyAccumulate += prevAmountTotal // 累计历史金额
  1280. partHistoryAccumulate += prevAmountTotal // 累计部分历史金额
  1281. }
  1282. if i == j || i == numMonth {
  1283. if req.ListParam == "4" {
  1284. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate) // 将累计金额添加到总金额切片中
  1285. if prevStartDateTime.Month() == 12 {
  1286. historyAccumulate = 0 // 如果是去年的12月份,则将历史金额清零
  1287. }
  1288. } else if req.ListParam == "0" {
  1289. prevTotalMoneySlice = append(prevTotalMoneySlice, prevAmountTotal) // 将部分历史金额添加到总金额切片中
  1290. } else if i > 0 || i == numMonth {
  1291. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate) // 将部分历史金额添加到总金额切片中
  1292. fmt.Println("partHistoryAccumulate:", partHistoryAccumulate)
  1293. partHistoryAccumulate = 0.0 // 清零部分历史金额
  1294. }
  1295. }
  1296. } else if prevEndDateTime.Before(historyTime) || prevEndDateTime.Equal(historyTime) {
  1297. // 全部走旧查询
  1298. fmt.Println("prevSt:", prevSt)
  1299. fmt.Println("prevEd:", prevEd)
  1300. prevHistoryCond += ` AND (invoice_time BETWEEN ? AND ?)` // 查询条件加入旧的时间范围
  1301. prevHistoryPars = append(prevHistoryPars, prevSt, prevEd) // 添加时间参数到参数列表
  1302. // 开票到款金额合计(换算后)
  1303. var amountTotal float64
  1304. results, e := fms.GetIncomeHistory(prevHistoryCond, prevHistoryPars) // 获取历史收入数据
  1305. if e != nil {
  1306. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1307. return
  1308. }
  1309. //historydataList = append(historydataList, results...)
  1310. var amountSum float64
  1311. for _, result := range results {
  1312. amountSum += result.Amount // 累计收入金额
  1313. }
  1314. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64) // 将累计金额转换为浮点数
  1315. historyAccumulate += amountTotal // 累计历史金额
  1316. partHistoryAccumulate += amountTotal // 累计部分历史金额
  1317. if i == j || i == numMonth {
  1318. if req.ListParam == "4" {
  1319. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate) // 将累计金额添加到总金额切片中
  1320. if prevStartDateTime.Month() == 12 {
  1321. historyAccumulate = 0 // 如果是去年的12月份,则将历史金额清零
  1322. }
  1323. } else if req.ListParam == "0" {
  1324. prevTotalMoneySlice = append(prevTotalMoneySlice, amountTotal) // 将历史金额添加到总金额切片中
  1325. } else if i > 0 || i == numMonth {
  1326. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate) // 将部分历史金额添加到总金额切片中
  1327. fmt.Println("partHistoryAccumulate:", partHistoryAccumulate)
  1328. partHistoryAccumulate = 0.0 // 清零部分历史金额
  1329. }
  1330. }
  1331. if req.ListParam == "1" && i == j {
  1332. if i == 0 {
  1333. dateSlice = append(dateSlice, startDateTime.AddDate(0, 2, 0).Format("06/01")) // 添加下一个月份的开始日期到日期切片中
  1334. j = j + 2
  1335. } else {
  1336. dateSlice = append(dateSlice, startDateTime.AddDate(0, 3, 0).Format("06/01")) // 添加下一季度的开始日期到日期切片中
  1337. j = j + 3
  1338. }
  1339. } else if req.ListParam == "2" && i == j {
  1340. if i == 0 {
  1341. dateSlice = append(dateSlice, startDateTime.AddDate(0, 5, 0).Format("06/01")) // 添加下五个月份的开始日期到日期切片中
  1342. j = j + 5
  1343. } else {
  1344. dateSlice = append(dateSlice, startDateTime.AddDate(0, 6, 0).Format("06/01")) // 添加下半年的开始日期到日期切片中
  1345. j = j + 6
  1346. }
  1347. } else if req.ListParam == "3" && i == j {
  1348. if i == 0 {
  1349. dateSlice = append(dateSlice, startDateTime.AddDate(0, 11, 0).Format("06/01")) // 添加下十一个月份的开始日期到日期切片中
  1350. j = j + 11
  1351. } else {
  1352. dateSlice = append(dateSlice, startDateTime.AddDate(0, 12, 0).Format("06/01")) // 添加下一季度的开始日期到日期切片中
  1353. j = j + 12
  1354. }
  1355. } else if i == j {
  1356. dateSlice = append(dateSlice, startDateTime.Format("06/01")) // 添加当月开始日期到日期切片中
  1357. j++
  1358. }
  1359. }
  1360. if req.ListParam == "1" && i == j {
  1361. if i == 0 {
  1362. dateSlice = append(dateSlice, startDateTime.AddDate(0, 2, 0).Format("06/01")) // 添加下一个月份的开始日期到日期切片中
  1363. j = j + 2
  1364. } else {
  1365. dateSlice = append(dateSlice, startDateTime.AddDate(0, 3, 0).Format("06/01")) // 添加下一季度的开始日期到日期切片中
  1366. j = j + 3
  1367. }
  1368. } else if req.ListParam == "2" && i == j {
  1369. if i == 0 {
  1370. dateSlice = append(dateSlice, startDateTime.AddDate(0, 5, 0).Format("06/01")) // 添加下五个月份的开始日期到日期切片中
  1371. j = j + 5
  1372. } else {
  1373. dateSlice = append(dateSlice, startDateTime.AddDate(0, 6, 0).Format("06/01")) // 添加下半年的开始日期到日期切片中
  1374. j = j + 6
  1375. }
  1376. } else if req.ListParam == "3" && i == j {
  1377. if i == 0 {
  1378. dateSlice = append(dateSlice, startDateTime.AddDate(0, 11, 0).Format("06/01"))
  1379. j = j + 11
  1380. } else {
  1381. dateSlice = append(dateSlice, startDateTime.AddDate(0, 12, 0).Format("06/01"))
  1382. j = j + 12
  1383. }
  1384. } else if i == j {
  1385. dateSlice = append(dateSlice, startDateTime.Format("06/01"))
  1386. j++
  1387. }
  1388. }
  1389. }
  1390. fmt.Println("prevTotalMoneySlice:", len(prevTotalMoneySlice))
  1391. fmt.Println("totalMoneySlice:", len(totalMoneySlice))
  1392. if req.CompanyType != 3 {
  1393. //计算同比值
  1394. for i := range prevTotalMoneySlice {
  1395. var yoy float64
  1396. var yoyStr string
  1397. //fmt.Println("1:", prevTotalMoneySlice[i])
  1398. //fmt.Println("2:", totalMoneySlice[i])
  1399. //fmt.Println("3:", totalMoneySlice[i]-prevTotalMoneySlice[i])
  1400. totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", totalMoneySlice[i]), 64)
  1401. if prevTotalMoneySlice[i] != 0 && totalMoneySlice[i] != 0 {
  1402. yoy = (totalMoneySlice[i] - prevTotalMoneySlice[i]) / prevTotalMoneySlice[i]
  1403. yoyStr = fmt.Sprintf("%.4f", yoy)
  1404. if i == len(prevTotalMoneySlice)-1 && i > 0 && req.ListParam == "3" {
  1405. fmt.Println("totalMoneySlice[i-1]:", totalMoneySlice[i-1])
  1406. yoy = (totalMoneySlice[i] - totalMoneySlice[i-1]) / totalMoneySlice[i-1]
  1407. yoyStr = fmt.Sprintf("%.4f", yoy)
  1408. }
  1409. }
  1410. yoySlice = append(yoySlice, yoyStr)
  1411. }
  1412. } else {
  1413. // 当筛选条件是”月度“时,并且客户是”未续约“客户,展示柱形图和曲线图
  1414. // 当筛选条件是”季度“、”半年度“、”年度“、”月度统计“时,并且客户是”未续约“时,仅展示柱形图,无曲线图
  1415. // 未续约客户收入:去年同期老客户收入金额 减 当期老客户收入金额
  1416. // 移动平均值:若是10月份,计算8月,9月,10月,这三个月的收入金额平均值
  1417. for i := range prevTotalMoneySlice {
  1418. var yoy float64
  1419. var yoyStr string
  1420. //fmt.Println("1:", prevTotalMoneySlice[i])
  1421. //fmt.Println("2:", totalMoneySlice[i])
  1422. //fmt.Println("3:", totalMoneySlice[i]-prevTotalMoneySlice[i])
  1423. totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", totalMoneySlice[i] - prevTotalMoneySlice[i]), 64)
  1424. if prevTotalMoneySlice[i] != 0 && totalMoneySlice[i] != 0 {
  1425. yoy = (totalMoneySlice[i] - prevTotalMoneySlice[i]) / prevTotalMoneySlice[i]
  1426. yoyStr = fmt.Sprintf("%.4f", yoy)
  1427. if i == len(prevTotalMoneySlice)-1 && i > 0 && req.ListParam == "3" {
  1428. fmt.Println("totalMoneySlice[i-1]:", totalMoneySlice[i-1])
  1429. yoy = (totalMoneySlice[i] - totalMoneySlice[i-1]) / totalMoneySlice[i-1]
  1430. yoyStr = fmt.Sprintf("%.4f", yoy)
  1431. }
  1432. }
  1433. yoySlice = append(yoySlice, yoyStr)
  1434. }
  1435. }
  1436. incomeChart.Title = "开票到款统计图"
  1437. incomeChart.Date = dateSlice
  1438. incomeChart.TotalMoney = totalMoneySlice
  1439. incomeChart.PrevTotalMoney = prevTotalMoneySlice
  1440. incomeChart.Yoy = yoySlice
  1441. //redisJsonData, err := json.Marshal(incomeChart)
  1442. //if err == nil {
  1443. // global.Redis.SetEX(context.TODO(), key, string(redisJsonData), time.Minute*30)
  1444. //}
  1445. //} else {
  1446. // err = json.Unmarshal([]byte(redisJsonData), &incomeChart)
  1447. // if err != nil {
  1448. // fmt.Println("近两年的收入统计数据,json转换失败")
  1449. // }
  1450. //}
  1451. return
  1452. }
  1453. // ExportIncomeList 导出业务收入统计列表
  1454. func ExportIncomeList(c *gin.Context, list []*fms.IncomeSummaryItem) {
  1455. // 生成Excel文件
  1456. xlsxFile := xlsx.NewFile()
  1457. style := xlsx.NewStyle()
  1458. alignment := xlsx.Alignment{
  1459. Horizontal: "center",
  1460. Vertical: "center",
  1461. WrapText: true,
  1462. }
  1463. style.Alignment = alignment
  1464. style.ApplyAlignment = true
  1465. sheetName := "业务收入统计表"
  1466. sheet, err := xlsxFile.AddSheet(sheetName)
  1467. if err != nil {
  1468. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1469. return
  1470. }
  1471. // 数据表头
  1472. rowTitle := []string{"开票日期", "新客户(1)", "客户名称", "金额", "销售"}
  1473. titleRow := sheet.AddRow()
  1474. for i := range rowTitle {
  1475. v := titleRow.AddCell()
  1476. v.SetString(rowTitle[i])
  1477. v.SetStyle(style)
  1478. }
  1479. incomeSummaryItemList := make(fms.IncomeSummaryItemList, 0)
  1480. incomeSummaryItemList = list
  1481. sort.Sort(incomeSummaryItemList)
  1482. // 填充数据
  1483. for _, v := range incomeSummaryItemList {
  1484. dataRow := sheet.AddRow()
  1485. dataRow.AddCell().SetString(v.InvoiceDate.Format(utils.FormatDate)) // 开票日期
  1486. newCompany := 0
  1487. if v.ContractType == 1 {
  1488. newCompany = 1
  1489. }
  1490. dataRow.AddCell().SetString(strconv.Itoa(newCompany)) // 新客户
  1491. dataRow.AddCell().SetString(v.CompanyName) // 客户名称
  1492. dataRow.AddCell().SetString(fmt.Sprint(v.Amount)) // 金额
  1493. dataRow.AddCell().SetString(v.SellerName) // 销售员
  1494. }
  1495. // 输出文件
  1496. var buffer bytes.Buffer
  1497. _ = xlsxFile.Write(&buffer)
  1498. content := bytes.NewReader(buffer.Bytes())
  1499. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1500. fileName := sheetName + randStr + ".xlsx"
  1501. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1502. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1503. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1504. }
  1505. // List
  1506. // @Title 未开票统计列表
  1507. // @Description 未开票统计列表
  1508. // @Param Keyword query string false "关键词"
  1509. // @Param SellGroupId query int false "销售组别ID"
  1510. // @Param ServiceType query int false "套餐类型"
  1511. // @Param StartDate query string false "合同开始日期"
  1512. // @Param EndDate query string false "合同结束日期"
  1513. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  1514. // @Param HasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
  1515. // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
  1516. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  1517. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  1518. // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'start_date':开票日 、 'end_date':到款日"
  1519. // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
  1520. // @Success 200 {object} fms.ContractRegisterItem
  1521. // @router /census/invoice_payment/not_invoice/list [get]
  1522. func (ct *InvoicePaymentController) NotInvoiceList(c *gin.Context) {
  1523. var req fms.InvoicePaymentCensusListReq
  1524. if e := c.BindQuery(&req); e != nil {
  1525. err, ok := e.(validator.ValidationErrors)
  1526. if !ok {
  1527. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1528. return
  1529. }
  1530. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1531. return
  1532. }
  1533. cond := `1 = 1`
  1534. pars := make([]interface{}, 0)
  1535. noSummaryCond := `1 = 1`
  1536. noSummaryPars := make([]interface{}, 0)
  1537. // 客户姓名/合同编号
  1538. if req.Keyword != "" {
  1539. kw := "%" + req.Keyword + "%"
  1540. cond += ` AND (b.company_name LIKE ? OR b.contract_code LIKE ?)`
  1541. pars = append(pars, kw, kw)
  1542. noSummaryCond += ` AND (b.company_name LIKE ? OR b.contract_code LIKE ?)`
  1543. noSummaryPars = append(noSummaryPars, kw, kw)
  1544. }
  1545. if req.SellerIds != "" {
  1546. sellerIds := strings.Split(req.SellerIds, ",")
  1547. cond += ` AND (b.seller_id in ? OR b.rai_seller_id in ?)`
  1548. pars = append(pars, sellerIds, sellerIds)
  1549. noSummaryCond += ` AND (b.seller_id in ? OR b.rai_seller_id in ?)`
  1550. noSummaryPars = append(noSummaryPars, sellerIds, sellerIds)
  1551. }
  1552. // 套餐筛选
  1553. if req.ServiceTypes != "" {
  1554. serviceTypes := strings.Split(req.ServiceTypes, ",")
  1555. tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  1556. if e != nil {
  1557. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  1558. return
  1559. }
  1560. if len(tempRegisterIds) > 0 {
  1561. cond += ` AND a.register_id IN ?`
  1562. pars = append(pars, tempRegisterIds)
  1563. noSummaryCond += ` AND b.register_id IN ? `
  1564. noSummaryPars = append(noSummaryPars, tempRegisterIds)
  1565. } else {
  1566. cond += ` AND 1 = 2`
  1567. noSummaryCond += ` AND 1 = 2`
  1568. }
  1569. }
  1570. if req.ListParam == 1 {
  1571. cond += ` AND a.service_product_id = 1 `
  1572. noSummaryCond += ` AND b.product_ids = '1' `
  1573. } else if req.ListParam == 2 {
  1574. cond += ` AND a.service_product_id = 2 `
  1575. noSummaryCond += ` AND b.product_ids = '2' `
  1576. }
  1577. page := new(base.Page)
  1578. page.SetPageSize(req.PageSize)
  1579. page.SetCurrent(req.Current)
  1580. //排序
  1581. if req.SortType == "" {
  1582. req.SortType = "asc"
  1583. }
  1584. if req.SortType != "desc" && req.SortType != "asc" {
  1585. resp.Fail("排序类型不正确", c)
  1586. return
  1587. }
  1588. if req.SortParam == "" {
  1589. page.AddOrderItem(base.OrderItem{Column: "e.start_date", Asc: true})
  1590. } else if req.SortParam == "start_date" {
  1591. if req.SortType == "asc" {
  1592. page.AddOrderItem(base.OrderItem{Column: "e.start_date", Asc: true})
  1593. } else {
  1594. page.AddOrderItem(base.OrderItem{Column: "e.start_date", Asc: false})
  1595. }
  1596. } else if req.SortParam == "end_date" {
  1597. if req.SortType == "asc" {
  1598. page.AddOrderItem(base.OrderItem{Column: "e.end_date", Asc: true})
  1599. } else {
  1600. page.AddOrderItem(base.OrderItem{Column: "e.end_date", Asc: false})
  1601. }
  1602. } else {
  1603. resp.Fail("排序字段不正确", c)
  1604. return
  1605. }
  1606. if req.IsExport == 1 {
  1607. page.SetPageSize(10000)
  1608. page.SetCurrent(1)
  1609. }
  1610. //先拿到在筛选范围内的合同列表
  1611. 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 `
  1612. registerList, total, e := fms.GetInvoiceCensusPageList(page, cond, pars)
  1613. if e != nil {
  1614. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1615. return
  1616. }
  1617. queryRegisterIds := make([]int, 0)
  1618. for _, v := range registerList {
  1619. queryRegisterIds = append(queryRegisterIds, v.ContractRegisterId)
  1620. }
  1621. fmt.Println("queryRegisterIds:", queryRegisterIds)
  1622. results := new(fms.NotInvoicePaymentCensusResp)
  1623. if len(queryRegisterIds) > 0 {
  1624. // 获取合同的套餐金额信息
  1625. serviceAmountList, e := fms.GetContractServiceAmountByContractRegisterIds(queryRegisterIds)
  1626. if e != nil {
  1627. resp.FailData("获取合同的套餐金额信息失败", "Err:"+e.Error(), c)
  1628. return
  1629. }
  1630. serviceAmountMap := make(map[int]map[int]*fms.ContractServiceAmount, 0)
  1631. for _, v := range serviceAmountList {
  1632. if _, ok := serviceAmountMap[v.ContractRegisterId]; !ok {
  1633. serviceAmountMap[v.ContractRegisterId] = make(map[int]*fms.ContractServiceAmount)
  1634. }
  1635. serviceAmountMap[v.ContractRegisterId][v.ProductId] = v
  1636. }
  1637. var listErr, totalErr, totalGroupErr error
  1638. wg := sync.WaitGroup{}
  1639. // 响应列表
  1640. respList := make([]*fms.NotPaymentCensusItem, 0)
  1641. summaryList := make([]*fms.NotInvoicePaymentSummaryItem, 0)
  1642. wg.Add(1)
  1643. go func() {
  1644. defer wg.Done()
  1645. // 获取汇总数据
  1646. // 这里只能获取到有开票到款过的记录
  1647. summaryCond := cond
  1648. summaryCond += ` AND a.register_id IN ?`
  1649. summaryPars := pars
  1650. summaryPars = append(summaryPars, queryRegisterIds)
  1651. summaryData, e := fms.GetNotInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  1652. if e != nil {
  1653. resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
  1654. return
  1655. }
  1656. //fmt.Println("len(summaryData)", len(summaryData))
  1657. // 有过开票到款记录的合同ids,在后面的查询中去除
  1658. notQueryRegisterIds := make([]int, 0)
  1659. for _, v := range summaryData {
  1660. notQueryRegisterIds = append(notQueryRegisterIds, v.ContractRegisterId)
  1661. }
  1662. summaryList = summaryData
  1663. // 有开票到款过的记录map,用于在后面判断是否有过开票到款,然后补充数据
  1664. NotInvoiceSummaryMap := make(map[int][]*fms.NotInvoicePaymentSummaryItem, 0)
  1665. for _, v := range summaryList {
  1666. //fmt.Println("v2.ContractRegisterId", v.ContractRegisterId)
  1667. NotInvoiceSummaryMap[v.RegisterId] = append(NotInvoiceSummaryMap[v.RegisterId], v)
  1668. }
  1669. // 获取未进行过开票到款的合同数据,其实只用到了合同id和ProductIds用来补充不同的套餐信息
  1670. noSummaryCond += ` AND b.is_deleted = 0 AND b.contract_status <> 4 `
  1671. if len(notQueryRegisterIds) > 0 {
  1672. noSummaryCond += ` AND b.contract_register_id IN ? AND b.contract_register_id NOT IN ?`
  1673. noSummaryPars = append(noSummaryPars, queryRegisterIds, notQueryRegisterIds)
  1674. } else {
  1675. noSummaryCond += ` AND b.contract_register_id IN ? `
  1676. noSummaryPars = append(noSummaryPars, queryRegisterIds)
  1677. }
  1678. noSummaryData, e := fms.GetNoInvoicePaymentCensusData(noSummaryCond, noSummaryPars)
  1679. if e != nil {
  1680. resp.FailMsg("获取失败", "GetNoInvoicePaymentCensusData, Err: "+e.Error(), c)
  1681. return
  1682. }
  1683. //fmt.Println("len(noSummaryData)", len(noSummaryData))
  1684. //补充为完整的list,包含有汇总记录的和没有汇总记录的
  1685. summaryList = append(summaryList, noSummaryData...)
  1686. //fmt.Println("len(NotInvoiceSummaryMap):", len(NotInvoiceSummaryMap))
  1687. //遍历列表,补充数据
  1688. for _, v := range summaryList {
  1689. //fmt.Println("ProductIds:", v.ProductIds)
  1690. //fmt.Println("ContractRegisterId:", v.ContractRegisterId)
  1691. //fmt.Println("ServiceProductId:", v.ServiceProductId)
  1692. //fmt.Println("RegisterId:", v.RegisterId)
  1693. fmt.Println("len(NotInvoiceSummaryMap[v.RegisterId]):", len(NotInvoiceSummaryMap[v.ContractRegisterId]))
  1694. if (v.ProductIds == "1,2" || v.ProductIds == "2,1") && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 1 {
  1695. // 套餐是ficc权益都有的,但是只有一个套餐有过开票到款,手动补充另一个套餐的信息
  1696. if v.ServiceProductId == 1 {
  1697. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1698. item := fms.NotInvoicePaymentSummaryItem{
  1699. NotInvoicedAmountTotal: serviceAmount[2].ServiceAmount,
  1700. ServiceProductId: 2,
  1701. }
  1702. item.SellerId = v.SellerId
  1703. item.SellerName = v.SellerName
  1704. item.RaiSellerId = v.RaiSellerId
  1705. item.RaiSellerName = v.RaiSellerName
  1706. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item)
  1707. }
  1708. } else {
  1709. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1710. item := fms.NotInvoicePaymentSummaryItem{
  1711. NotInvoicedAmountTotal: serviceAmount[1].ServiceAmount,
  1712. ServiceProductId: 1,
  1713. }
  1714. item.SellerId = v.SellerId
  1715. item.SellerName = v.SellerName
  1716. item.RaiSellerId = v.RaiSellerId
  1717. item.RaiSellerName = v.RaiSellerName
  1718. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item)
  1719. }
  1720. }
  1721. } else if (v.ProductIds == "1,2" || v.ProductIds == "2,1") && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1722. // 套餐是ficc权益都有的,但是都没进行过开票到款,补充两个套餐的内容,直接用合同金额当作未开票金额即可
  1723. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1724. item1 := fms.NotInvoicePaymentSummaryItem{
  1725. NotInvoicedAmountTotal: serviceAmount[2].ServiceAmount,
  1726. ServiceProductId: 2,
  1727. }
  1728. item1.SellerId = v.SellerId
  1729. item1.SellerName = v.SellerName
  1730. item1.RaiSellerId = v.RaiSellerId
  1731. item1.RaiSellerName = v.RaiSellerName
  1732. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item1)
  1733. item2 := fms.NotInvoicePaymentSummaryItem{
  1734. NotInvoicedAmountTotal: serviceAmount[1].ServiceAmount,
  1735. ServiceProductId: 1,
  1736. }
  1737. item2.SellerId = v.SellerId
  1738. item2.SellerName = v.SellerName
  1739. item2.RaiSellerId = v.RaiSellerId
  1740. item2.RaiSellerName = v.RaiSellerName
  1741. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item2)
  1742. }
  1743. } else if v.ProductIds == "1" && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1744. // 只有ficc套餐,但是未进行过开票到款,手动补充信息
  1745. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1746. item1 := fms.NotInvoicePaymentSummaryItem{
  1747. NotInvoicedAmountTotal: serviceAmount[1].ServiceAmount,
  1748. ServiceProductId: 1,
  1749. }
  1750. item1.SellerId = v.SellerId
  1751. item1.SellerName = v.SellerName
  1752. item1.RaiSellerId = v.RaiSellerId
  1753. item1.RaiSellerName = v.RaiSellerName
  1754. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item1)
  1755. }
  1756. } else if v.ProductIds == "2" && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1757. // 只有权益套餐,但是未进行过开票到款,手动补充信息
  1758. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1759. item2 := fms.NotInvoicePaymentSummaryItem{
  1760. NotInvoicedAmountTotal: serviceAmount[2].ServiceAmount,
  1761. ServiceProductId: 2,
  1762. }
  1763. item2.SellerId = v.SellerId
  1764. item2.SellerName = v.SellerName
  1765. item2.RaiSellerId = v.RaiSellerId
  1766. item2.RaiSellerName = v.RaiSellerName
  1767. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item2)
  1768. }
  1769. }
  1770. }
  1771. // 重组汇总数据
  1772. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  1773. if e != nil {
  1774. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  1775. return
  1776. }
  1777. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  1778. for i := range sellerList {
  1779. sellerMap[sellerList[i].SellerId] = sellerList[i]
  1780. }
  1781. sellerTypeMap := map[int]string{2: "FICC销售", 5: "权益销售"}
  1782. // 货币列表
  1783. currencyOB := new(fms.CurrencyUnit)
  1784. currencyCond := `enable = 1`
  1785. currencyPars := make([]interface{}, 0)
  1786. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1787. if e != nil {
  1788. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  1789. return
  1790. }
  1791. unitMap := make(map[string]string)
  1792. for i := range currencyList {
  1793. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1794. }
  1795. for registerId, list := range NotInvoiceSummaryMap {
  1796. for _, v := range list {
  1797. //fmt.Println("v.ContractRegisterId", v.ContractRegisterId)
  1798. //fmt.Println("v.ServiceProductId:", v.ServiceProductId)
  1799. //fmt.Println("v.NotInvoicedAmountTotal:", v.NotInvoicedAmountTotal)
  1800. //fmt.Println("registerId:",registerId)
  1801. if v.NotInvoicedAmountTotal == 0 {
  1802. if v.InvoiceAmountTotal > v.PaymentAmountTotal {
  1803. // 有合规登记或补录合同过的,有serviceAmountMap信息
  1804. if _, ok := serviceAmountMap[registerId]; ok {
  1805. if _, ok2 := serviceAmountMap[registerId][v.ServiceProductId]; ok2 {
  1806. v.NotInvoicedAmountTotal = serviceAmountMap[registerId][v.ServiceProductId].ServiceAmount - v.InvoiceAmountTotal
  1807. }
  1808. } else {
  1809. // 预登记没有合同套餐金额信息
  1810. v.NotInvoicedAmountTotal = v.InvoiceAmountTotal - v.PaymentAmountTotal
  1811. }
  1812. } else {
  1813. if _, ok := serviceAmountMap[registerId]; ok {
  1814. // 有合规登记或补录合同过的,有serviceAmountMap信息
  1815. if _, ok2 := serviceAmountMap[registerId][v.ServiceProductId]; ok2 {
  1816. v.NotInvoicedAmountTotal = serviceAmountMap[registerId][v.ServiceProductId].ServiceAmount - v.PaymentAmountTotal
  1817. }
  1818. } else {
  1819. // 预登记没有合同套餐金额信息
  1820. v.NotInvoicedAmountTotal = v.PaymentAmountTotal - v.InvoiceAmountTotal
  1821. }
  1822. }
  1823. }
  1824. // 补充销售信息
  1825. if v.SellerId > 0 && v.RaiSellerId > 0 {
  1826. if v.ServiceProductId == 1 {
  1827. if seller, ok := sellerMap[v.SellerId]; ok {
  1828. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1829. v.SellerGroupId = seller.GroupId
  1830. v.SellerGroupName = seller.GroupName
  1831. }
  1832. } else {
  1833. if seller, ok := sellerMap[v.RaiSellerId]; ok {
  1834. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1835. v.RaiSellerGroupId = seller.GroupId
  1836. v.RaiSellerGroupName = seller.GroupName
  1837. }
  1838. }
  1839. } else if v.SellerId > 0 && v.RaiSellerId == 0 {
  1840. if seller, ok := sellerMap[v.SellerId]; ok {
  1841. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1842. v.SellerGroupId = seller.GroupId
  1843. v.SellerGroupName = seller.GroupName
  1844. }
  1845. } else if v.SellerId == 0 && v.RaiSellerId > 0 {
  1846. if seller, ok := sellerMap[v.RaiSellerId]; ok {
  1847. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1848. v.RaiSellerGroupId = seller.GroupId
  1849. v.RaiSellerGroupName = seller.GroupName
  1850. }
  1851. }
  1852. }
  1853. }
  1854. // 响应列表
  1855. for i := range registerList {
  1856. v := new(fms.NotPaymentCensusItem)
  1857. v.SummaryId = registerList[i].SummaryId
  1858. v.ContractRegisterId = registerList[i].ContractRegisterId
  1859. v.CompanyName = registerList[i].CompanyName
  1860. v.NewCompany = registerList[i].NewCompany
  1861. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  1862. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  1863. v.ContractType = registerList[i].ContractType
  1864. v.ContractCode = registerList[i].ContractCode
  1865. v.ContractAmount = registerList[i].ContractAmount
  1866. v.UnitName = unitMap[registerList[i].CurrencyUnit]
  1867. v.ProductIds = registerList[i].ProductIds
  1868. //if registerList[i].InvoicedAmount != 0 {
  1869. // v.NotInvoiceTotal = registerList[i].ContractAmount - registerList[i].InvoicedAmount
  1870. //} else {
  1871. // v.NotInvoiceTotal = registerList[i].ContractAmount - registerList[i].PaymentAmount
  1872. //}
  1873. v.NotInvoiceList = NotInvoiceSummaryMap[registerList[i].ContractRegisterId]
  1874. respList = append(respList, v)
  1875. }
  1876. }()
  1877. // 开票到款金额合计(换算后)V2
  1878. var invoiceTotal, contractAmount float64
  1879. wg.Add(1)
  1880. go func() {
  1881. defer wg.Done()
  1882. registerList, e := fms.GetInvoiceCensusList(cond, pars)
  1883. if e != nil {
  1884. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1885. return
  1886. }
  1887. contractIdSumMap := make(map[int]int)
  1888. for _, v := range registerList {
  1889. if v.InvoicedAmount >= v.PaymentAmount {
  1890. invoiceTotal += v.InvoicedAmount
  1891. } else if v.InvoicedAmount == 0 {
  1892. invoiceTotal += v.PaymentAmount
  1893. }
  1894. rate := v.RMBRate
  1895. if rate == 0.0 {
  1896. rate = 1.0
  1897. }
  1898. if _, ok := contractIdSumMap[v.ContractRegisterId]; !ok {
  1899. contractIdSumMap[v.ContractRegisterId] = 1
  1900. contractAmount += v.ContractAmount / rate
  1901. }
  1902. }
  1903. }()
  1904. // 分币种金额统计
  1905. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1906. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1907. contractAmountCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1908. wg.Add(1)
  1909. go func() {
  1910. defer wg.Done()
  1911. currencyOB := new(fms.CurrencyUnit)
  1912. currencyCond := `enable = 1`
  1913. currencyPars := make([]interface{}, 0)
  1914. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1915. if e != nil {
  1916. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  1917. return
  1918. }
  1919. unitMap := make(map[string]string)
  1920. for i := range currencyList {
  1921. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1922. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1923. Name: currencyList[i].Name,
  1924. UnitName: currencyList[i].UnitName,
  1925. Code: currencyList[i].Code,
  1926. FlagImg: currencyList[i].FlagImg,
  1927. })
  1928. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1929. Name: currencyList[i].Name,
  1930. UnitName: currencyList[i].UnitName,
  1931. Code: currencyList[i].Code,
  1932. FlagImg: currencyList[i].FlagImg,
  1933. })
  1934. contractAmountCurrencyTotals = append(contractAmountCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1935. Name: currencyList[i].Name,
  1936. UnitName: currencyList[i].UnitName,
  1937. Code: currencyList[i].Code,
  1938. FlagImg: currencyList[i].FlagImg,
  1939. })
  1940. }
  1941. registerList, e := fms.GetInvoiceCensusList(cond, pars)
  1942. if e != nil {
  1943. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1944. return
  1945. }
  1946. invoiceSumMap := make(map[string]float64)
  1947. contractSumMap := make(map[string]float64)
  1948. contractIdSumMap := make(map[int]int)
  1949. for _, v := range registerList {
  1950. if v.InvoiceOrigin >= v.PaymentOrigin {
  1951. invoiceSumMap[v.CurrencyUnit] += v.InvoicedAmount
  1952. } else {
  1953. invoiceSumMap[v.CurrencyUnit] += v.PaymentAmount
  1954. }
  1955. if _, ok := contractIdSumMap[v.ContractRegisterId]; !ok {
  1956. contractIdSumMap[v.ContractRegisterId] = 1
  1957. contractSumMap[v.CurrencyUnit] += v.ContractAmount
  1958. }
  1959. }
  1960. for _, v := range contractAmountCurrencyTotals {
  1961. v.Amount = contractSumMap[v.Code] - invoiceSumMap[v.Code]
  1962. v.Amount, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", v.Amount), 64)
  1963. }
  1964. }()
  1965. wg.Wait()
  1966. if listErr != nil {
  1967. resp.FailMsg("获取失败", listErr.Error(), c)
  1968. return
  1969. }
  1970. if totalErr != nil {
  1971. resp.FailMsg("获取失败", totalErr.Error(), c)
  1972. return
  1973. }
  1974. if totalGroupErr != nil {
  1975. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  1976. return
  1977. }
  1978. results.DataList = respList
  1979. results.InvoiceTotal = invoiceTotal
  1980. results.NotInvoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", contractAmount-invoiceTotal), 64)
  1981. results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  1982. results.PaymentCurrencyTotal = paymentCurrencyTotals
  1983. results.NotInvoiceCurrencyTotal = contractAmountCurrencyTotals
  1984. fmt.Println("NotInvoiceTotal:", contractAmount-invoiceTotal)
  1985. fmt.Println("contractAmount:", contractAmount)
  1986. fmt.Println("invoiceTotal:", invoiceTotal)
  1987. }
  1988. // 是否导出
  1989. if req.IsExport == 1 {
  1990. ExportNotInvoiceCensusList(c, results)
  1991. return
  1992. }
  1993. page.SetTotal(total)
  1994. baseData := new(base.BaseData)
  1995. baseData.SetPage(page)
  1996. baseData.SetList(results)
  1997. resp.OkData("获取成功", baseData, c)
  1998. }
  1999. // List
  2000. // @Title 开票未到款统计列表
  2001. // @Description 开票未到款统计列表
  2002. // @Param Keyword query string false "关键词"
  2003. // @Param SellGroupId query int false "销售组别ID"
  2004. // @Param ServiceType query int false "套餐类型"
  2005. // @Param StartDate query string false "合同开始日期"
  2006. // @Param EndDate query string false "合同结束日期"
  2007. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  2008. // @Param HasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
  2009. // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
  2010. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  2011. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  2012. // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'invoice_time':开票日 、 'payment_date':到款日"
  2013. // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
  2014. // @Success 200 {object} fms.ContractRegisterItem
  2015. // @router /census/invoice_payment/not_payment/list [get]
  2016. func (ct *InvoicePaymentController) NotPaymentList(c *gin.Context) {
  2017. var req fms.InvoicePaymentCensusListReq
  2018. if e := c.BindQuery(&req); e != nil {
  2019. err, ok := e.(validator.ValidationErrors)
  2020. if !ok {
  2021. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  2022. return
  2023. }
  2024. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  2025. return
  2026. }
  2027. cond := `1 = 1`
  2028. pars := make([]interface{}, 0)
  2029. // 客户姓名/销售
  2030. if req.Keyword != "" {
  2031. kw := "%" + req.Keyword + "%"
  2032. cond += ` AND (b.company_name LIKE ? OR b.contract_code LIKE ?)`
  2033. pars = append(pars, kw, kw)
  2034. }
  2035. if req.SellerIds != "" {
  2036. sellerIds := strings.Split(req.SellerIds, ",")
  2037. cond += ` AND (c.seller_id in ?)`
  2038. pars = append(pars, sellerIds)
  2039. }
  2040. // 套餐筛选
  2041. if req.ServiceTypes != "" {
  2042. serviceTypes := strings.Split(req.ServiceTypes, ",")
  2043. tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  2044. if e != nil {
  2045. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  2046. return
  2047. }
  2048. if len(tempRegisterIds) > 0 {
  2049. cond += ` AND a.register_id IN ?`
  2050. pars = append(pars, tempRegisterIds)
  2051. } else {
  2052. cond += ` AND 1 = 2`
  2053. }
  2054. }
  2055. if req.ListParam == 1 {
  2056. cond += ` AND a.service_product_id = 1 `
  2057. } else if req.ListParam == 2 {
  2058. cond += ` AND a.service_product_id = 2 `
  2059. }
  2060. page := new(base.Page)
  2061. page.SetPageSize(req.PageSize)
  2062. page.SetCurrent(req.Current)
  2063. //排序
  2064. if req.SortType == "" {
  2065. req.SortType = "asc"
  2066. }
  2067. if req.SortType != "desc" && req.SortType != "asc" {
  2068. resp.Fail("排序类型不正确", c)
  2069. return
  2070. }
  2071. if req.SortType == "asc" {
  2072. page.AddOrderItem(base.OrderItem{Column: "e.invoice_time", Asc: true})
  2073. page.AddOrderItem(base.OrderItem{Column: "e.modify_time", Asc: false})
  2074. } else {
  2075. page.AddOrderItem(base.OrderItem{Column: "e.invoice_time", Asc: false})
  2076. page.AddOrderItem(base.OrderItem{Column: "e.modify_time", Asc: false})
  2077. }
  2078. if req.IsExport == 1 {
  2079. page.SetPageSize(10000)
  2080. page.SetCurrent(1)
  2081. }
  2082. cond += ` AND b.payment_amount <> b.invoiced_amount AND b.is_deleted = 0 AND b.contract_status <> 4 `
  2083. registerList, total, e := fms.GetNoPaymentCensusPageList(page, cond, pars)
  2084. if e != nil {
  2085. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  2086. return
  2087. }
  2088. queryRegisterIds := make([]int, 0)
  2089. for i := range registerList {
  2090. queryRegisterIds = append(queryRegisterIds, registerList[i].ContractRegisterId)
  2091. }
  2092. fmt.Println("queryRegisterIds:", queryRegisterIds)
  2093. //fmt.Println("queryRegisterIds:",queryRegisterIds)
  2094. results := new(fms.NotInvoicePaymentCensusResp)
  2095. if len(queryRegisterIds) > 0 {
  2096. // 获取汇总数据IDs, 用于查询合计数据
  2097. summaryIdsCond := cond
  2098. summaryIdsPars := pars
  2099. if req.SellerIds != "" {
  2100. sellerIds := strings.Split(req.SellerIds, ",")
  2101. summaryIdsCond += ` AND c.seller_id in ? AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2102. summaryIdsPars = append(summaryIdsPars, sellerIds)
  2103. } else {
  2104. summaryIdsCond += ` AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2105. summaryIdsPars = append(summaryIdsPars)
  2106. }
  2107. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(summaryIdsCond, summaryIdsPars)
  2108. if e != nil {
  2109. resp.FailMsg("获取失败", "获取商品到款汇总IDs失败, Err: "+e.Error(), c)
  2110. return
  2111. }
  2112. //fmt.Println("summaryIds:",summaryIds)
  2113. var listErr, totalErr, totalGroupErr error
  2114. wg := sync.WaitGroup{}
  2115. // 响应列表
  2116. respList := make([]*fms.NotPaymentCensusItem, 0)
  2117. summaryList := make([]*fms.InvoicePaymentSummaryItem, 0)
  2118. wg.Add(1)
  2119. go func() {
  2120. defer wg.Done()
  2121. // 获取汇总数据
  2122. summaryCond := cond
  2123. summaryCond += ` AND a.register_id IN ?`
  2124. summaryPars := pars
  2125. summaryPars = append(summaryPars, queryRegisterIds)
  2126. if req.SellerIds != "" {
  2127. sellerIds := strings.Split(req.SellerIds, ",")
  2128. summaryCond += ` AND c.seller_id in ? AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2129. summaryPars = append(summaryPars, sellerIds)
  2130. } else {
  2131. summaryCond += ` AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2132. summaryPars = append(summaryPars)
  2133. }
  2134. summaryData, e := fms.GetInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  2135. if e != nil {
  2136. resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
  2137. return
  2138. }
  2139. summaryList = summaryData
  2140. //summaryIds := make([]int, 0)
  2141. //for i := range summaryList {
  2142. // //summaryIds = append(summaryIds, summaryList[i].SummaryId)
  2143. //
  2144. //}
  2145. // 货币列表
  2146. currencyOB := new(fms.CurrencyUnit)
  2147. currencyCond := `enable = 1`
  2148. currencyPars := make([]interface{}, 0)
  2149. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  2150. if e != nil {
  2151. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  2152. return
  2153. }
  2154. unitMap := make(map[string]string)
  2155. for i := range currencyList {
  2156. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  2157. }
  2158. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  2159. if e != nil {
  2160. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  2161. return
  2162. }
  2163. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  2164. for i := range sellerList {
  2165. sellerMap[sellerList[i].SellerId] = sellerList[i]
  2166. }
  2167. sellerTypeMap := map[int]int{crm.SellerDepartmentId: 1, crm.RaiSellerDepartmentId: 2}
  2168. // 重组汇总数据
  2169. summaryMap := make(map[int][]*fms.NotPaymentCensusInfo)
  2170. for i := range summaryList {
  2171. v := new(fms.NotPaymentCensusInfo)
  2172. v.InvoiceId = summaryList[i].InvoiceId
  2173. v.InvoiceDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].InvoiceDate)
  2174. v.InvoiceAmount = summaryList[i].InvoiceAmount
  2175. v.SellerId = summaryList[i].SellerId
  2176. v.SellerName = summaryList[i].SellerName
  2177. v.SellerGroupId = summaryList[i].SellerGroupId
  2178. v.SellerGroupName = summaryList[i].SellerGroupName
  2179. if seller, ok := sellerMap[summaryList[i].SellerId]; ok {
  2180. v.SellerType = sellerTypeMap[seller.DepartmentId]
  2181. }
  2182. v.PaymentId = summaryList[i].PaymentId
  2183. v.PaymentDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].PaymentDate)
  2184. v.PaymentAmount = summaryList[i].PaymentAmount
  2185. v.PayType = summaryList[i].PayType
  2186. v.NotPaymentAmount = summaryList[i].InvoiceAmount - summaryList[i].PaymentAmount
  2187. v.ServiceProductId = summaryList[i].ServiceProductId
  2188. v.UnitName = unitMap[summaryList[i].CurrencyUnit]
  2189. summaryMap[summaryList[i].SummaryId] = append(summaryMap[summaryList[i].SummaryId], v)
  2190. }
  2191. // 响应列表
  2192. for i := range registerList {
  2193. v := new(fms.NotPaymentCensusItem)
  2194. v.SummaryId = registerList[i].SummaryId
  2195. v.ContractRegisterId = registerList[i].ContractRegisterId
  2196. v.CompanyName = registerList[i].CompanyName
  2197. v.NewCompany = registerList[i].NewCompany
  2198. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  2199. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  2200. v.InvoicePaymentList = summaryMap[registerList[i].SummaryId]
  2201. v.ContractType = registerList[i].ContractType
  2202. v.ContractCode = registerList[i].ContractCode
  2203. v.ContractAmount = registerList[i].ContractAmount
  2204. v.UnitName = unitMap[registerList[i].CurrencyUnit]
  2205. v.ProductIds = registerList[i].ProductIds
  2206. respList = append(respList, v)
  2207. }
  2208. }()
  2209. // 开票到款金额合计(换算后)
  2210. var invoiceTotal, paymentTotal float64
  2211. wg.Add(1)
  2212. go func() {
  2213. defer wg.Done()
  2214. if len(summaryIds) == 0 {
  2215. return
  2216. }
  2217. amountTotalCond := `a.id IN ?`
  2218. amountTotalPars := make([]interface{}, 0)
  2219. amountTotalPars = append(amountTotalPars, summaryIds)
  2220. invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
  2221. if e != nil {
  2222. totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
  2223. return
  2224. }
  2225. invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
  2226. paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
  2227. if e != nil {
  2228. totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
  2229. return
  2230. }
  2231. paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
  2232. }()
  2233. // 分币种金额统计
  2234. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2235. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2236. notpaymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2237. //contractAmountCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2238. wg.Add(1)
  2239. go func() {
  2240. defer wg.Done()
  2241. currencyOB := new(fms.CurrencyUnit)
  2242. currencyCond := `enable = 1`
  2243. currencyPars := make([]interface{}, 0)
  2244. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  2245. if e != nil {
  2246. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  2247. return
  2248. }
  2249. unitMap := make(map[string]string)
  2250. for i := range currencyList {
  2251. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  2252. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2253. Name: currencyList[i].Name,
  2254. UnitName: currencyList[i].UnitName,
  2255. Code: currencyList[i].Code,
  2256. FlagImg: currencyList[i].FlagImg,
  2257. })
  2258. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2259. Name: currencyList[i].Name,
  2260. UnitName: currencyList[i].UnitName,
  2261. Code: currencyList[i].Code,
  2262. FlagImg: currencyList[i].FlagImg,
  2263. })
  2264. notpaymentCurrencyTotals = append(notpaymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2265. Name: currencyList[i].Name,
  2266. UnitName: currencyList[i].UnitName,
  2267. Code: currencyList[i].Code,
  2268. FlagImg: currencyList[i].FlagImg,
  2269. })
  2270. }
  2271. if len(summaryIds) == 0 {
  2272. return
  2273. }
  2274. totalGroupCond := `a.id IN ?`
  2275. totalGroupPars := make([]interface{}, 0)
  2276. totalGroupPars = append(totalGroupPars, summaryIds)
  2277. invoiceSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 1)
  2278. if e != nil {
  2279. totalGroupErr = fmt.Errorf("获取汇总货币合计开票金额失败, Err: %s", e.Error())
  2280. return
  2281. }
  2282. paymentSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 2)
  2283. if e != nil {
  2284. totalGroupErr = fmt.Errorf("获取汇总货币合计到款金额失败, Err: %s", e.Error())
  2285. return
  2286. }
  2287. invoiceSumMap := make(map[string]float64)
  2288. paymentSumMap := make(map[string]float64)
  2289. //contractSumMap := make(map[string]float64)
  2290. for i := range invoiceSumGroup {
  2291. invoiceSumMap[invoiceSumGroup[i].CurrencyUnit] = invoiceSumGroup[i].OriginAmountTotal
  2292. continue
  2293. }
  2294. for i := range paymentSumGroup {
  2295. paymentSumMap[paymentSumGroup[i].CurrencyUnit] = paymentSumGroup[i].OriginAmountTotal
  2296. continue
  2297. }
  2298. for i := range invoiceCurrencyTotals {
  2299. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
  2300. invoiceCurrencyTotals[i].Amount = a
  2301. }
  2302. for i := range paymentCurrencyTotals {
  2303. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  2304. paymentCurrencyTotals[i].Amount = a
  2305. }
  2306. for i := range notpaymentCurrencyTotals {
  2307. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]-paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  2308. notpaymentCurrencyTotals[i].Amount = a
  2309. }
  2310. }()
  2311. wg.Wait()
  2312. if listErr != nil {
  2313. resp.FailMsg("获取失败", listErr.Error(), c)
  2314. return
  2315. }
  2316. if totalErr != nil {
  2317. resp.FailMsg("获取失败", totalErr.Error(), c)
  2318. return
  2319. }
  2320. if totalGroupErr != nil {
  2321. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  2322. return
  2323. }
  2324. results.DataList = respList
  2325. results.InvoiceTotal = invoiceTotal
  2326. results.PaymentTotal = paymentTotal
  2327. results.NotPaymentTotal = invoiceTotal - paymentTotal
  2328. results.NotPaymentCurrencyTotal = notpaymentCurrencyTotals
  2329. }
  2330. // 是否导出
  2331. if req.IsExport == 1 {
  2332. ExportNotPaymentCensusList(c, results)
  2333. return
  2334. }
  2335. page.SetTotal(total)
  2336. baseData := new(base.BaseData)
  2337. baseData.SetPage(page)
  2338. baseData.SetList(results)
  2339. resp.OkData("获取成功", baseData, c)
  2340. }
  2341. // ExportNotInvoiceCensusList 导出未开票统计列表
  2342. func ExportNotInvoiceCensusList(c *gin.Context, results *fms.NotInvoicePaymentCensusResp) {
  2343. list := results.DataList
  2344. if len(list) == 0 {
  2345. resp.Fail("列表数据为空", c)
  2346. return
  2347. }
  2348. // 生成Excel文件
  2349. xlsxFile := xlsx.NewFile()
  2350. style := xlsx.NewStyle()
  2351. alignment := xlsx.Alignment{
  2352. Horizontal: "center",
  2353. Vertical: "center",
  2354. WrapText: true,
  2355. }
  2356. style.Alignment = alignment
  2357. style.ApplyAlignment = true
  2358. sheetName := "未开票统计表"
  2359. sheet, err := xlsxFile.AddSheet(sheetName)
  2360. if err != nil {
  2361. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  2362. return
  2363. }
  2364. // 前三行-开票金额合计
  2365. rowA := sheet.AddRow()
  2366. cellAA := rowA.AddCell()
  2367. cellAA.SetString(fmt.Sprintf("未开票合计金额(换算后):%.2f(元)", results.NotInvoiceTotal))
  2368. rowBData := "未开票金额:"
  2369. for _, v := range results.NotInvoiceCurrencyTotal {
  2370. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  2371. }
  2372. rowB := sheet.AddRow()
  2373. rowB.AddCell().SetString(rowBData)
  2374. sheet.AddRow()
  2375. // 数据表头
  2376. rowTitle := []string{"序号", "客户名称", "合同编号", "合同开始时间", "合同结束时间", "合同金额", "金额单位", "未开票金额", "套餐类型", "销售", "销售组别", "销售类型"}
  2377. titleRow := sheet.AddRow()
  2378. for i := range rowTitle {
  2379. v := titleRow.AddCell()
  2380. v.SetString(rowTitle[i])
  2381. v.SetStyle(style)
  2382. }
  2383. incomeSummaryItemList := make([]*fms.NotPaymentCensusItem, 0)
  2384. incomeSummaryItemList = list
  2385. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  2386. if e != nil {
  2387. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  2388. return
  2389. }
  2390. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  2391. for i := range sellerList {
  2392. sellerMap[sellerList[i].SellerId] = sellerList[i]
  2393. }
  2394. sellerTypeMap := map[int]string{2: "FICC销售", 5: "权益销售"}
  2395. serviceProductIdMap := map[int]string{
  2396. 1: "FICC套餐",
  2397. 2: "权益套餐",
  2398. }
  2399. // 填充数据
  2400. for i, v := range incomeSummaryItemList {
  2401. dataRow := sheet.AddRow()
  2402. dataRow2 := sheet.AddRow()
  2403. cell := dataRow.AddCell()
  2404. cell.VMerge = 1
  2405. cell.SetString(strconv.Itoa(i + 1)) //序号
  2406. dataRow2.AddCell().SetString("")
  2407. cell2 := dataRow.AddCell()
  2408. cell2.VMerge = 1
  2409. cell2.SetString(v.CompanyName) // 客户名称
  2410. dataRow2.AddCell().SetString("")
  2411. cell3 := dataRow.AddCell()
  2412. cell3.VMerge = 1
  2413. cell3.SetString(v.ContractCode) // 合同编号
  2414. dataRow2.AddCell().SetString("")
  2415. cell4 := dataRow.AddCell()
  2416. cell4.VMerge = 1
  2417. cell4.SetString(v.StartDate) // 合同开始时间
  2418. dataRow2.AddCell().SetString("")
  2419. cell5 := dataRow.AddCell()
  2420. cell5.VMerge = 1
  2421. cell5.SetString(v.EndDate) // 合同结束时间
  2422. dataRow2.AddCell().SetString("")
  2423. cell6 := dataRow.AddCell()
  2424. cell6.VMerge = 1
  2425. cell6.SetString(fmt.Sprintf("%.2f", v.ContractAmount)) // 合同金额
  2426. dataRow2.AddCell().SetString("")
  2427. cell7 := dataRow.AddCell()
  2428. cell7.VMerge = 1
  2429. cell7.SetString(v.UnitName) // 金额单位
  2430. dataRow2.AddCell().SetString("")
  2431. for j, item := range v.NotInvoiceList {
  2432. if j == 1 {
  2433. dataRow2.AddCell().SetString(fmt.Sprintf("%.2f", item.NotInvoicedAmountTotal)) // 未开票金额
  2434. dataRow2.AddCell().SetString(serviceProductIdMap[item.ServiceProductId]) // 套餐类型
  2435. if item.SellerId > 0 && item.RaiSellerId > 0 {
  2436. if item.ServiceProductId == 1 {
  2437. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2438. if seller, ok := sellerMap[item.SellerId]; ok {
  2439. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2440. }
  2441. dataRow2.AddCell().SetString(item.SellerName) // 销售
  2442. dataRow2.AddCell().SetString(item.SellerGroupName) // 销售组别
  2443. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2444. } else {
  2445. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2446. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2447. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2448. }
  2449. dataRow2.AddCell().SetString(item.RaiSellerName) // 销售
  2450. dataRow2.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2451. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2452. }
  2453. } else if item.SellerId > 0 && item.RaiSellerId == 0 {
  2454. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2455. if seller, ok := sellerMap[item.SellerId]; ok {
  2456. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2457. }
  2458. dataRow2.AddCell().SetString(item.SellerName) // 销售
  2459. dataRow2.AddCell().SetString(item.SellerGroupName) // 销售组别
  2460. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2461. } else if item.SellerId == 0 && item.RaiSellerId > 0 {
  2462. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2463. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2464. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2465. }
  2466. dataRow2.AddCell().SetString(item.RaiSellerName) // 销售
  2467. dataRow2.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2468. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2469. }
  2470. } else {
  2471. dataRow.AddCell().SetString(fmt.Sprintf("%.2f", item.NotInvoicedAmountTotal)) // 未开票金额
  2472. dataRow.AddCell().SetString(serviceProductIdMap[item.ServiceProductId]) // 套餐类型
  2473. if item.SellerId > 0 && item.RaiSellerId > 0 {
  2474. if item.ServiceProductId == 1 {
  2475. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2476. if seller, ok := sellerMap[item.SellerId]; ok {
  2477. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2478. }
  2479. dataRow.AddCell().SetString(item.SellerName) // 销售
  2480. dataRow.AddCell().SetString(item.SellerGroupName) // 销售组别
  2481. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2482. } else {
  2483. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2484. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2485. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2486. }
  2487. dataRow.AddCell().SetString(item.RaiSellerName) // 销售
  2488. dataRow.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2489. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2490. }
  2491. } else if item.SellerId > 0 && item.RaiSellerId == 0 {
  2492. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2493. if seller, ok := sellerMap[item.SellerId]; ok {
  2494. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2495. }
  2496. dataRow.AddCell().SetString(item.SellerName) // 销售
  2497. dataRow.AddCell().SetString(item.SellerGroupName) // 销售组别
  2498. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2499. } else if item.SellerId == 0 && item.RaiSellerId > 0 {
  2500. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2501. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2502. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2503. }
  2504. dataRow.AddCell().SetString(item.RaiSellerName) // 销售
  2505. dataRow.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2506. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2507. }
  2508. }
  2509. }
  2510. }
  2511. // 输出文件
  2512. var buffer bytes.Buffer
  2513. _ = xlsxFile.Write(&buffer)
  2514. content := bytes.NewReader(buffer.Bytes())
  2515. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2516. fileName := sheetName + randStr + ".xlsx"
  2517. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  2518. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2519. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  2520. }
  2521. // ExportNotPaymentCensusList 导出开票未到款统计列表
  2522. func ExportNotPaymentCensusList(c *gin.Context, results *fms.NotInvoicePaymentCensusResp) {
  2523. list := results.DataList
  2524. if len(list) == 0 {
  2525. resp.Fail("列表数据为空", c)
  2526. return
  2527. }
  2528. // 生成Excel文件
  2529. xlsxFile := xlsx.NewFile()
  2530. style := xlsx.NewStyle()
  2531. alignment := xlsx.Alignment{
  2532. Horizontal: "center",
  2533. Vertical: "center",
  2534. WrapText: true,
  2535. }
  2536. style.Alignment = alignment
  2537. style.ApplyAlignment = true
  2538. sheet, err := xlsxFile.AddSheet("开票未到款统计")
  2539. if err != nil {
  2540. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  2541. return
  2542. }
  2543. _ = sheet.SetColWidth(1, 1, 30)
  2544. _ = sheet.SetColWidth(3, 3, 30)
  2545. // 前三行-开票金额合计
  2546. rowA := sheet.AddRow()
  2547. cellAA := rowA.AddCell()
  2548. cellAA.SetString(fmt.Sprintf("开票未到款合计金额(换算后):%.2f(元)", results.NotPaymentTotal))
  2549. rowBData := "开票未到款金额:"
  2550. for _, v := range results.NotPaymentCurrencyTotal {
  2551. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  2552. }
  2553. rowB := sheet.AddRow()
  2554. rowB.AddCell().SetString(rowBData)
  2555. sheet.AddRow()
  2556. // 表头, 套餐动态获取
  2557. rowTitle := []string{"序号", "客户名称", "合同编号", "合同有效期", "套餐类型", "开票日", "开票金额", "金额单位", "开票销售",
  2558. "销售组别", "销售类型"}
  2559. titleRow := sheet.AddRow()
  2560. for i := range rowTitle {
  2561. v := titleRow.AddCell()
  2562. v.SetString(rowTitle[i])
  2563. v.SetStyle(style)
  2564. }
  2565. serviceProductIdMap := map[int]string{
  2566. 1: "FICC套餐",
  2567. 2: "权益套餐",
  2568. }
  2569. sellerTypeMap := map[int]string{1: "FICC销售", 2: "权益销售"}
  2570. for k, v := range list {
  2571. dataRow := sheet.AddRow()
  2572. // 前四个单元格根据每行开票到款条数向下合并
  2573. l := len(v.InvoicePaymentList)
  2574. mergeRowNum := l - 1
  2575. // 序号
  2576. sortNum := k + 1
  2577. colA := dataRow.AddCell()
  2578. colA.VMerge = mergeRowNum
  2579. colA.SetString(fmt.Sprint(sortNum))
  2580. // 客户名称
  2581. colB := dataRow.AddCell()
  2582. colB.VMerge = mergeRowNum
  2583. colB.SetString(v.CompanyName)
  2584. // 合同编号
  2585. colC := dataRow.AddCell()
  2586. colC.VMerge = mergeRowNum
  2587. colC.SetString(v.ContractCode)
  2588. // 合同有效期
  2589. colD := dataRow.AddCell()
  2590. colD.VMerge = mergeRowNum
  2591. colD.SetString(fmt.Sprint(v.StartDate, "至", v.EndDate))
  2592. // 套餐类型
  2593. colE := dataRow.AddCell()
  2594. colE.VMerge = mergeRowNum
  2595. colE.SetString(serviceProductIdMap[v.InvoicePaymentList[0].ServiceProductId])
  2596. // 开票到款信息
  2597. for _, v2 := range v.InvoicePaymentList {
  2598. rowData := []string{
  2599. v2.InvoiceDate, // 开票日
  2600. fmt.Sprint(v2.NotPaymentAmount), // 开票金额
  2601. v2.UnitName, // 开票金额
  2602. v2.SellerName, // 销售
  2603. v2.SellerGroupName, // 组别
  2604. sellerTypeMap[v2.SellerType], // 销售类型
  2605. }
  2606. for i := range rowData {
  2607. dataRow.AddCell().SetString(rowData[i])
  2608. }
  2609. }
  2610. }
  2611. // 输出文件
  2612. var buffer bytes.Buffer
  2613. _ = xlsxFile.Write(&buffer)
  2614. content := bytes.NewReader(buffer.Bytes())
  2615. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2616. fileName := "商品到款统计_" + randStr + ".xlsx"
  2617. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  2618. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2619. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  2620. }