invoice_payment.go 116 KB

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