invoice_payment.go 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737
  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", e.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. //先拿到在筛选范围内的合同列表
  1552. cond += ` AND b.contract_amount <> b.invoiced_amount AND b.is_deleted = 0 AND b.contract_amount <> b.payment_amount AND b.contract_status <> 4 `
  1553. registerList, total, e := fms.GetInvoiceCensusPageList(page, cond, pars)
  1554. if e != nil {
  1555. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1556. return
  1557. }
  1558. queryRegisterIds := make([]int, 0)
  1559. for _, v := range registerList {
  1560. queryRegisterIds = append(queryRegisterIds, v.ContractRegisterId)
  1561. }
  1562. fmt.Println("queryRegisterIds:", queryRegisterIds)
  1563. results := new(fms.NotInvoicePaymentCensusResp)
  1564. if len(queryRegisterIds) > 0 {
  1565. // 获取合同的套餐金额信息
  1566. serviceAmountList, e := fms.GetContractServiceAmountByContractRegisterIds(queryRegisterIds)
  1567. if e != nil {
  1568. resp.FailData("获取合同的套餐金额信息失败", "Err:"+e.Error(), c)
  1569. return
  1570. }
  1571. serviceAmountMap := make(map[int]map[int]*fms.ContractServiceAmount, 0)
  1572. for _, v := range serviceAmountList {
  1573. if _, ok := serviceAmountMap[v.ContractRegisterId]; !ok {
  1574. serviceAmountMap[v.ContractRegisterId] = make(map[int]*fms.ContractServiceAmount)
  1575. }
  1576. serviceAmountMap[v.ContractRegisterId][v.ProductId] = v
  1577. }
  1578. var listErr, totalErr, totalGroupErr error
  1579. wg := sync.WaitGroup{}
  1580. // 响应列表
  1581. respList := make([]*fms.NotPaymentCensusItem, 0)
  1582. summaryList := make([]*fms.NotInvoicePaymentSummaryItem, 0)
  1583. wg.Add(1)
  1584. go func() {
  1585. defer wg.Done()
  1586. // 获取汇总数据
  1587. // 这里只能获取到有开票到款过的记录
  1588. summaryCond := cond
  1589. summaryCond += ` AND a.register_id IN ?`
  1590. summaryPars := pars
  1591. summaryPars = append(summaryPars, queryRegisterIds)
  1592. summaryData, e := fms.GetNotInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  1593. if e != nil {
  1594. resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
  1595. return
  1596. }
  1597. //fmt.Println("len(summaryData)", len(summaryData))
  1598. // 有过开票到款记录的合同ids,在后面的查询中去除
  1599. notQueryRegisterIds := make([]int, 0)
  1600. for _, v := range summaryData {
  1601. notQueryRegisterIds = append(notQueryRegisterIds, v.ContractRegisterId)
  1602. }
  1603. summaryList = summaryData
  1604. // 有开票到款过的记录map,用于在后面判断是否有过开票到款,然后补充数据
  1605. NotInvoiceSummaryMap := make(map[int][]*fms.NotInvoicePaymentSummaryItem, 0)
  1606. for _, v := range summaryList {
  1607. //fmt.Println("v2.ContractRegisterId", v.ContractRegisterId)
  1608. NotInvoiceSummaryMap[v.RegisterId] = append(NotInvoiceSummaryMap[v.RegisterId], v)
  1609. }
  1610. // 获取未进行过开票到款的合同数据,其实只用到了合同id和ProductIds用来补充不同的套餐信息
  1611. noSummaryCond += ` AND b.is_deleted = 0 AND b.contract_status <> 4 `
  1612. if len(notQueryRegisterIds) >0 {
  1613. noSummaryCond += ` AND b.contract_register_id IN ? AND b.contract_register_id NOT IN ?`
  1614. noSummaryPars = append(noSummaryPars, queryRegisterIds, notQueryRegisterIds)
  1615. } else {
  1616. noSummaryCond += ` AND b.contract_register_id IN ? `
  1617. noSummaryPars = append(noSummaryPars, queryRegisterIds)
  1618. }
  1619. noSummaryData, e := fms.GetNoInvoicePaymentCensusData(noSummaryCond, noSummaryPars)
  1620. if e != nil {
  1621. resp.FailMsg("获取失败", "GetNoInvoicePaymentCensusData, Err: "+e.Error(), c)
  1622. return
  1623. }
  1624. //fmt.Println("len(noSummaryData)", len(noSummaryData))
  1625. //补充为完整的list,包含有汇总记录的和没有汇总记录的
  1626. summaryList = append(summaryList, noSummaryData...)
  1627. //fmt.Println("len(NotInvoiceSummaryMap):", len(NotInvoiceSummaryMap))
  1628. //遍历列表,补充数据
  1629. for _, v := range summaryList {
  1630. //fmt.Println("ProductIds:", v.ProductIds)
  1631. //fmt.Println("ContractRegisterId:", v.ContractRegisterId)
  1632. //fmt.Println("ServiceProductId:", v.ServiceProductId)
  1633. //fmt.Println("RegisterId:", v.RegisterId)
  1634. fmt.Println("len(NotInvoiceSummaryMap[v.RegisterId]):", len(NotInvoiceSummaryMap[v.ContractRegisterId]))
  1635. if (v.ProductIds == "1,2" || v.ProductIds == "2,1") && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 1 {
  1636. // 套餐是ficc权益都有的,但是只有一个套餐有过开票到款,手动补充另一个套餐的信息
  1637. if v.ServiceProductId == 1 {
  1638. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1639. item := fms.NotInvoicePaymentSummaryItem{
  1640. NotInvoicedAmountTotal: serviceAmount[2].ServiceAmount,
  1641. ServiceProductId: 2,
  1642. }
  1643. item.SellerId = v.SellerId
  1644. item.SellerName = v.SellerName
  1645. item.RaiSellerId = v.RaiSellerId
  1646. item.RaiSellerName = v.RaiSellerName
  1647. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item)
  1648. }
  1649. } else {
  1650. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1651. item := fms.NotInvoicePaymentSummaryItem{
  1652. NotInvoicedAmountTotal: serviceAmount[1].ServiceAmount,
  1653. ServiceProductId: 1,
  1654. }
  1655. item.SellerId = v.SellerId
  1656. item.SellerName = v.SellerName
  1657. item.RaiSellerId = v.RaiSellerId
  1658. item.RaiSellerName = v.RaiSellerName
  1659. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item)
  1660. }
  1661. }
  1662. } else if (v.ProductIds == "1,2" || v.ProductIds == "2,1") && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1663. // 套餐是ficc权益都有的,但是都没进行过开票到款,补充两个套餐的内容,直接用合同金额当作未开票金额即可
  1664. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1665. item1 := fms.NotInvoicePaymentSummaryItem{
  1666. NotInvoicedAmountTotal: serviceAmount[2].ServiceAmount,
  1667. ServiceProductId: 2,
  1668. }
  1669. item1.SellerId = v.SellerId
  1670. item1.SellerName = v.SellerName
  1671. item1.RaiSellerId = v.RaiSellerId
  1672. item1.RaiSellerName = v.RaiSellerName
  1673. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item1)
  1674. item2 := fms.NotInvoicePaymentSummaryItem{
  1675. NotInvoicedAmountTotal: serviceAmount[1].ServiceAmount,
  1676. ServiceProductId: 1,
  1677. }
  1678. item2.SellerId = v.SellerId
  1679. item2.SellerName = v.SellerName
  1680. item2.RaiSellerId = v.RaiSellerId
  1681. item2.RaiSellerName = v.RaiSellerName
  1682. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item2)
  1683. }
  1684. } else if v.ProductIds == "1" && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1685. // 只有ficc套餐,但是未进行过开票到款,手动补充信息
  1686. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1687. item1 := fms.NotInvoicePaymentSummaryItem{
  1688. NotInvoicedAmountTotal: serviceAmount[1].ServiceAmount,
  1689. ServiceProductId: 1,
  1690. }
  1691. item1.SellerId = v.SellerId
  1692. item1.SellerName = v.SellerName
  1693. item1.RaiSellerId = v.RaiSellerId
  1694. item1.RaiSellerName = v.RaiSellerName
  1695. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item1)
  1696. }
  1697. } else if v.ProductIds == "2" && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1698. // 只有权益套餐,但是未进行过开票到款,手动补充信息
  1699. if serviceAmount, ok := serviceAmountMap[v.ContractRegisterId]; ok {
  1700. item2 := fms.NotInvoicePaymentSummaryItem{
  1701. NotInvoicedAmountTotal: serviceAmount[2].ServiceAmount,
  1702. ServiceProductId: 2,
  1703. }
  1704. item2.SellerId = v.SellerId
  1705. item2.SellerName = v.SellerName
  1706. item2.RaiSellerId = v.RaiSellerId
  1707. item2.RaiSellerName = v.RaiSellerName
  1708. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item2)
  1709. }
  1710. }
  1711. }
  1712. // 重组汇总数据
  1713. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  1714. if e != nil {
  1715. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  1716. return
  1717. }
  1718. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  1719. for i := range sellerList {
  1720. sellerMap[sellerList[i].SellerId] = sellerList[i]
  1721. }
  1722. sellerTypeMap := map[int]string{2: "FICC销售", 5: "权益销售"}
  1723. // 货币列表
  1724. currencyOB := new(fms.CurrencyUnit)
  1725. currencyCond := `enable = 1`
  1726. currencyPars := make([]interface{}, 0)
  1727. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1728. if e != nil {
  1729. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  1730. return
  1731. }
  1732. unitMap := make(map[string]string)
  1733. for i := range currencyList {
  1734. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1735. }
  1736. for registerId, list := range NotInvoiceSummaryMap {
  1737. for _, v := range list {
  1738. //fmt.Println("v.ContractRegisterId", v.ContractRegisterId)
  1739. //fmt.Println("v.ServiceProductId:", v.ServiceProductId)
  1740. //fmt.Println("v.NotInvoicedAmountTotal:", v.NotInvoicedAmountTotal)
  1741. //fmt.Println("registerId:",registerId)
  1742. if v.NotInvoicedAmountTotal == 0 {
  1743. if v.InvoiceAmountTotal > v.PaymentAmountTotal {
  1744. // 有合规登记或补录合同过的,有serviceAmountMap信息
  1745. if _,ok := serviceAmountMap[registerId]; ok {
  1746. if _,ok2 := serviceAmountMap[registerId][v.ServiceProductId]; ok2{
  1747. v.NotInvoicedAmountTotal = serviceAmountMap[registerId][v.ServiceProductId].ServiceAmount - v.InvoiceAmountTotal
  1748. }
  1749. } else {
  1750. // 预登记没有合同套餐金额信息
  1751. v.NotInvoicedAmountTotal = v.InvoiceAmountTotal - v.PaymentAmountTotal
  1752. }
  1753. } else {
  1754. if _,ok := serviceAmountMap[registerId]; ok {
  1755. // 有合规登记或补录合同过的,有serviceAmountMap信息
  1756. if _,ok2 := serviceAmountMap[registerId][v.ServiceProductId]; ok2{
  1757. v.NotInvoicedAmountTotal = serviceAmountMap[registerId][v.ServiceProductId].ServiceAmount - v.PaymentAmountTotal
  1758. }
  1759. } else {
  1760. // 预登记没有合同套餐金额信息
  1761. v.NotInvoicedAmountTotal = v.PaymentAmountTotal - v.InvoiceAmountTotal
  1762. }
  1763. }
  1764. }
  1765. // 补充销售信息
  1766. if v.SellerId > 0 && v.RaiSellerId > 0 {
  1767. if v.ServiceProductId == 1 {
  1768. if seller, ok := sellerMap[v.SellerId]; ok {
  1769. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1770. v.SellerGroupId = seller.GroupId
  1771. v.SellerGroupName = seller.GroupName
  1772. }
  1773. } else {
  1774. if seller, ok := sellerMap[v.RaiSellerId]; ok {
  1775. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1776. v.RaiSellerGroupId = seller.GroupId
  1777. v.RaiSellerGroupName = seller.GroupName
  1778. }
  1779. }
  1780. } else if v.SellerId > 0 && v.RaiSellerId == 0 {
  1781. if seller, ok := sellerMap[v.SellerId]; ok {
  1782. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1783. v.SellerGroupId = seller.GroupId
  1784. v.SellerGroupName = seller.GroupName
  1785. }
  1786. } else if v.SellerId == 0 && v.RaiSellerId > 0 {
  1787. if seller, ok := sellerMap[v.RaiSellerId]; ok {
  1788. v.SellerType = sellerTypeMap[seller.DepartmentId]
  1789. v.RaiSellerGroupId = seller.GroupId
  1790. v.RaiSellerGroupName = seller.GroupName
  1791. }
  1792. }
  1793. }
  1794. }
  1795. // 响应列表
  1796. for i := range registerList {
  1797. v := new(fms.NotPaymentCensusItem)
  1798. v.SummaryId = registerList[i].SummaryId
  1799. v.ContractRegisterId = registerList[i].ContractRegisterId
  1800. v.CompanyName = registerList[i].CompanyName
  1801. v.NewCompany = registerList[i].NewCompany
  1802. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  1803. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  1804. v.ContractType = registerList[i].ContractType
  1805. v.ContractCode = registerList[i].ContractCode
  1806. v.ContractAmount = registerList[i].ContractAmount
  1807. v.UnitName = unitMap[registerList[i].CurrencyUnit]
  1808. v.ProductIds = registerList[i].ProductIds
  1809. //if registerList[i].InvoicedAmount != 0 {
  1810. // v.NotInvoiceTotal = registerList[i].ContractAmount - registerList[i].InvoicedAmount
  1811. //} else {
  1812. // v.NotInvoiceTotal = registerList[i].ContractAmount - registerList[i].PaymentAmount
  1813. //}
  1814. v.NotInvoiceList = NotInvoiceSummaryMap[registerList[i].ContractRegisterId]
  1815. respList = append(respList, v)
  1816. }
  1817. }()
  1818. // 开票到款金额合计(换算后)V2
  1819. var invoiceTotal, contractAmount float64
  1820. wg.Add(1)
  1821. go func() {
  1822. defer wg.Done()
  1823. registerList, e := fms.GetInvoiceCensusList(cond, pars)
  1824. if e != nil {
  1825. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1826. return
  1827. }
  1828. contractIdSumMap := make(map[int]int)
  1829. for _, v := range registerList {
  1830. if v.InvoicedAmount >= v.PaymentAmount {
  1831. invoiceTotal += v.InvoicedAmount
  1832. } else if v.InvoicedAmount == 0 {
  1833. invoiceTotal += v.PaymentAmount
  1834. }
  1835. rate := v.RMBRate
  1836. if rate == 0.0 {
  1837. rate = 1.0
  1838. }
  1839. if _, ok := contractIdSumMap[v.ContractRegisterId]; !ok {
  1840. contractIdSumMap[v.ContractRegisterId] = 1
  1841. contractAmount += v.ContractAmount / rate
  1842. }
  1843. }
  1844. }()
  1845. // 分币种金额统计
  1846. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1847. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1848. contractAmountCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1849. wg.Add(1)
  1850. go func() {
  1851. defer wg.Done()
  1852. currencyOB := new(fms.CurrencyUnit)
  1853. currencyCond := `enable = 1`
  1854. currencyPars := make([]interface{}, 0)
  1855. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1856. if e != nil {
  1857. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  1858. return
  1859. }
  1860. unitMap := make(map[string]string)
  1861. for i := range currencyList {
  1862. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1863. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1864. Name: currencyList[i].Name,
  1865. UnitName: currencyList[i].UnitName,
  1866. Code: currencyList[i].Code,
  1867. FlagImg: currencyList[i].FlagImg,
  1868. })
  1869. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1870. Name: currencyList[i].Name,
  1871. UnitName: currencyList[i].UnitName,
  1872. Code: currencyList[i].Code,
  1873. FlagImg: currencyList[i].FlagImg,
  1874. })
  1875. contractAmountCurrencyTotals = append(contractAmountCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1876. Name: currencyList[i].Name,
  1877. UnitName: currencyList[i].UnitName,
  1878. Code: currencyList[i].Code,
  1879. FlagImg: currencyList[i].FlagImg,
  1880. })
  1881. }
  1882. registerList, e := fms.GetInvoiceCensusList(cond, pars)
  1883. if e != nil {
  1884. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1885. return
  1886. }
  1887. invoiceSumMap := make(map[string]float64)
  1888. contractSumMap := make(map[string]float64)
  1889. contractIdSumMap := make(map[int]int)
  1890. for _, v := range registerList {
  1891. if v.InvoiceOrigin >= v.PaymentOrigin {
  1892. invoiceSumMap[v.CurrencyUnit] += v.InvoicedAmount
  1893. } else {
  1894. invoiceSumMap[v.CurrencyUnit] += v.PaymentAmount
  1895. }
  1896. if _, ok := contractIdSumMap[v.ContractRegisterId]; !ok {
  1897. contractIdSumMap[v.ContractRegisterId] = 1
  1898. contractSumMap[v.CurrencyUnit] += v.ContractAmount
  1899. }
  1900. }
  1901. for _, v := range contractAmountCurrencyTotals {
  1902. v.Amount = contractSumMap[v.Code] - invoiceSumMap[v.Code]
  1903. }
  1904. }()
  1905. wg.Wait()
  1906. if listErr != nil {
  1907. resp.FailMsg("获取失败", listErr.Error(), c)
  1908. return
  1909. }
  1910. if totalErr != nil {
  1911. resp.FailMsg("获取失败", totalErr.Error(), c)
  1912. return
  1913. }
  1914. if totalGroupErr != nil {
  1915. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  1916. return
  1917. }
  1918. results.DataList = respList
  1919. results.InvoiceTotal = invoiceTotal
  1920. results.NotInvoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", contractAmount-invoiceTotal), 64)
  1921. results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  1922. results.PaymentCurrencyTotal = paymentCurrencyTotals
  1923. results.NotInvoiceCurrencyTotal = contractAmountCurrencyTotals
  1924. fmt.Println("NotInvoiceTotal:", contractAmount-invoiceTotal)
  1925. fmt.Println("contractAmount:", contractAmount)
  1926. fmt.Println("invoiceTotal:", invoiceTotal)
  1927. }
  1928. // 是否导出
  1929. if req.IsExport == 1 {
  1930. ExportNotInvoiceCensusList(c, results)
  1931. return
  1932. }
  1933. page.SetTotal(total)
  1934. baseData := new(base.BaseData)
  1935. baseData.SetPage(page)
  1936. baseData.SetList(results)
  1937. resp.OkData("获取成功", baseData, c)
  1938. }
  1939. // List
  1940. // @Title 开票未到款统计列表
  1941. // @Description 开票未到款统计列表
  1942. // @Param Keyword query string false "关键词"
  1943. // @Param SellGroupId query int false "销售组别ID"
  1944. // @Param ServiceType query int false "套餐类型"
  1945. // @Param StartDate query string false "合同开始日期"
  1946. // @Param EndDate query string false "合同结束日期"
  1947. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  1948. // @Param HasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
  1949. // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
  1950. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  1951. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  1952. // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'invoice_time':开票日 、 'payment_date':到款日"
  1953. // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
  1954. // @Success 200 {object} fms.ContractRegisterItem
  1955. // @router /census/invoice_payment/not_payment/list [get]
  1956. func (ct *InvoicePaymentController) NotPaymentList(c *gin.Context) {
  1957. var req fms.InvoicePaymentCensusListReq
  1958. if e := c.BindQuery(&req); e != nil {
  1959. err, ok := e.(validator.ValidationErrors)
  1960. if !ok {
  1961. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1962. return
  1963. }
  1964. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1965. return
  1966. }
  1967. cond := `1 = 1`
  1968. pars := make([]interface{}, 0)
  1969. // 客户姓名/销售
  1970. if req.Keyword != "" {
  1971. kw := "%" + req.Keyword + "%"
  1972. cond += ` AND (b.company_name LIKE ? OR b.contract_code LIKE ?)`
  1973. pars = append(pars, kw, kw)
  1974. }
  1975. if req.SellerIds != "" {
  1976. sellerIds := strings.Split(req.SellerIds, ",")
  1977. cond += ` AND (c.seller_id in ?)`
  1978. pars = append(pars, sellerIds)
  1979. }
  1980. // 套餐筛选
  1981. if req.ServiceTypes != "" {
  1982. serviceTypes := strings.Split(req.ServiceTypes, ",")
  1983. tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  1984. if e != nil {
  1985. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  1986. return
  1987. }
  1988. if len(tempRegisterIds) > 0 {
  1989. cond += ` AND a.register_id IN ?`
  1990. pars = append(pars, tempRegisterIds)
  1991. } else {
  1992. cond += ` AND 1 = 2`
  1993. }
  1994. }
  1995. if req.ListParam == 1 {
  1996. cond += ` AND a.service_product_id = 1 `
  1997. } else if req.ListParam == 2 {
  1998. cond += ` AND a.service_product_id = 2 `
  1999. }
  2000. page := new(base.Page)
  2001. page.SetPageSize(req.PageSize)
  2002. page.SetCurrent(req.Current)
  2003. //排序
  2004. if req.SortType == "" {
  2005. req.SortType = "asc"
  2006. }
  2007. if req.SortType != "desc" && req.SortType != "asc" {
  2008. resp.Fail("排序类型不正确", c)
  2009. return
  2010. }
  2011. if req.SortType == "asc" {
  2012. page.AddOrderItem(base.OrderItem{Column: "e.invoice_time", Asc: true})
  2013. page.AddOrderItem(base.OrderItem{Column: "e.modify_time", Asc: false})
  2014. } else {
  2015. page.AddOrderItem(base.OrderItem{Column: "e.invoice_time", Asc: false})
  2016. page.AddOrderItem(base.OrderItem{Column: "e.modify_time", Asc: false})
  2017. }
  2018. if req.IsExport == 1 {
  2019. page.SetPageSize(10000)
  2020. page.SetCurrent(1)
  2021. }
  2022. cond += ` AND b.payment_amount <> b.invoiced_amount AND b.is_deleted = 0 AND b.contract_status <> 4 `
  2023. registerList, total, e := fms.GetNoPaymentCensusPageList(page, cond, pars)
  2024. if e != nil {
  2025. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  2026. return
  2027. }
  2028. queryRegisterIds := make([]int, 0)
  2029. for i := range registerList {
  2030. queryRegisterIds = append(queryRegisterIds, registerList[i].ContractRegisterId)
  2031. }
  2032. fmt.Println("queryRegisterIds:", queryRegisterIds)
  2033. //fmt.Println("queryRegisterIds:",queryRegisterIds)
  2034. results := new(fms.NotInvoicePaymentCensusResp)
  2035. if len(queryRegisterIds) > 0 {
  2036. // 获取汇总数据IDs, 用于查询合计数据
  2037. summaryIdsCond := cond
  2038. summaryIdsPars := pars
  2039. if req.SellerIds != "" {
  2040. sellerIds := strings.Split(req.SellerIds, ",")
  2041. summaryIdsCond += ` AND c.seller_id in ? AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2042. summaryIdsPars = append(summaryIdsPars, sellerIds)
  2043. } else {
  2044. summaryIdsCond += ` AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2045. summaryIdsPars = append(summaryIdsPars)
  2046. }
  2047. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(summaryIdsCond, summaryIdsPars)
  2048. if e != nil {
  2049. resp.FailMsg("获取失败", "获取商品到款汇总IDs失败, Err: "+e.Error(), c)
  2050. return
  2051. }
  2052. //fmt.Println("summaryIds:",summaryIds)
  2053. var listErr, totalErr, totalGroupErr error
  2054. wg := sync.WaitGroup{}
  2055. // 响应列表
  2056. respList := make([]*fms.NotPaymentCensusItem, 0)
  2057. summaryList := make([]*fms.InvoicePaymentSummaryItem, 0)
  2058. wg.Add(1)
  2059. go func() {
  2060. defer wg.Done()
  2061. // 获取汇总数据
  2062. summaryCond := cond
  2063. summaryCond += ` AND a.register_id IN ?`
  2064. summaryPars := pars
  2065. summaryPars = append(summaryPars, queryRegisterIds)
  2066. if req.SellerIds != "" {
  2067. sellerIds := strings.Split(req.SellerIds, ",")
  2068. summaryCond += ` AND c.seller_id in ? AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2069. summaryPars = append(summaryPars, sellerIds)
  2070. } else {
  2071. summaryCond += ` AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2072. summaryPars = append(summaryPars)
  2073. }
  2074. summaryData, e := fms.GetInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  2075. if e != nil {
  2076. resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
  2077. return
  2078. }
  2079. summaryList = summaryData
  2080. //summaryIds := make([]int, 0)
  2081. //for i := range summaryList {
  2082. // //summaryIds = append(summaryIds, summaryList[i].SummaryId)
  2083. //
  2084. //}
  2085. // 货币列表
  2086. currencyOB := new(fms.CurrencyUnit)
  2087. currencyCond := `enable = 1`
  2088. currencyPars := make([]interface{}, 0)
  2089. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  2090. if e != nil {
  2091. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  2092. return
  2093. }
  2094. unitMap := make(map[string]string)
  2095. for i := range currencyList {
  2096. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  2097. }
  2098. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  2099. if e != nil {
  2100. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  2101. return
  2102. }
  2103. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  2104. for i := range sellerList {
  2105. sellerMap[sellerList[i].SellerId] = sellerList[i]
  2106. }
  2107. sellerTypeMap := map[int]int{crm.SellerDepartmentId: 1, crm.RaiSellerDepartmentId: 2}
  2108. // 重组汇总数据
  2109. summaryMap := make(map[int][]*fms.NotPaymentCensusInfo)
  2110. for i := range summaryList {
  2111. v := new(fms.NotPaymentCensusInfo)
  2112. v.InvoiceId = summaryList[i].InvoiceId
  2113. v.InvoiceDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].InvoiceDate)
  2114. v.InvoiceAmount = summaryList[i].InvoiceAmount
  2115. v.SellerId = summaryList[i].SellerId
  2116. v.SellerName = summaryList[i].SellerName
  2117. v.SellerGroupId = summaryList[i].SellerGroupId
  2118. v.SellerGroupName = summaryList[i].SellerGroupName
  2119. if seller, ok := sellerMap[summaryList[i].SellerId]; ok {
  2120. v.SellerType = sellerTypeMap[seller.DepartmentId]
  2121. }
  2122. v.PaymentId = summaryList[i].PaymentId
  2123. v.PaymentDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].PaymentDate)
  2124. v.PaymentAmount = summaryList[i].PaymentAmount
  2125. v.PayType = summaryList[i].PayType
  2126. v.NotPaymentAmount = summaryList[i].InvoiceAmount - summaryList[i].PaymentAmount
  2127. v.ServiceProductId = summaryList[i].ServiceProductId
  2128. v.UnitName = unitMap[summaryList[i].CurrencyUnit]
  2129. summaryMap[summaryList[i].SummaryId] = append(summaryMap[summaryList[i].SummaryId], v)
  2130. }
  2131. // 响应列表
  2132. for i := range registerList {
  2133. v := new(fms.NotPaymentCensusItem)
  2134. v.SummaryId = registerList[i].SummaryId
  2135. v.ContractRegisterId = registerList[i].ContractRegisterId
  2136. v.CompanyName = registerList[i].CompanyName
  2137. v.NewCompany = registerList[i].NewCompany
  2138. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  2139. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  2140. v.InvoicePaymentList = summaryMap[registerList[i].SummaryId]
  2141. v.ContractType = registerList[i].ContractType
  2142. v.ContractCode = registerList[i].ContractCode
  2143. v.ContractAmount = registerList[i].ContractAmount
  2144. v.UnitName = unitMap[registerList[i].CurrencyUnit]
  2145. v.ProductIds = registerList[i].ProductIds
  2146. respList = append(respList, v)
  2147. }
  2148. }()
  2149. // 开票到款金额合计(换算后)
  2150. var invoiceTotal, paymentTotal float64
  2151. wg.Add(1)
  2152. go func() {
  2153. defer wg.Done()
  2154. if len(summaryIds) == 0 {
  2155. return
  2156. }
  2157. amountTotalCond := `a.id IN ?`
  2158. amountTotalPars := make([]interface{}, 0)
  2159. amountTotalPars = append(amountTotalPars, summaryIds)
  2160. invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
  2161. if e != nil {
  2162. totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
  2163. return
  2164. }
  2165. invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
  2166. paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
  2167. if e != nil {
  2168. totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
  2169. return
  2170. }
  2171. paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
  2172. }()
  2173. // 分币种金额统计
  2174. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2175. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2176. notpaymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2177. //contractAmountCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2178. wg.Add(1)
  2179. go func() {
  2180. defer wg.Done()
  2181. currencyOB := new(fms.CurrencyUnit)
  2182. currencyCond := `enable = 1`
  2183. currencyPars := make([]interface{}, 0)
  2184. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  2185. if e != nil {
  2186. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  2187. return
  2188. }
  2189. unitMap := make(map[string]string)
  2190. for i := range currencyList {
  2191. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  2192. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2193. Name: currencyList[i].Name,
  2194. UnitName: currencyList[i].UnitName,
  2195. Code: currencyList[i].Code,
  2196. FlagImg: currencyList[i].FlagImg,
  2197. })
  2198. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2199. Name: currencyList[i].Name,
  2200. UnitName: currencyList[i].UnitName,
  2201. Code: currencyList[i].Code,
  2202. FlagImg: currencyList[i].FlagImg,
  2203. })
  2204. notpaymentCurrencyTotals = append(notpaymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2205. Name: currencyList[i].Name,
  2206. UnitName: currencyList[i].UnitName,
  2207. Code: currencyList[i].Code,
  2208. FlagImg: currencyList[i].FlagImg,
  2209. })
  2210. }
  2211. if len(summaryIds) == 0 {
  2212. return
  2213. }
  2214. totalGroupCond := `a.id IN ?`
  2215. totalGroupPars := make([]interface{}, 0)
  2216. totalGroupPars = append(totalGroupPars, summaryIds)
  2217. invoiceSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 1)
  2218. if e != nil {
  2219. totalGroupErr = fmt.Errorf("获取汇总货币合计开票金额失败, Err: %s", e.Error())
  2220. return
  2221. }
  2222. paymentSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 2)
  2223. if e != nil {
  2224. totalGroupErr = fmt.Errorf("获取汇总货币合计到款金额失败, Err: %s", e.Error())
  2225. return
  2226. }
  2227. invoiceSumMap := make(map[string]float64)
  2228. paymentSumMap := make(map[string]float64)
  2229. //contractSumMap := make(map[string]float64)
  2230. for i := range invoiceSumGroup {
  2231. invoiceSumMap[invoiceSumGroup[i].CurrencyUnit] = invoiceSumGroup[i].OriginAmountTotal
  2232. continue
  2233. }
  2234. for i := range paymentSumGroup {
  2235. paymentSumMap[paymentSumGroup[i].CurrencyUnit] = paymentSumGroup[i].OriginAmountTotal
  2236. continue
  2237. }
  2238. for i := range invoiceCurrencyTotals {
  2239. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
  2240. invoiceCurrencyTotals[i].Amount = a
  2241. }
  2242. for i := range paymentCurrencyTotals {
  2243. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  2244. paymentCurrencyTotals[i].Amount = a
  2245. }
  2246. for i := range notpaymentCurrencyTotals {
  2247. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]-paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  2248. notpaymentCurrencyTotals[i].Amount = a
  2249. }
  2250. }()
  2251. wg.Wait()
  2252. if listErr != nil {
  2253. resp.FailMsg("获取失败", listErr.Error(), c)
  2254. return
  2255. }
  2256. if totalErr != nil {
  2257. resp.FailMsg("获取失败", totalErr.Error(), c)
  2258. return
  2259. }
  2260. if totalGroupErr != nil {
  2261. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  2262. return
  2263. }
  2264. results.DataList = respList
  2265. results.InvoiceTotal = invoiceTotal
  2266. results.PaymentTotal = paymentTotal
  2267. results.NotPaymentTotal = invoiceTotal - paymentTotal
  2268. results.NotPaymentCurrencyTotal = notpaymentCurrencyTotals
  2269. }
  2270. // 是否导出
  2271. if req.IsExport == 1 {
  2272. ExportNotPaymentCensusList(c, results)
  2273. return
  2274. }
  2275. page.SetTotal(total)
  2276. baseData := new(base.BaseData)
  2277. baseData.SetPage(page)
  2278. baseData.SetList(results)
  2279. resp.OkData("获取成功", baseData, c)
  2280. }
  2281. // ExportNotInvoiceCensusList 导出未开票统计列表
  2282. func ExportNotInvoiceCensusList(c *gin.Context, results *fms.NotInvoicePaymentCensusResp) {
  2283. list := results.DataList
  2284. if len(list) == 0 {
  2285. resp.Fail("列表数据为空", c)
  2286. return
  2287. }
  2288. // 生成Excel文件
  2289. xlsxFile := xlsx.NewFile()
  2290. style := xlsx.NewStyle()
  2291. alignment := xlsx.Alignment{
  2292. Horizontal: "center",
  2293. Vertical: "center",
  2294. WrapText: true,
  2295. }
  2296. style.Alignment = alignment
  2297. style.ApplyAlignment = true
  2298. sheetName := "未开票统计表"
  2299. sheet, err := xlsxFile.AddSheet(sheetName)
  2300. if err != nil {
  2301. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  2302. return
  2303. }
  2304. // 前三行-开票金额合计
  2305. rowA := sheet.AddRow()
  2306. cellAA := rowA.AddCell()
  2307. cellAA.SetString(fmt.Sprintf("未开票合计金额(换算后):%.2f(元)", results.NotInvoiceTotal))
  2308. rowBData := "未开票金额:"
  2309. for _, v := range results.NotInvoiceCurrencyTotal {
  2310. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  2311. }
  2312. rowB := sheet.AddRow()
  2313. rowB.AddCell().SetString(rowBData)
  2314. sheet.AddRow()
  2315. // 数据表头
  2316. rowTitle := []string{"序号", "客户名称", "合同编号", "合同开始时间", "合同结束时间", "合同金额", "金额单位", "未开票金额", "套餐类型", "销售", "销售组别", "销售类型"}
  2317. titleRow := sheet.AddRow()
  2318. for i := range rowTitle {
  2319. v := titleRow.AddCell()
  2320. v.SetString(rowTitle[i])
  2321. v.SetStyle(style)
  2322. }
  2323. incomeSummaryItemList := make([]*fms.NotPaymentCensusItem, 0)
  2324. incomeSummaryItemList = list
  2325. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  2326. if e != nil {
  2327. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  2328. return
  2329. }
  2330. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  2331. for i := range sellerList {
  2332. sellerMap[sellerList[i].SellerId] = sellerList[i]
  2333. }
  2334. sellerTypeMap := map[int]string{2: "FICC销售", 5: "权益销售"}
  2335. serviceProductIdMap := map[int]string{
  2336. 1: "FICC套餐",
  2337. 2: "权益套餐",
  2338. }
  2339. // 填充数据
  2340. for i, v := range incomeSummaryItemList {
  2341. dataRow := sheet.AddRow()
  2342. dataRow2 := sheet.AddRow()
  2343. cell := dataRow.AddCell()
  2344. cell.VMerge = 1
  2345. cell.SetString(strconv.Itoa(i + 1)) //序号
  2346. dataRow2.AddCell().SetString("")
  2347. cell2 := dataRow.AddCell()
  2348. cell2.VMerge = 1
  2349. cell2.SetString(v.CompanyName) // 客户名称
  2350. dataRow2.AddCell().SetString("")
  2351. cell3 := dataRow.AddCell()
  2352. cell3.VMerge = 1
  2353. cell3.SetString(v.ContractCode) // 合同编号
  2354. dataRow2.AddCell().SetString("")
  2355. cell4 := dataRow.AddCell()
  2356. cell4.VMerge = 1
  2357. cell4.SetString(v.StartDate) // 合同开始时间
  2358. dataRow2.AddCell().SetString("")
  2359. cell5 := dataRow.AddCell()
  2360. cell5.VMerge = 1
  2361. cell5.SetString(v.EndDate) // 合同结束时间
  2362. dataRow2.AddCell().SetString("")
  2363. cell6 := dataRow.AddCell()
  2364. cell6.VMerge = 1
  2365. cell6.SetString(fmt.Sprintf("%.2f", v.ContractAmount)) // 合同金额
  2366. dataRow2.AddCell().SetString("")
  2367. cell7 := dataRow.AddCell()
  2368. cell7.VMerge = 1
  2369. cell7.SetString(v.UnitName) // 金额单位
  2370. dataRow2.AddCell().SetString("")
  2371. for j, item := range v.NotInvoiceList {
  2372. if j == 1 {
  2373. dataRow2.AddCell().SetString(fmt.Sprintf("%.2f", item.NotInvoicedAmountTotal)) // 未开票金额
  2374. dataRow2.AddCell().SetString(serviceProductIdMap[item.ServiceProductId]) // 套餐类型
  2375. if item.SellerId > 0 && item.RaiSellerId > 0 {
  2376. if item.ServiceProductId == 1 {
  2377. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2378. if seller, ok := sellerMap[item.SellerId]; ok {
  2379. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2380. }
  2381. dataRow2.AddCell().SetString(item.SellerName) // 销售
  2382. dataRow2.AddCell().SetString(item.SellerGroupName) // 销售组别
  2383. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2384. } else {
  2385. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2386. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2387. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2388. }
  2389. dataRow2.AddCell().SetString(item.RaiSellerName) // 销售
  2390. dataRow2.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2391. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2392. }
  2393. } else if item.SellerId > 0 && item.RaiSellerId == 0 {
  2394. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2395. if seller, ok := sellerMap[item.SellerId]; ok {
  2396. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2397. }
  2398. dataRow2.AddCell().SetString(item.SellerName) // 销售
  2399. dataRow2.AddCell().SetString(item.SellerGroupName) // 销售组别
  2400. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2401. } else if item.SellerId == 0 && item.RaiSellerId > 0 {
  2402. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2403. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2404. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2405. }
  2406. dataRow2.AddCell().SetString(item.RaiSellerName) // 销售
  2407. dataRow2.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2408. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2409. }
  2410. } else {
  2411. dataRow.AddCell().SetString(fmt.Sprintf("%.2f", item.NotInvoicedAmountTotal)) // 未开票金额
  2412. dataRow.AddCell().SetString(serviceProductIdMap[item.ServiceProductId]) // 套餐类型
  2413. if item.SellerId > 0 && item.RaiSellerId > 0 {
  2414. if item.ServiceProductId == 1 {
  2415. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2416. if seller, ok := sellerMap[item.SellerId]; ok {
  2417. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2418. }
  2419. dataRow.AddCell().SetString(item.SellerName) // 销售
  2420. dataRow.AddCell().SetString(item.SellerGroupName) // 销售组别
  2421. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2422. } else {
  2423. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2424. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2425. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2426. }
  2427. dataRow.AddCell().SetString(item.RaiSellerName) // 销售
  2428. dataRow.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2429. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2430. }
  2431. } else if item.SellerId > 0 && item.RaiSellerId == 0 {
  2432. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2433. if seller, ok := sellerMap[item.SellerId]; ok {
  2434. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2435. }
  2436. dataRow.AddCell().SetString(item.SellerName) // 销售
  2437. dataRow.AddCell().SetString(item.SellerGroupName) // 销售组别
  2438. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2439. } else if item.SellerId == 0 && item.RaiSellerId > 0 {
  2440. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2441. if seller, ok := sellerMap[item.RaiSellerId]; ok {
  2442. item.SellerType = sellerTypeMap[seller.DepartmentId]
  2443. }
  2444. dataRow.AddCell().SetString(item.RaiSellerName) // 销售
  2445. dataRow.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2446. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2447. }
  2448. }
  2449. }
  2450. }
  2451. // 输出文件
  2452. var buffer bytes.Buffer
  2453. _ = xlsxFile.Write(&buffer)
  2454. content := bytes.NewReader(buffer.Bytes())
  2455. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2456. fileName := sheetName + randStr + ".xlsx"
  2457. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  2458. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2459. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  2460. }
  2461. // ExportNotPaymentCensusList 导出开票未到款统计列表
  2462. func ExportNotPaymentCensusList(c *gin.Context, results *fms.NotInvoicePaymentCensusResp) {
  2463. list := results.DataList
  2464. if len(list) == 0 {
  2465. resp.Fail("列表数据为空", c)
  2466. return
  2467. }
  2468. // 生成Excel文件
  2469. xlsxFile := xlsx.NewFile()
  2470. style := xlsx.NewStyle()
  2471. alignment := xlsx.Alignment{
  2472. Horizontal: "center",
  2473. Vertical: "center",
  2474. WrapText: true,
  2475. }
  2476. style.Alignment = alignment
  2477. style.ApplyAlignment = true
  2478. sheet, err := xlsxFile.AddSheet("开票未到款统计")
  2479. if err != nil {
  2480. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  2481. return
  2482. }
  2483. _ = sheet.SetColWidth(1, 1, 30)
  2484. _ = sheet.SetColWidth(3, 3, 30)
  2485. // 前三行-开票金额合计
  2486. rowA := sheet.AddRow()
  2487. cellAA := rowA.AddCell()
  2488. cellAA.SetString(fmt.Sprintf("开票未到款合计金额(换算后):%.2f(元)", results.NotPaymentTotal))
  2489. rowBData := "开票未到款金额:"
  2490. for _, v := range results.NotPaymentCurrencyTotal {
  2491. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  2492. }
  2493. rowB := sheet.AddRow()
  2494. rowB.AddCell().SetString(rowBData)
  2495. sheet.AddRow()
  2496. // 表头, 套餐动态获取
  2497. rowTitle := []string{"序号", "客户名称", "合同编号", "合同有效期", "套餐类型", "开票日", "开票金额", "金额单位", "开票销售",
  2498. "销售组别", "销售类型"}
  2499. titleRow := sheet.AddRow()
  2500. for i := range rowTitle {
  2501. v := titleRow.AddCell()
  2502. v.SetString(rowTitle[i])
  2503. v.SetStyle(style)
  2504. }
  2505. serviceProductIdMap := map[int]string{
  2506. 1: "FICC套餐",
  2507. 2: "权益套餐",
  2508. }
  2509. sellerTypeMap := map[int]string{1: "FICC销售", 2: "权益销售"}
  2510. for k, v := range list {
  2511. dataRow := sheet.AddRow()
  2512. // 前四个单元格根据每行开票到款条数向下合并
  2513. l := len(v.InvoicePaymentList)
  2514. mergeRowNum := l - 1
  2515. // 序号
  2516. sortNum := k + 1
  2517. colA := dataRow.AddCell()
  2518. colA.VMerge = mergeRowNum
  2519. colA.SetString(fmt.Sprint(sortNum))
  2520. // 客户名称
  2521. colB := dataRow.AddCell()
  2522. colB.VMerge = mergeRowNum
  2523. colB.SetString(v.CompanyName)
  2524. // 合同编号
  2525. colC := dataRow.AddCell()
  2526. colC.VMerge = mergeRowNum
  2527. colC.SetString(v.ContractCode)
  2528. // 合同有效期
  2529. colD := dataRow.AddCell()
  2530. colD.VMerge = mergeRowNum
  2531. colD.SetString(fmt.Sprint(v.StartDate, "至", v.EndDate))
  2532. // 套餐类型
  2533. colE := dataRow.AddCell()
  2534. colE.VMerge = mergeRowNum
  2535. colE.SetString(serviceProductIdMap[v.InvoicePaymentList[0].ServiceProductId])
  2536. // 开票到款信息
  2537. for _, v2 := range v.InvoicePaymentList {
  2538. rowData := []string{
  2539. v2.InvoiceDate, // 开票日
  2540. fmt.Sprint(v2.NotPaymentAmount), // 开票金额
  2541. v2.UnitName, // 开票金额
  2542. v2.SellerName, // 销售
  2543. v2.SellerGroupName, // 组别
  2544. sellerTypeMap[v2.SellerType], // 销售类型
  2545. }
  2546. for i := range rowData {
  2547. dataRow.AddCell().SetString(rowData[i])
  2548. }
  2549. }
  2550. }
  2551. // 输出文件
  2552. var buffer bytes.Buffer
  2553. _ = xlsxFile.Write(&buffer)
  2554. content := bytes.NewReader(buffer.Bytes())
  2555. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2556. fileName := "商品到款统计_" + randStr + ".xlsx"
  2557. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  2558. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2559. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  2560. }