invoice_payment.go 116 KB

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