invoice_payment.go 101 KB

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