invoice_payment.go 98 KB

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