invoice_payment.go 100 KB

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