invoice_payment.go 101 KB

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