invoice_payment.go 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740
  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.GetSellerDepartmentListWithGroupAndTeam()
  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. v.SellerType = sellerTypeMap[sellerMap[summaryList[i].SellerId].DepartmentId]
  755. v.PaymentId = summaryList[i].PaymentId
  756. v.PaymentDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].PaymentDate)
  757. v.PaymentAmount = summaryList[i].PaymentAmount
  758. v.PayType = summaryList[i].PayType
  759. // 套餐到款分配
  760. svaList := make([]*fms.ContractPaymentServiceAmountItem, 0)
  761. amountList := serviceAmountMap[summaryList[i].PaymentId]
  762. if amountList != nil {
  763. for i := range amountList {
  764. k := fmt.Sprintf("%d-%d", amountList[i].ContractPaymentId, amountList[i].ServiceTemplateId)
  765. amountMap[k] = amountList[i]
  766. }
  767. }
  768. // 合同对应的所有套餐
  769. svList := serviceFormatMap[summaryList[i].RegisterId]
  770. if svList != nil {
  771. for ii := range svList {
  772. vv := new(fms.ContractPaymentServiceAmountItem)
  773. vv.ServiceTemplateId = svList[ii].ServiceTemplateId
  774. vv.ServiceTemplateName = svList[ii].FormatTitle
  775. vv.ServiceTemplatePid = svList[ii].ServiceTemplatePid
  776. vv.ServiceProductId = svList[ii].ServiceProductId
  777. k2 := fmt.Sprintf("%d-%d", summaryList[i].PaymentId, svList[ii].ServiceTemplateId)
  778. a := amountMap[k2]
  779. if a != nil {
  780. vv.ContractPaymentServiceAmountId = a.ContractPaymentServiceAmountId
  781. vv.ContractPaymentId = a.ContractPaymentId
  782. vv.Amount = a.Amount
  783. }
  784. svaList = append(svaList, vv)
  785. }
  786. }
  787. v.ServiceAmountList = svaList
  788. summaryMap[summaryList[i].SummaryId] = append(summaryMap[summaryList[i].SummaryId], v)
  789. }
  790. // 响应列表
  791. for i := range registerList {
  792. v := new(fms.InvoicePaymentCensusItem)
  793. v.SummaryId = registerList[i].SummaryId
  794. v.ContractRegisterId = registerList[i].ContractRegisterId
  795. v.CompanyName = registerList[i].CompanyName
  796. v.NewCompany = registerList[i].NewCompany
  797. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  798. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  799. v.ServicesName = servicesNameMap[registerList[i].ContractRegisterId]
  800. v.InvoicePaymentList = summaryMap[registerList[i].SummaryId]
  801. v.ContractType = registerList[i].ContractType
  802. v.ActualPayCompanies = registerList[i].ActualPayCompanies
  803. respList = append(respList, v)
  804. }
  805. }()
  806. // 开票到款金额合计(换算后)
  807. var invoiceTotal, paymentTotal, amountTotal float64
  808. wg.Add(1)
  809. go func() {
  810. defer wg.Done()
  811. if len(summaryIds) == 0 {
  812. return
  813. }
  814. amountTotalCond := `a.id IN ?`
  815. amountTotalPars := make([]interface{}, 0)
  816. amountTotalPars = append(amountTotalPars, summaryIds)
  817. invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
  818. if e != nil {
  819. totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
  820. return
  821. }
  822. invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
  823. paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
  824. if e != nil {
  825. totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
  826. return
  827. }
  828. paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
  829. amountCond := `a.id IN ? AND (a.invoice_id <> 0 OR (a.payment_id <> 0 AND a.invoice_id =0))`
  830. amountPars := make([]interface{}, 0)
  831. amountPars = append(amountPars, summaryIds)
  832. amountSum, e := fms.GetContractSummaryInvoicePaymentAmount(amountCond, amountPars)
  833. if e != nil {
  834. totalErr = fmt.Errorf("获取汇总金额合计失败, Err: %s", e.Error())
  835. return
  836. }
  837. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  838. }()
  839. // 分币种金额统计
  840. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  841. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  842. wg.Add(1)
  843. go func() {
  844. defer wg.Done()
  845. currencyOB := new(fms.CurrencyUnit)
  846. currencyCond := `enable = 1`
  847. currencyPars := make([]interface{}, 0)
  848. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  849. if e != nil {
  850. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  851. return
  852. }
  853. unitMap := make(map[string]string)
  854. for i := range currencyList {
  855. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  856. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  857. Name: currencyList[i].Name,
  858. UnitName: currencyList[i].UnitName,
  859. Code: currencyList[i].Code,
  860. FlagImg: currencyList[i].FlagImg,
  861. })
  862. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  863. Name: currencyList[i].Name,
  864. UnitName: currencyList[i].UnitName,
  865. Code: currencyList[i].Code,
  866. FlagImg: currencyList[i].FlagImg,
  867. })
  868. }
  869. if len(summaryIds) == 0 {
  870. return
  871. }
  872. totalGroupCond := `a.id IN ?`
  873. totalGroupPars := make([]interface{}, 0)
  874. totalGroupPars = append(totalGroupPars, summaryIds)
  875. invoiceSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 1)
  876. if e != nil {
  877. totalGroupErr = fmt.Errorf("获取汇总货币合计开票金额失败, Err: %s", e.Error())
  878. return
  879. }
  880. paymentSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 2)
  881. if e != nil {
  882. totalGroupErr = fmt.Errorf("获取汇总货币合计到款金额失败, Err: %s", e.Error())
  883. return
  884. }
  885. invoiceSumMap := make(map[string]float64)
  886. paymentSumMap := make(map[string]float64)
  887. for i := range invoiceSumGroup {
  888. invoiceSumMap[invoiceSumGroup[i].CurrencyUnit] = invoiceSumGroup[i].OriginAmountTotal
  889. continue
  890. }
  891. for i := range paymentSumGroup {
  892. paymentSumMap[paymentSumGroup[i].CurrencyUnit] = paymentSumGroup[i].OriginAmountTotal
  893. continue
  894. }
  895. for i := range invoiceCurrencyTotals {
  896. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
  897. invoiceCurrencyTotals[i].Amount = a
  898. }
  899. for i := range paymentCurrencyTotals {
  900. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  901. paymentCurrencyTotals[i].Amount = a
  902. }
  903. }()
  904. wg.Wait()
  905. if listErr != nil {
  906. resp.FailMsg("获取失败", listErr.Error(), c)
  907. return
  908. }
  909. if totalErr != nil {
  910. resp.FailMsg("获取失败", totalErr.Error(), c)
  911. return
  912. }
  913. if totalGroupErr != nil {
  914. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  915. return
  916. }
  917. results.DataList = respList
  918. results.InvoiceTotal = invoiceTotal
  919. results.PaymentTotal = paymentTotal
  920. results.AmountTotal = amountTotal
  921. results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  922. results.PaymentCurrencyTotal = paymentCurrencyTotals
  923. }
  924. // 是否导出
  925. if req.IsExport == 1 {
  926. ExportInvoicePaymentCensusList(c, results)
  927. return
  928. }
  929. page.SetTotal(total)
  930. baseData := new(base.BaseData)
  931. baseData.SetPage(page)
  932. baseData.SetList(results)
  933. resp.OkData("获取成功", baseData, c)
  934. }
  935. // IncomeList
  936. // @Title 业务收入统计表
  937. // @Description 获取业务收入统计表接口
  938. // @Param ListParam query int false "套餐类型: 0-月度; 1-季度; 2-半年度;3-年度;4-月度累计"
  939. // @Success 200 {object} fms.CensusIncomeChartResp
  940. // @router /census/income/list [get]
  941. func (this *InvoicePaymentController) IncomeList(c *gin.Context) {
  942. var req fms.IncomeListReq
  943. if e := c.BindQuery(&req); e != nil {
  944. err, ok := e.(validator.ValidationErrors)
  945. if !ok {
  946. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  947. return
  948. }
  949. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  950. return
  951. }
  952. //收入统计
  953. var incomeList models.CensusIncomeChartResp
  954. ch := make(chan models.CensusIncomeChartResp, 1)
  955. go getCensusIncomeListV2(ch, req)
  956. for v := range ch {
  957. incomeList = v
  958. close(ch)
  959. }
  960. // 是否导出
  961. if req.IsExport == 1 {
  962. ExportIncomeList(c, incomeList.DataList)
  963. return
  964. }
  965. resp.OkData("获取成功", incomeList, c)
  966. }
  967. func getCensusIncomeListV2(ch chan models.CensusIncomeChartResp, req fms.IncomeListReq) (incomeChart models.CensusIncomeChartResp, err error) {
  968. defer func() {
  969. if err != nil {
  970. global.LOG.Error(err)
  971. if err != utils.ErrNoRow {
  972. go alarm_msg.SendAlarmMsg("获取业务收入金额统计数据异常,Err:"+err.Error(), 3)
  973. }
  974. }
  975. ch <- incomeChart
  976. }()
  977. //todayStr := utils.GetToday("20060102")
  978. //key := "admin:home:fmsIncomeList:" + todayStr
  979. //
  980. //redisJsonData, redisErr := global.Redis.Get(context.TODO(), key).Result()
  981. //if redisErr != nil {
  982. //获取最新的开票到款日期
  983. cond := ``
  984. historyCond := ``
  985. pars := make([]interface{}, 0)
  986. historyPars := make([]interface{}, 0)
  987. if req.SellerIds != "" {
  988. sellerIds := strings.Split(req.SellerIds, ",")
  989. cond += ` AND (a.seller_id in ? )`
  990. historyCond += ` AND (seller_id in ? )`
  991. pars = append(pars, sellerIds)
  992. historyPars = append(historyPars, sellerIds)
  993. }
  994. if req.CompanyType == 1 {
  995. cond += ` AND b.contract_type = 1 `
  996. historyCond += ` AND new_company = 1`
  997. } else if req.CompanyType == 2 {
  998. cond += ` AND b.contract_type IN (2,3,4) `
  999. historyCond += ` AND new_company = 0`
  1000. }
  1001. var latestTime time.Time
  1002. invoiceItem, err := fms.GetLatestIncome(cond, pars)
  1003. if err != nil && err != utils.ErrNoRow {
  1004. err = fmt.Errorf("获取最新的开票或到款日期, Err: %s", err.Error())
  1005. return
  1006. }
  1007. latestTime = invoiceItem.InvoiceDate
  1008. if err == utils.ErrNoRow {
  1009. historyItem, e := fms.GetLatestHistoryIncome(historyCond, historyPars)
  1010. if e != nil && e != utils.ErrNoRow {
  1011. err = fmt.Errorf("获取最新的历史开票或到款日期, Err: %s", err.Error())
  1012. return
  1013. }
  1014. latestTime = historyItem.InvoiceDate
  1015. }
  1016. if latestTime.IsZero() {
  1017. latestTime = time.Now()
  1018. }
  1019. latestTime = latestTime.AddDate(0, 0, -latestTime.Day()+1)
  1020. var dateSlice []string
  1021. var totalMoneySlice, prevTotalMoneySlice []float64
  1022. var yoySlice []string
  1023. var yearNum, monthNum int
  1024. var reqStartDate, reqEndDate time.Time
  1025. historyTime, _ := time.Parse(utils.FormatDate, "2023-04-01")
  1026. if req.StartDate != "" && req.EndDate != "" {
  1027. st := fmt.Sprint(req.StartDate, "-01 00:00:00")
  1028. ed := fmt.Sprint(req.EndDate, "-01 23:59:59")
  1029. reqStartDate, _ = time.Parse(utils.FormatDateTime, st)
  1030. reqEndDate, _ = time.Parse(utils.FormatDateTime, ed)
  1031. if reqEndDate.After(latestTime) {
  1032. yearNum = latestTime.Year() - reqStartDate.Year()
  1033. monthNum = int(latestTime.Month() - reqStartDate.Month())
  1034. } else {
  1035. yearNum = reqEndDate.Year() - reqStartDate.Year()
  1036. monthNum = int(reqEndDate.Month() - reqStartDate.Month())
  1037. }
  1038. } else {
  1039. yearNum = latestTime.Year() - 2020
  1040. monthNum = int(latestTime.Month() - 1)
  1041. }
  1042. if yearNum < 0 {
  1043. yearNum = -yearNum
  1044. }
  1045. if monthNum < 0 {
  1046. monthNum = -monthNum
  1047. }
  1048. numMonth := yearNum*12 + monthNum //共存在多少个月
  1049. //if req.ListParam == "1" {
  1050. // numMonth = numMonth / 3
  1051. //} else if req.ListParam == "2" {
  1052. // numMonth = numMonth / 6
  1053. //} else if req.ListParam == "3" {
  1054. // numMonth = numMonth / 12
  1055. //}
  1056. // 累计值
  1057. var accumulate float64
  1058. var partAccumulate float64
  1059. var historyAccumulate float64
  1060. var partHistoryAccumulate float64
  1061. //dataList := make([]*fms.IncomeSummaryItem, 0)
  1062. //historydataList := make([]*fms.IncomeSummaryItem, 0)
  1063. fmt.Println("numMonth:", numMonth)
  1064. fmt.Println("InvoiceDate:", latestTime)
  1065. var j int
  1066. for i := 0; i <= numMonth; i++ {
  1067. //timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
  1068. var endDateTime time.Time
  1069. var prevEndDateTime time.Time
  1070. var prevStartDate, prevEndDate string
  1071. var startDate, endDate string
  1072. //开始日期
  1073. if req.StartDate != "" && req.EndDate != "" {
  1074. startDate = reqStartDate.AddDate(0, i, 0).Format("2006-01")
  1075. prevStartDate = reqStartDate.AddDate(-1, i, 0).Format("2006-01")
  1076. } else {
  1077. startDate = latestTime.AddDate(0, i-numMonth, 0).Format("2006-01")
  1078. prevStartDate = latestTime.AddDate(-1, i-numMonth, 0).Format("2006-01")
  1079. }
  1080. startDate = fmt.Sprint(startDate, "-01")
  1081. prevStartDate = fmt.Sprint(prevStartDate, "-01")
  1082. startDateTime, _ := time.Parse(utils.FormatDate, startDate)
  1083. prevStartDateTime, _ := time.Parse(utils.FormatDate, prevStartDate)
  1084. //结束日期
  1085. if req.StartDate != "" && req.EndDate != "" {
  1086. endDateTime = reqStartDate.AddDate(0, i+1, -1)
  1087. prevEndDateTime = reqStartDate.AddDate(-1, i+1, -1)
  1088. if reqEndDate.After(latestTime) {
  1089. endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
  1090. prevEndDateTime = latestTime.AddDate(-1, i-numMonth+1, -1)
  1091. }
  1092. } else {
  1093. endDateTime = latestTime.AddDate(0, i-numMonth+1, -1)
  1094. prevEndDateTime = latestTime.AddDate(-1, i-numMonth+1, -1)
  1095. }
  1096. endDate = endDateTime.Format(utils.FormatDate)
  1097. prevEndDate = prevEndDateTime.Format(utils.FormatDate)
  1098. cond := `1 = 1`
  1099. histrtyCond := `1 = 1`
  1100. pars := make([]interface{}, 0)
  1101. historyPars := make([]interface{}, 0)
  1102. prevCond := `1 = 1`
  1103. prevHistoryCond := `1 = 1`
  1104. prevPars := make([]interface{}, 0)
  1105. prevHistoryPars := make([]interface{}, 0)
  1106. if req.CompanyType == 1 {
  1107. cond += ` AND b.contract_type = 1 `
  1108. prevCond += ` AND b.contract_type = 1 `
  1109. histrtyCond += ` AND new_company = 1 `
  1110. prevHistoryCond += ` AND new_company = 1 `
  1111. } else if req.CompanyType == 2 {
  1112. cond += ` AND b.contract_type IN (2,3,4) `
  1113. prevCond += ` AND b.contract_type IN (2,3,4) `
  1114. histrtyCond += ` AND new_company = 0 `
  1115. prevHistoryCond += ` AND new_company = 0 `
  1116. }
  1117. if req.SellerIds != "" {
  1118. sellerIds := strings.Split(req.SellerIds, ",")
  1119. cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  1120. pars = append(pars, sellerIds, sellerIds)
  1121. prevCond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  1122. prevPars = append(prevPars, sellerIds, sellerIds)
  1123. histrtyCond += ` AND seller_id in ? `
  1124. prevHistoryCond += ` AND seller_id in ? `
  1125. historyPars = append(historyPars, sellerIds)
  1126. prevHistoryPars = append(prevHistoryPars, sellerIds)
  1127. }
  1128. //fmt.Println("i:",i)
  1129. //fmt.Println("j:",j)
  1130. {
  1131. //本期
  1132. st := fmt.Sprint(startDate, " 00:00:00")
  1133. ed := fmt.Sprint(endDate, " 23:59:59")
  1134. //校验日期,分段查询
  1135. if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
  1136. //全部走新查询
  1137. //fmt.Println("新查询")
  1138. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1139. pars = append(pars, st, ed, st, ed)
  1140. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1141. if e != nil {
  1142. return
  1143. }
  1144. // 开票到款金额合计(换算后)
  1145. var amountTotal float64
  1146. if len(summaryIds) > 0 {
  1147. amountCond := `a.id IN ? `
  1148. amountPars := make([]interface{}, 0)
  1149. amountPars = append(amountPars, summaryIds)
  1150. if req.SellerIds != "" {
  1151. sellerIds := strings.Split(req.SellerIds, ",")
  1152. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1153. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1154. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  1155. } else {
  1156. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1157. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1158. amountPars = append(amountPars, st, ed, st, ed)
  1159. }
  1160. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1161. if e != nil {
  1162. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1163. return
  1164. }
  1165. //dataList = append(dataList, results...)
  1166. var amountSum float64
  1167. for _, result := range results {
  1168. incomeChart.DataList = append(incomeChart.DataList, result)
  1169. amountSum += result.Amount
  1170. fmt.Println("result.Amount:", result.Amount)
  1171. }
  1172. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1173. accumulate += amountTotal
  1174. partAccumulate += amountTotal
  1175. }
  1176. if i == j || i == numMonth {
  1177. if req.ListParam == "4" {
  1178. totalMoneySlice = append(totalMoneySlice, accumulate)
  1179. if startDateTime.Month() == 12 {
  1180. accumulate = 0
  1181. }
  1182. } else if req.ListParam == "0" {
  1183. totalMoneySlice = append(totalMoneySlice, amountTotal)
  1184. } else if i > 0 || i == numMonth {
  1185. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  1186. fmt.Println("partAccumulate:", partAccumulate)
  1187. partAccumulate = 0.0
  1188. }
  1189. }
  1190. } else if endDateTime.Before(historyTime) || endDateTime.Equal(historyTime) {
  1191. //全部走旧查询
  1192. //fmt.Println("旧查询")
  1193. //fmt.Println("st:",st)
  1194. //fmt.Println("ed:",ed)
  1195. histrtyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1196. historyPars = append(historyPars, st, ed)
  1197. //fmt.Println("st:",st)
  1198. //fmt.Println("ed:",ed)
  1199. // 开票到款金额合计(换算后)
  1200. var amountTotal float64
  1201. results, e := fms.GetIncomeHistory(histrtyCond, historyPars)
  1202. if e != nil {
  1203. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1204. return
  1205. }
  1206. var amountSum float64
  1207. //dataList = append(dataList, results...)
  1208. for _, result := range results {
  1209. incomeChart.DataList = append(incomeChart.DataList, result)
  1210. amountSum += result.Amount
  1211. }
  1212. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1213. accumulate += amountTotal
  1214. partAccumulate += amountTotal
  1215. if i == j || i == numMonth {
  1216. if req.ListParam == "4" {
  1217. totalMoneySlice = append(totalMoneySlice, accumulate)
  1218. if startDateTime.Month() == 12 {
  1219. accumulate = 0
  1220. }
  1221. } else if req.ListParam == "0" {
  1222. totalMoneySlice = append(totalMoneySlice, amountTotal)
  1223. } else if i > 0 || i == numMonth {
  1224. totalMoneySlice = append(totalMoneySlice, partAccumulate)
  1225. partAccumulate = 0.0
  1226. }
  1227. }
  1228. //fmt.Println("partAccumulate:",partAccumulate)
  1229. }
  1230. }
  1231. { //去年同期,用于计算同比值
  1232. prevSt := fmt.Sprint(prevStartDate, " 00:00:00")
  1233. prevEd := fmt.Sprint(prevEndDate, " 23:59:59")
  1234. //校验日期,分段查询
  1235. if prevStartDateTime.After(historyTime) || prevStartDateTime.Equal(historyTime) {
  1236. //全部走新查询
  1237. prevCond += ` AND ((b.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1238. prevPars = append(prevPars, prevSt, prevEd, prevSt, prevEd)
  1239. prevSummaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(prevCond, prevPars)
  1240. if e != nil {
  1241. return
  1242. }
  1243. // 开票到款金额合计(换算后)
  1244. var prevAmountTotal float64
  1245. if len(prevSummaryIds) > 0 {
  1246. amountCond := `a.id IN ? `
  1247. amountPars := make([]interface{}, 0)
  1248. amountPars = append(amountPars, prevSummaryIds)
  1249. if req.SellerIds != "" {
  1250. sellerIds := strings.Split(req.SellerIds, ",")
  1251. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1252. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1253. amountPars = append(amountPars, sellerIds, prevSt, prevEd, sellerIds, prevSt, prevEd)
  1254. } else {
  1255. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1256. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1257. amountPars = append(amountPars, prevSt, prevEd)
  1258. }
  1259. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1260. if e != nil {
  1261. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1262. return
  1263. }
  1264. var amountSum float64
  1265. //historydataList = append(historydataList, results...)
  1266. for _, result := range results {
  1267. amountSum += result.Amount
  1268. }
  1269. prevAmountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1270. historyAccumulate += prevAmountTotal
  1271. partHistoryAccumulate += prevAmountTotal
  1272. }
  1273. if i == j || i == numMonth {
  1274. if req.ListParam == "4" {
  1275. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate)
  1276. if prevStartDateTime.Month() == 12 {
  1277. historyAccumulate = 0
  1278. }
  1279. } else if req.ListParam == "0" {
  1280. prevTotalMoneySlice = append(prevTotalMoneySlice, prevAmountTotal)
  1281. } else if i > 0 || i == numMonth {
  1282. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate)
  1283. fmt.Println("partHistoryAccumulate:", partHistoryAccumulate)
  1284. partHistoryAccumulate = 0.0
  1285. }
  1286. }
  1287. } else if prevEndDateTime.Before(historyTime) || prevEndDateTime.Equal(historyTime) {
  1288. //全部走旧查询
  1289. fmt.Println("prevSt:", prevSt)
  1290. fmt.Println("prevEd:", prevEd)
  1291. prevHistoryCond += ` AND (invoice_time BETWEEN ? AND ?)`
  1292. prevHistoryPars = append(prevHistoryPars, prevSt, prevEd)
  1293. // 开票到款金额合计(换算后)
  1294. var amountTotal float64
  1295. results, e := fms.GetIncomeHistory(prevHistoryCond, prevHistoryPars)
  1296. if e != nil {
  1297. err = fmt.Errorf("获取汇总数据失败, Err: %s", e.Error())
  1298. return
  1299. }
  1300. //historydataList = append(historydataList, results...)
  1301. var amountSum float64
  1302. for _, result := range results {
  1303. amountSum += result.Amount
  1304. }
  1305. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1306. historyAccumulate += amountTotal
  1307. partHistoryAccumulate += amountTotal
  1308. if i == j || i == numMonth {
  1309. if req.ListParam == "4" {
  1310. prevTotalMoneySlice = append(prevTotalMoneySlice, historyAccumulate)
  1311. if prevStartDateTime.Month() == 12 {
  1312. historyAccumulate = 0
  1313. }
  1314. } else if req.ListParam == "0" {
  1315. prevTotalMoneySlice = append(prevTotalMoneySlice, amountTotal)
  1316. } else if i > 0 || i == numMonth {
  1317. prevTotalMoneySlice = append(prevTotalMoneySlice, partHistoryAccumulate)
  1318. fmt.Println("partHistoryAccumulate:", partHistoryAccumulate)
  1319. partHistoryAccumulate = 0.0
  1320. }
  1321. }
  1322. //fmt.Println("partHistoryAccumulate:",partHistoryAccumulate)
  1323. }
  1324. if req.ListParam == "1" && i == j {
  1325. if i == 0 {
  1326. dateSlice = append(dateSlice, startDateTime.AddDate(0, 2, 0).Format("06/01"))
  1327. j = j + 2
  1328. } else {
  1329. dateSlice = append(dateSlice, startDateTime.AddDate(0, 3, 0).Format("06/01"))
  1330. j = j + 3
  1331. }
  1332. } else if req.ListParam == "2" && i == j {
  1333. if i == 0 {
  1334. dateSlice = append(dateSlice, startDateTime.AddDate(0, 5, 0).Format("06/01"))
  1335. j = j + 5
  1336. } else {
  1337. dateSlice = append(dateSlice, startDateTime.AddDate(0, 6, 0).Format("06/01"))
  1338. j = j + 6
  1339. }
  1340. } else if req.ListParam == "3" && i == j {
  1341. if i == 0 {
  1342. dateSlice = append(dateSlice, startDateTime.AddDate(0, 11, 0).Format("06/01"))
  1343. j = j + 11
  1344. } else {
  1345. dateSlice = append(dateSlice, startDateTime.AddDate(0, 12, 0).Format("06/01"))
  1346. j = j + 12
  1347. }
  1348. } else if i == j {
  1349. dateSlice = append(dateSlice, startDateTime.Format("06/01"))
  1350. j++
  1351. }
  1352. }
  1353. }
  1354. fmt.Println("prevTotalMoneySlice:", len(prevTotalMoneySlice))
  1355. fmt.Println("totalMoneySlice:", len(totalMoneySlice))
  1356. //计算同比值
  1357. for i := range prevTotalMoneySlice {
  1358. var yoy float64
  1359. var yoyStr string
  1360. //fmt.Println("1:", prevTotalMoneySlice[i])
  1361. //fmt.Println("2:", totalMoneySlice[i])
  1362. //fmt.Println("3:", totalMoneySlice[i]-prevTotalMoneySlice[i])
  1363. totalMoneySlice[i], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", totalMoneySlice[i]), 64)
  1364. if prevTotalMoneySlice[i] != 0 && totalMoneySlice[i] != 0 {
  1365. yoy = (totalMoneySlice[i] - prevTotalMoneySlice[i]) / prevTotalMoneySlice[i]
  1366. yoyStr = fmt.Sprintf("%.4f", yoy)
  1367. if i == len(prevTotalMoneySlice)-1 && i > 0 && req.ListParam == "3" {
  1368. fmt.Println("totalMoneySlice[i-1]:", totalMoneySlice[i-1])
  1369. yoy = (totalMoneySlice[i] - totalMoneySlice[i-1]) / totalMoneySlice[i-1]
  1370. yoyStr = fmt.Sprintf("%.4f", yoy)
  1371. }
  1372. }
  1373. yoySlice = append(yoySlice, yoyStr)
  1374. }
  1375. incomeChart.Title = "开票到款统计图"
  1376. incomeChart.Date = dateSlice
  1377. incomeChart.TotalMoney = totalMoneySlice
  1378. incomeChart.PrevTotalMoney = prevTotalMoneySlice
  1379. incomeChart.Yoy = yoySlice
  1380. //redisJsonData, err := json.Marshal(incomeChart)
  1381. //if err == nil {
  1382. // global.Redis.SetEX(context.TODO(), key, string(redisJsonData), time.Minute*30)
  1383. //}
  1384. //} else {
  1385. // err = json.Unmarshal([]byte(redisJsonData), &incomeChart)
  1386. // if err != nil {
  1387. // fmt.Println("近两年的收入统计数据,json转换失败")
  1388. // }
  1389. //}
  1390. return
  1391. }
  1392. // ExportIncomeList 导出业务收入统计列表
  1393. func ExportIncomeList(c *gin.Context, list []*fms.IncomeSummaryItem) {
  1394. // 生成Excel文件
  1395. xlsxFile := xlsx.NewFile()
  1396. style := xlsx.NewStyle()
  1397. alignment := xlsx.Alignment{
  1398. Horizontal: "center",
  1399. Vertical: "center",
  1400. WrapText: true,
  1401. }
  1402. style.Alignment = alignment
  1403. style.ApplyAlignment = true
  1404. sheetName := "业务收入统计表"
  1405. sheet, err := xlsxFile.AddSheet(sheetName)
  1406. if err != nil {
  1407. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1408. return
  1409. }
  1410. // 数据表头
  1411. rowTitle := []string{"开票日期", "新客户(1)", "客户名称", "金额", "销售"}
  1412. titleRow := sheet.AddRow()
  1413. for i := range rowTitle {
  1414. v := titleRow.AddCell()
  1415. v.SetString(rowTitle[i])
  1416. v.SetStyle(style)
  1417. }
  1418. incomeSummaryItemList := make(fms.IncomeSummaryItemList, 0)
  1419. incomeSummaryItemList = list
  1420. sort.Sort(incomeSummaryItemList)
  1421. // 填充数据
  1422. for _, v := range incomeSummaryItemList {
  1423. dataRow := sheet.AddRow()
  1424. dataRow.AddCell().SetString(v.InvoiceDate.Format(utils.FormatDate)) // 开票日期
  1425. newCompany := 0
  1426. if v.ContractType == 1 {
  1427. newCompany = 1
  1428. }
  1429. dataRow.AddCell().SetString(strconv.Itoa(newCompany)) // 新客户
  1430. dataRow.AddCell().SetString(v.CompanyName) // 客户名称
  1431. dataRow.AddCell().SetString(fmt.Sprint(v.Amount)) // 金额
  1432. dataRow.AddCell().SetString(v.SellerName) // 销售员
  1433. }
  1434. // 输出文件
  1435. var buffer bytes.Buffer
  1436. _ = xlsxFile.Write(&buffer)
  1437. content := bytes.NewReader(buffer.Bytes())
  1438. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1439. fileName := sheetName + randStr + ".xlsx"
  1440. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1441. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1442. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1443. }
  1444. // List
  1445. // @Title 未开票统计列表
  1446. // @Description 未开票统计列表
  1447. // @Param Keyword query string false "关键词"
  1448. // @Param SellGroupId query int false "销售组别ID"
  1449. // @Param ServiceType query int false "套餐类型"
  1450. // @Param StartDate query string false "合同开始日期"
  1451. // @Param EndDate query string false "合同结束日期"
  1452. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  1453. // @Param HasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
  1454. // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
  1455. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  1456. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  1457. // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'start_date':开票日 、 'end_date':到款日"
  1458. // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
  1459. // @Success 200 {object} fms.ContractRegisterItem
  1460. // @router /census/invoice_payment/not_invoice/list [get]
  1461. func (ct *InvoicePaymentController) NotInvoiceList(c *gin.Context) {
  1462. var req fms.InvoicePaymentCensusListReq
  1463. if e := c.BindQuery(&req); e != nil {
  1464. err, ok := e.(validator.ValidationErrors)
  1465. if !ok {
  1466. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1467. return
  1468. }
  1469. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1470. return
  1471. }
  1472. cond := `1 = 1`
  1473. pars := make([]interface{}, 0)
  1474. noSummaryCond := `1 = 1`
  1475. noSummaryPars := make([]interface{}, 0)
  1476. // 客户姓名/合同编号
  1477. if req.Keyword != "" {
  1478. kw := "%" + req.Keyword + "%"
  1479. cond += ` AND (b.company_name LIKE ? OR b.contract_code LIKE ?)`
  1480. pars = append(pars, kw, kw)
  1481. noSummaryCond += ` AND (b.company_name LIKE ? OR b.contract_code LIKE ?)`
  1482. noSummaryPars = append(noSummaryPars, kw, kw)
  1483. }
  1484. if req.SellerIds != "" {
  1485. sellerIds := strings.Split(req.SellerIds, ",")
  1486. cond += ` AND (b.seller_id in ? OR b.rai_seller_id in ?)`
  1487. pars = append(pars, sellerIds, sellerIds)
  1488. noSummaryCond += ` AND (b.seller_id in ? OR b.rai_seller_id in ?)`
  1489. noSummaryPars = append(noSummaryPars, sellerIds, sellerIds)
  1490. }
  1491. // 套餐筛选
  1492. if req.ServiceTypes != "" {
  1493. serviceTypes := strings.Split(req.ServiceTypes, ",")
  1494. tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  1495. if e != nil {
  1496. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  1497. return
  1498. }
  1499. if len(tempRegisterIds) > 0 {
  1500. cond += ` AND a.register_id IN ?`
  1501. pars = append(pars, tempRegisterIds)
  1502. noSummaryCond += ` AND b.register_id IN ? `
  1503. noSummaryPars = append(noSummaryPars, tempRegisterIds)
  1504. } else {
  1505. cond += ` AND 1 = 2`
  1506. noSummaryCond += ` AND 1 = 2`
  1507. }
  1508. }
  1509. if req.ListParam == 1 {
  1510. cond += ` AND a.service_product_id = 1 `
  1511. noSummaryCond += ` AND b.product_ids = '1' `
  1512. } else if req.ListParam == 2 {
  1513. cond += ` AND a.service_product_id = 2 `
  1514. noSummaryCond += ` AND b.product_ids = '2' `
  1515. }
  1516. page := new(base.Page)
  1517. page.SetPageSize(req.PageSize)
  1518. page.SetCurrent(req.Current)
  1519. //排序
  1520. if req.SortType == "" {
  1521. req.SortType = "asc"
  1522. }
  1523. if req.SortType != "desc" && req.SortType != "asc" {
  1524. resp.Fail("排序类型不正确", c)
  1525. return
  1526. }
  1527. if req.SortParam == "" {
  1528. page.AddOrderItem(base.OrderItem{Column: "e.start_date", Asc: true})
  1529. } else if req.SortParam == "start_date" {
  1530. if req.SortType == "asc" {
  1531. page.AddOrderItem(base.OrderItem{Column: "e.start_date", Asc: true})
  1532. } else {
  1533. page.AddOrderItem(base.OrderItem{Column: "e.start_date", Asc: false})
  1534. }
  1535. } else if req.SortParam == "end_date" {
  1536. if req.SortType == "asc" {
  1537. page.AddOrderItem(base.OrderItem{Column: "e.end_date", Asc: true})
  1538. } else {
  1539. page.AddOrderItem(base.OrderItem{Column: "e.end_date", Asc: false})
  1540. }
  1541. } else {
  1542. resp.Fail("排序字段不正确", c)
  1543. return
  1544. }
  1545. if req.IsExport == 1 {
  1546. page.SetPageSize(10000)
  1547. page.SetCurrent(1)
  1548. }
  1549. cond += ` AND b.contract_amount <> b.invoiced_amount AND b.is_deleted = 0 AND b.contract_amount <> b.payment_amount `
  1550. registerList, total, e := fms.GetInvoiceCensusPageList(page, cond, pars)
  1551. if e != nil {
  1552. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1553. return
  1554. }
  1555. queryRegisterIds := make([]int, 0)
  1556. for _, v := range registerList {
  1557. queryRegisterIds = append(queryRegisterIds, v.ContractRegisterId)
  1558. }
  1559. fmt.Println("queryRegisterIds:", queryRegisterIds)
  1560. results := new(fms.NotInvoicePaymentCensusResp)
  1561. if len(queryRegisterIds) > 0 {
  1562. // 获取合同的套餐金额信息
  1563. serviceAmountList, e := fms.GetContractServiceAmountByContractRegisterIds(queryRegisterIds)
  1564. if e != nil {
  1565. resp.FailData("获取合同的套餐金额信息失败", "Err:"+e.Error(), c)
  1566. return
  1567. }
  1568. serviceAmountMap := make(map[int]map[int]*fms.ContractServiceAmount, 0)
  1569. for _, v := range serviceAmountList {
  1570. if _, ok := serviceAmountMap[v.ContractRegisterId]; !ok {
  1571. serviceAmountMap[v.ContractRegisterId] = make(map[int]*fms.ContractServiceAmount)
  1572. }
  1573. serviceAmountMap[v.ContractRegisterId][v.ProductId] = v
  1574. fmt.Println("ServiceAmount,ProductId", v.ServiceAmount, v.ProductId, v.ContractRegisterId)
  1575. }
  1576. // 获取汇总数据IDs, 用于查询合计数据
  1577. //summaryIdsCond := cond
  1578. //summaryIdsPars := pars
  1579. //if req.SellerIds != "" {
  1580. // sellerIds := strings.Split(req.SellerIds, ",")
  1581. // summaryIdsCond += ` AND c.seller_id in ? AND (d.origin_amount > c.origin_amount OR c.origin_amount IS NULL) `
  1582. // summaryIdsPars = append(summaryIdsPars, sellerIds)
  1583. //} else {
  1584. // summaryIdsCond += ` AND (d.origin_amount > c.origin_amount OR c.origin_amount IS NULL) `
  1585. // summaryIdsPars = append(summaryIdsPars)
  1586. //}
  1587. //summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(summaryIdsCond, summaryIdsPars)
  1588. //if e != nil {
  1589. // resp.FailMsg("获取失败", "获取商品到款汇总IDs失败, Err: "+e.Error(), c)
  1590. // return
  1591. //}
  1592. //fmt.Println("summaryIds:",summaryIds)
  1593. var listErr, totalErr, totalGroupErr error
  1594. wg := sync.WaitGroup{}
  1595. // 响应列表
  1596. respList := make([]*fms.NotPaymentCensusItem, 0)
  1597. summaryList := make([]*fms.NotInvoicePaymentSummaryItem, 0)
  1598. wg.Add(1)
  1599. go func() {
  1600. defer wg.Done()
  1601. // 获取汇总数据
  1602. summaryCond := cond
  1603. summaryCond += ` AND a.register_id IN ?`
  1604. summaryPars := pars
  1605. summaryPars = append(summaryPars, queryRegisterIds)
  1606. //if req.SellerIds != "" {
  1607. // sellerIds := strings.Split(req.SellerIds, ",")
  1608. // summaryCond += ` AND c.seller_id in ? AND a.payment_id <> 0 AND (d.origin_amount > c.origin_amount OR c.origin_amount IS NULL) `
  1609. // summaryPars = append(summaryPars, sellerIds, sellerIds)
  1610. //} else {
  1611. // summaryCond += ` AND a.payment_id <> 0 AND (d.origin_amount > c.origin_amount OR c.origin_amount IS NULL) `
  1612. // summaryPars = append(summaryPars)
  1613. //}
  1614. summaryData, e := fms.GetNotInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  1615. if e != nil {
  1616. resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
  1617. return
  1618. }
  1619. notQueryRegisterIds := make([]int, 0)
  1620. for _, v := range summaryData {
  1621. notQueryRegisterIds = append(notQueryRegisterIds, v.ContractRegisterId)
  1622. }
  1623. noSummaryCond += ` AND b.is_deleted = 0`
  1624. noSummaryCond += ` AND b.contract_register_id IN ? AND b.contract_register_id NOT IN ?`
  1625. noSummaryPars = append(noSummaryPars, queryRegisterIds, notQueryRegisterIds)
  1626. noSummaryData, e := fms.GetNoInvoicePaymentCensusData(noSummaryCond, noSummaryPars)
  1627. if e != nil {
  1628. resp.FailMsg("获取失败", "GetNoInvoicePaymentCensusData, Err: "+e.Error(), c)
  1629. return
  1630. }
  1631. fmt.Println("len(summaryData)", len(summaryData))
  1632. fmt.Println("len(noSummaryData)", len(noSummaryData))
  1633. summaryList = summaryData
  1634. NotInvoiceSummaryMap := make(map[int][]*fms.NotInvoicePaymentSummaryItem, 0)
  1635. for _, v := range summaryList {
  1636. fmt.Println("v2.ContractRegisterId", v.ContractRegisterId)
  1637. NotInvoiceSummaryMap[v.RegisterId] = append(NotInvoiceSummaryMap[v.RegisterId], v)
  1638. }
  1639. summaryList = append(summaryList, noSummaryData...)
  1640. //summaryIds := make([]int, 0)
  1641. //paymentIds := make([]int, 0)
  1642. //for i := range summaryList {
  1643. // //summaryIds = append(summaryIds, summaryList[i].SummaryId)
  1644. //}
  1645. fmt.Println("len(NotInvoiceSummaryMap):", len(NotInvoiceSummaryMap))
  1646. for _, v := range summaryList {
  1647. fmt.Println("ProductIds:", v.ProductIds)
  1648. fmt.Println("ContractRegisterId:", v.ContractRegisterId)
  1649. fmt.Println("ServiceProductId:", v.ServiceProductId)
  1650. fmt.Println("RegisterId:", v.RegisterId)
  1651. fmt.Println("len(NotInvoiceSummaryMap[v.RegisterId]):", len(NotInvoiceSummaryMap[v.ContractRegisterId]))
  1652. if (v.ProductIds == "1,2" || v.ProductIds == "2,1") && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 1 {
  1653. if v.ServiceProductId == 1 {
  1654. item := fms.NotInvoicePaymentSummaryItem{
  1655. NotInvoicedAmountTotal: serviceAmountMap[v.ContractRegisterId][2].ServiceAmount,
  1656. ServiceProductId: 2,
  1657. }
  1658. item.SellerId = v.SellerId
  1659. item.SellerName = v.SellerName
  1660. item.RaiSellerId = v.RaiSellerId
  1661. item.RaiSellerName = v.RaiSellerName
  1662. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item)
  1663. } else {
  1664. item := fms.NotInvoicePaymentSummaryItem{
  1665. NotInvoicedAmountTotal: serviceAmountMap[v.ContractRegisterId][1].ServiceAmount,
  1666. ServiceProductId: 1,
  1667. }
  1668. item.SellerId = v.SellerId
  1669. item.SellerName = v.SellerName
  1670. item.RaiSellerId = v.RaiSellerId
  1671. item.RaiSellerName = v.RaiSellerName
  1672. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item)
  1673. }
  1674. } else if (v.ProductIds == "1,2" || v.ProductIds == "2,1") && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1675. item1 := fms.NotInvoicePaymentSummaryItem{
  1676. NotInvoicedAmountTotal: serviceAmountMap[v.ContractRegisterId][2].ServiceAmount,
  1677. ServiceProductId: 2,
  1678. }
  1679. item1.SellerId = v.SellerId
  1680. item1.SellerName = v.SellerName
  1681. item1.RaiSellerId = v.RaiSellerId
  1682. item1.RaiSellerName = v.RaiSellerName
  1683. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item1)
  1684. item2 := fms.NotInvoicePaymentSummaryItem{
  1685. NotInvoicedAmountTotal: serviceAmountMap[v.ContractRegisterId][1].ServiceAmount,
  1686. ServiceProductId: 1,
  1687. }
  1688. item2.SellerId = v.SellerId
  1689. item2.SellerName = v.SellerName
  1690. item2.RaiSellerId = v.RaiSellerId
  1691. item2.RaiSellerName = v.RaiSellerName
  1692. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item2)
  1693. } else if v.ProductIds == "1" && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1694. item1 := fms.NotInvoicePaymentSummaryItem{
  1695. NotInvoicedAmountTotal: serviceAmountMap[v.ContractRegisterId][1].ServiceAmount,
  1696. ServiceProductId: 1,
  1697. }
  1698. item1.SellerId = v.SellerId
  1699. item1.SellerName = v.SellerName
  1700. item1.RaiSellerId = v.RaiSellerId
  1701. item1.RaiSellerName = v.RaiSellerName
  1702. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item1)
  1703. } else if v.ProductIds == "2" && len(NotInvoiceSummaryMap[v.ContractRegisterId]) == 0 {
  1704. item2 := fms.NotInvoicePaymentSummaryItem{
  1705. NotInvoicedAmountTotal: serviceAmountMap[v.ContractRegisterId][2].ServiceAmount,
  1706. ServiceProductId: 2,
  1707. }
  1708. item2.SellerId = v.SellerId
  1709. item2.SellerName = v.SellerName
  1710. item2.RaiSellerId = v.RaiSellerId
  1711. item2.RaiSellerName = v.RaiSellerName
  1712. NotInvoiceSummaryMap[v.ContractRegisterId] = append(NotInvoiceSummaryMap[v.ContractRegisterId], &item2)
  1713. }
  1714. }
  1715. // 重组汇总数据
  1716. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  1717. if e != nil {
  1718. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  1719. return
  1720. }
  1721. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  1722. for i := range sellerList {
  1723. sellerMap[sellerList[i].SellerId] = sellerList[i]
  1724. }
  1725. sellerTypeMap := map[int]string{2: "FICC销售", 5: "权益销售"}
  1726. // 货币列表
  1727. currencyOB := new(fms.CurrencyUnit)
  1728. currencyCond := `enable = 1`
  1729. currencyPars := make([]interface{}, 0)
  1730. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1731. if e != nil {
  1732. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  1733. return
  1734. }
  1735. unitMap := make(map[string]string)
  1736. for i := range currencyList {
  1737. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1738. }
  1739. for registerId, list := range NotInvoiceSummaryMap {
  1740. for _, v := range list {
  1741. fmt.Println("v.ContractRegisterId", v.ContractRegisterId)
  1742. fmt.Println("v.ServiceProductId:", v.ServiceProductId)
  1743. fmt.Println("v.NotInvoicedAmountTotal:", v.NotInvoicedAmountTotal)
  1744. if v.NotInvoicedAmountTotal == 0 {
  1745. if v.InvoiceAmountTotal > v.PaymentAmountTotal {
  1746. v.NotInvoicedAmountTotal = serviceAmountMap[registerId][v.ServiceProductId].ServiceAmount - v.InvoiceAmountTotal
  1747. } else {
  1748. v.NotInvoicedAmountTotal = serviceAmountMap[registerId][v.ServiceProductId].ServiceAmount - v.PaymentAmountTotal
  1749. }
  1750. }
  1751. if v.SellerId > 0 && v.RaiSellerId > 0 {
  1752. if v.ServiceProductId == 1 {
  1753. v.SellerGroupId = sellerMap[v.SellerId].GroupId
  1754. v.SellerGroupName = sellerMap[v.SellerId].GroupName
  1755. v.SellerType = sellerTypeMap[sellerMap[v.SellerId].DepartmentId]
  1756. } else {
  1757. v.RaiSellerGroupId = sellerMap[v.RaiSellerId].GroupId
  1758. v.RaiSellerGroupName = sellerMap[v.RaiSellerId].GroupName
  1759. v.SellerType = sellerTypeMap[sellerMap[v.RaiSellerId].DepartmentId]
  1760. }
  1761. } else if v.SellerId > 0 && v.RaiSellerId == 0 {
  1762. v.SellerGroupId = sellerMap[v.SellerId].GroupId
  1763. v.SellerGroupName = sellerMap[v.SellerId].GroupName
  1764. v.SellerType = sellerTypeMap[sellerMap[v.SellerId].DepartmentId]
  1765. } else if v.SellerId == 0 && v.RaiSellerId > 0 {
  1766. v.RaiSellerGroupId = sellerMap[v.RaiSellerId].GroupId
  1767. v.RaiSellerGroupName = sellerMap[v.RaiSellerId].GroupName
  1768. v.SellerType = sellerTypeMap[sellerMap[v.RaiSellerId].DepartmentId]
  1769. }
  1770. }
  1771. }
  1772. // 响应列表
  1773. for i := range registerList {
  1774. v := new(fms.NotPaymentCensusItem)
  1775. v.SummaryId = registerList[i].SummaryId
  1776. v.ContractRegisterId = registerList[i].ContractRegisterId
  1777. v.CompanyName = registerList[i].CompanyName
  1778. v.NewCompany = registerList[i].NewCompany
  1779. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  1780. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  1781. v.ContractType = registerList[i].ContractType
  1782. v.ContractCode = registerList[i].ContractCode
  1783. v.ContractAmount = registerList[i].ContractAmount
  1784. v.UnitName = unitMap[registerList[i].CurrencyUnit]
  1785. v.ProductIds = registerList[i].ProductIds
  1786. //if registerList[i].InvoicedAmount != 0 {
  1787. // v.NotInvoiceTotal = registerList[i].ContractAmount - registerList[i].InvoicedAmount
  1788. //} else {
  1789. // v.NotInvoiceTotal = registerList[i].ContractAmount - registerList[i].PaymentAmount
  1790. //}
  1791. v.NotInvoiceList = NotInvoiceSummaryMap[registerList[i].ContractRegisterId]
  1792. respList = append(respList, v)
  1793. }
  1794. }()
  1795. // 开票到款金额合计(换算后)
  1796. //var invoiceTotal, paymentTotal, contractAmount float64
  1797. //wg.Add(1)
  1798. //go func() {
  1799. // defer wg.Done()
  1800. //
  1801. // if len(summaryIds) == 0 {
  1802. // return
  1803. // }
  1804. // amountTotalCond := `a.id IN ?`
  1805. // amountTotalPars := make([]interface{}, 0)
  1806. // amountTotalPars = append(amountTotalPars, summaryIds)
  1807. // invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
  1808. // if e != nil {
  1809. // totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
  1810. // return
  1811. // }
  1812. // invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
  1813. // paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
  1814. // if e != nil {
  1815. // totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
  1816. // return
  1817. // }
  1818. // paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
  1819. //}()
  1820. // 开票到款金额合计(换算后)V2
  1821. var invoiceTotal, contractAmount float64
  1822. wg.Add(1)
  1823. go func() {
  1824. defer wg.Done()
  1825. registerList, e := fms.GetInvoiceCensusList(cond, pars)
  1826. if e != nil {
  1827. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1828. return
  1829. }
  1830. contractIdSumMap := make(map[int]int)
  1831. for _, v := range registerList {
  1832. if v.InvoicedAmountCount >= v.PaymentAmountCount {
  1833. invoiceTotal += v.InvoicedAmountCount
  1834. } else if v.InvoicedAmountCount == 0 {
  1835. invoiceTotal += v.PaymentAmountCount
  1836. }
  1837. rate := v.RMBRate
  1838. if rate == 0.0 {
  1839. rate = 1.0
  1840. }
  1841. if _,ok := contractIdSumMap[v.ContractRegisterId]; !ok{
  1842. contractIdSumMap[v.ContractRegisterId] = 1
  1843. contractAmount += v.ContractAmount / v.RMBRate
  1844. }
  1845. }
  1846. }()
  1847. // 分币种金额统计
  1848. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1849. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1850. contractAmountCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1851. wg.Add(1)
  1852. go func() {
  1853. defer wg.Done()
  1854. currencyOB := new(fms.CurrencyUnit)
  1855. currencyCond := `enable = 1`
  1856. currencyPars := make([]interface{}, 0)
  1857. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1858. if e != nil {
  1859. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  1860. return
  1861. }
  1862. unitMap := make(map[string]string)
  1863. for i := range currencyList {
  1864. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1865. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1866. Name: currencyList[i].Name,
  1867. UnitName: currencyList[i].UnitName,
  1868. Code: currencyList[i].Code,
  1869. FlagImg: currencyList[i].FlagImg,
  1870. })
  1871. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1872. Name: currencyList[i].Name,
  1873. UnitName: currencyList[i].UnitName,
  1874. Code: currencyList[i].Code,
  1875. FlagImg: currencyList[i].FlagImg,
  1876. })
  1877. contractAmountCurrencyTotals = append(contractAmountCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  1878. Name: currencyList[i].Name,
  1879. UnitName: currencyList[i].UnitName,
  1880. Code: currencyList[i].Code,
  1881. FlagImg: currencyList[i].FlagImg,
  1882. })
  1883. }
  1884. registerList, e := fms.GetInvoiceCensusList(cond, pars)
  1885. if e != nil {
  1886. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  1887. return
  1888. }
  1889. invoiceSumMap := make(map[string]float64)
  1890. contractSumMap := make(map[string]float64)
  1891. contractIdSumMap := make(map[int]int)
  1892. for _, v := range registerList {
  1893. if v.InvoiceOrigin >= v.PaymentOrigin {
  1894. invoiceSumMap[v.CurrencyUnit] += v.InvoicedAmount
  1895. } else {
  1896. invoiceSumMap[v.CurrencyUnit] += v.PaymentAmount
  1897. }
  1898. if _,ok := contractIdSumMap[v.ContractRegisterId]; !ok{
  1899. contractIdSumMap[v.ContractRegisterId] = 1
  1900. contractSumMap[v.CurrencyUnit] += v.ContractAmount
  1901. }
  1902. }
  1903. for _, v := range contractAmountCurrencyTotals {
  1904. v.Amount = contractSumMap[v.Code] - invoiceSumMap[v.Code]
  1905. }
  1906. }()
  1907. wg.Wait()
  1908. if listErr != nil {
  1909. resp.FailMsg("获取失败", listErr.Error(), c)
  1910. return
  1911. }
  1912. if totalErr != nil {
  1913. resp.FailMsg("获取失败", totalErr.Error(), c)
  1914. return
  1915. }
  1916. if totalGroupErr != nil {
  1917. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  1918. return
  1919. }
  1920. results.DataList = respList
  1921. results.InvoiceTotal = invoiceTotal
  1922. results.NotInvoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", contractAmount-invoiceTotal), 64)
  1923. results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  1924. results.PaymentCurrencyTotal = paymentCurrencyTotals
  1925. results.NotInvoiceCurrencyTotal = contractAmountCurrencyTotals
  1926. }
  1927. // 是否导出
  1928. if req.IsExport == 1 {
  1929. ExportNotInvoiceCensusList(c, results)
  1930. return
  1931. }
  1932. page.SetTotal(total)
  1933. baseData := new(base.BaseData)
  1934. baseData.SetPage(page)
  1935. baseData.SetList(results)
  1936. resp.OkData("获取成功", baseData, c)
  1937. }
  1938. // List
  1939. // @Title 开票未到款统计列表
  1940. // @Description 开票未到款统计列表
  1941. // @Param Keyword query string false "关键词"
  1942. // @Param SellGroupId query int false "销售组别ID"
  1943. // @Param ServiceType query int false "套餐类型"
  1944. // @Param StartDate query string false "合同开始日期"
  1945. // @Param EndDate query string false "合同结束日期"
  1946. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  1947. // @Param HasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
  1948. // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
  1949. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  1950. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  1951. // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'invoice_time':开票日 、 'payment_date':到款日"
  1952. // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
  1953. // @Success 200 {object} fms.ContractRegisterItem
  1954. // @router /census/invoice_payment/not_payment/list [get]
  1955. func (ct *InvoicePaymentController) NotPaymentList(c *gin.Context) {
  1956. var req fms.InvoicePaymentCensusListReq
  1957. if e := c.BindQuery(&req); e != nil {
  1958. err, ok := e.(validator.ValidationErrors)
  1959. if !ok {
  1960. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1961. return
  1962. }
  1963. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1964. return
  1965. }
  1966. cond := `1 = 1`
  1967. pars := make([]interface{}, 0)
  1968. // 客户姓名/销售
  1969. if req.Keyword != "" {
  1970. kw := "%" + req.Keyword + "%"
  1971. cond += ` AND (b.company_name LIKE ? OR b.contract_code LIKE ?)`
  1972. pars = append(pars, kw, kw)
  1973. }
  1974. if req.SellerIds != "" {
  1975. sellerIds := strings.Split(req.SellerIds, ",")
  1976. cond += ` AND (c.seller_id in ?)`
  1977. pars = append(pars, sellerIds)
  1978. }
  1979. // 套餐筛选
  1980. if req.ServiceTypes != "" {
  1981. serviceTypes := strings.Split(req.ServiceTypes, ",")
  1982. tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  1983. if e != nil {
  1984. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  1985. return
  1986. }
  1987. if len(tempRegisterIds) > 0 {
  1988. cond += ` AND a.register_id IN ?`
  1989. pars = append(pars, tempRegisterIds)
  1990. } else {
  1991. cond += ` AND 1 = 2`
  1992. }
  1993. }
  1994. if req.ListParam == 1 {
  1995. cond += ` AND a.service_product_id = 1 `
  1996. } else if req.ListParam == 2 {
  1997. cond += ` AND a.service_product_id = 2 `
  1998. }
  1999. page := new(base.Page)
  2000. page.SetPageSize(req.PageSize)
  2001. page.SetCurrent(req.Current)
  2002. //排序
  2003. if req.SortType == "" {
  2004. req.SortType = "asc"
  2005. }
  2006. if req.SortType != "desc" && req.SortType != "asc" {
  2007. resp.Fail("排序类型不正确", c)
  2008. return
  2009. }
  2010. if req.SortType == "asc" {
  2011. page.AddOrderItem(base.OrderItem{Column: "e.invoice_time", Asc: true})
  2012. page.AddOrderItem(base.OrderItem{Column: "e.modify_time", Asc: false})
  2013. } else {
  2014. page.AddOrderItem(base.OrderItem{Column: "e.invoice_time", Asc: false})
  2015. page.AddOrderItem(base.OrderItem{Column: "e.modify_time", Asc: false})
  2016. }
  2017. if req.IsExport == 1 {
  2018. page.SetPageSize(10000)
  2019. page.SetCurrent(1)
  2020. }
  2021. registerList, total, e := fms.GetNoPaymentCensusPageList(page, cond, pars)
  2022. if e != nil {
  2023. resp.FailMsg("获取失败", "获取商品到款统计列表总数失败, Err: "+e.Error(), c)
  2024. return
  2025. }
  2026. queryRegisterIds := make([]int, 0)
  2027. for i := range registerList {
  2028. queryRegisterIds = append(queryRegisterIds, registerList[i].ContractRegisterId)
  2029. }
  2030. fmt.Println("queryRegisterIds:", queryRegisterIds)
  2031. //fmt.Println("queryRegisterIds:",queryRegisterIds)
  2032. results := new(fms.NotInvoicePaymentCensusResp)
  2033. if len(queryRegisterIds) > 0 {
  2034. // 获取汇总数据IDs, 用于查询合计数据
  2035. summaryIdsCond := cond
  2036. summaryIdsPars := pars
  2037. if req.SellerIds != "" {
  2038. sellerIds := strings.Split(req.SellerIds, ",")
  2039. summaryIdsCond += ` AND c.seller_id in ? AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2040. summaryIdsPars = append(summaryIdsPars, sellerIds)
  2041. } else {
  2042. summaryIdsCond += ` AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2043. summaryIdsPars = append(summaryIdsPars)
  2044. }
  2045. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(summaryIdsCond, summaryIdsPars)
  2046. if e != nil {
  2047. resp.FailMsg("获取失败", "获取商品到款汇总IDs失败, Err: "+e.Error(), c)
  2048. return
  2049. }
  2050. //fmt.Println("summaryIds:",summaryIds)
  2051. var listErr, totalErr, totalGroupErr error
  2052. wg := sync.WaitGroup{}
  2053. // 响应列表
  2054. respList := make([]*fms.NotPaymentCensusItem, 0)
  2055. summaryList := make([]*fms.InvoicePaymentSummaryItem, 0)
  2056. wg.Add(1)
  2057. go func() {
  2058. defer wg.Done()
  2059. // 获取汇总数据
  2060. summaryCond := cond
  2061. summaryCond += ` AND a.register_id IN ?`
  2062. summaryPars := pars
  2063. summaryPars = append(summaryPars, queryRegisterIds)
  2064. if req.SellerIds != "" {
  2065. sellerIds := strings.Split(req.SellerIds, ",")
  2066. summaryCond += ` AND c.seller_id in ? AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2067. summaryPars = append(summaryPars, sellerIds)
  2068. } else {
  2069. summaryCond += ` AND a.invoice_id <> 0 AND (c.origin_amount > d.origin_amount OR d.origin_amount IS NULL) `
  2070. summaryPars = append(summaryPars)
  2071. }
  2072. summaryData, e := fms.GetInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  2073. if e != nil {
  2074. resp.FailMsg("获取失败", "获取商品到款汇总列表失败, Err: "+e.Error(), c)
  2075. return
  2076. }
  2077. summaryList = summaryData
  2078. //summaryIds := make([]int, 0)
  2079. //for i := range summaryList {
  2080. // //summaryIds = append(summaryIds, summaryList[i].SummaryId)
  2081. //
  2082. //}
  2083. // 货币列表
  2084. currencyOB := new(fms.CurrencyUnit)
  2085. currencyCond := `enable = 1`
  2086. currencyPars := make([]interface{}, 0)
  2087. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  2088. if e != nil {
  2089. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  2090. return
  2091. }
  2092. unitMap := make(map[string]string)
  2093. for i := range currencyList {
  2094. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  2095. }
  2096. //// 获取合同的套餐金额信息
  2097. //serviceAmountList, e := fms.GetContractServiceAmountByContractRegisterIds(queryRegisterIds)
  2098. //if e != nil {
  2099. // resp.FailData("获取合同的套餐金额信息失败", "Err:"+e.Error(), c)
  2100. // return
  2101. //}
  2102. //serviceAmountMap := make(map[int]map[int]*fms.ContractServiceAmount, 0)
  2103. //for _, v := range serviceAmountList {
  2104. // if _, ok := serviceAmountMap[v.ContractRegisterId]; !ok {
  2105. // serviceAmountMap[v.ContractRegisterId] = make(map[int]*fms.ContractServiceAmount)
  2106. // }
  2107. // serviceAmountMap[v.ContractRegisterId][v.ProductId] = v
  2108. //}
  2109. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  2110. if e != nil {
  2111. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  2112. return
  2113. }
  2114. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  2115. for i := range sellerList {
  2116. sellerMap[sellerList[i].SellerId] = sellerList[i]
  2117. }
  2118. sellerTypeMap := map[int]int{crm.SellerDepartmentId: 1, crm.RaiSellerDepartmentId: 2}
  2119. // 重组汇总数据
  2120. summaryMap := make(map[int][]*fms.NotPaymentCensusInfo)
  2121. for i := range summaryList {
  2122. v := new(fms.NotPaymentCensusInfo)
  2123. v.InvoiceId = summaryList[i].InvoiceId
  2124. v.InvoiceDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].InvoiceDate)
  2125. v.InvoiceAmount = summaryList[i].InvoiceAmount
  2126. v.SellerId = summaryList[i].SellerId
  2127. v.SellerName = summaryList[i].SellerName
  2128. v.SellerGroupId = summaryList[i].SellerGroupId
  2129. v.SellerGroupName = summaryList[i].SellerGroupName
  2130. v.SellerType = sellerTypeMap[sellerMap[summaryList[i].SellerId].DepartmentId]
  2131. v.PaymentId = summaryList[i].PaymentId
  2132. v.PaymentDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].PaymentDate)
  2133. v.PaymentAmount = summaryList[i].PaymentAmount
  2134. v.PayType = summaryList[i].PayType
  2135. v.NotPaymentAmount = summaryList[i].InvoiceAmount - summaryList[i].PaymentAmount
  2136. v.ServiceProductId = summaryList[i].ServiceProductId
  2137. v.UnitName = unitMap[summaryList[i].CurrencyUnit]
  2138. summaryMap[summaryList[i].SummaryId] = append(summaryMap[summaryList[i].SummaryId], v)
  2139. }
  2140. // 响应列表
  2141. for i := range registerList {
  2142. v := new(fms.NotPaymentCensusItem)
  2143. v.SummaryId = registerList[i].SummaryId
  2144. v.ContractRegisterId = registerList[i].ContractRegisterId
  2145. v.CompanyName = registerList[i].CompanyName
  2146. v.NewCompany = registerList[i].NewCompany
  2147. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  2148. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  2149. v.InvoicePaymentList = summaryMap[registerList[i].SummaryId]
  2150. v.ContractType = registerList[i].ContractType
  2151. v.ContractCode = registerList[i].ContractCode
  2152. v.ContractAmount = registerList[i].ContractAmount
  2153. v.UnitName = unitMap[registerList[i].CurrencyUnit]
  2154. v.ProductIds = registerList[i].ProductIds
  2155. respList = append(respList, v)
  2156. }
  2157. }()
  2158. // 开票到款金额合计(换算后)
  2159. var invoiceTotal, paymentTotal float64
  2160. wg.Add(1)
  2161. go func() {
  2162. defer wg.Done()
  2163. if len(summaryIds) == 0 {
  2164. return
  2165. }
  2166. amountTotalCond := `a.id IN ?`
  2167. amountTotalPars := make([]interface{}, 0)
  2168. amountTotalPars = append(amountTotalPars, summaryIds)
  2169. invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
  2170. if e != nil {
  2171. totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
  2172. return
  2173. }
  2174. invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
  2175. paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
  2176. if e != nil {
  2177. totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
  2178. return
  2179. }
  2180. paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
  2181. }()
  2182. // 分币种金额统计
  2183. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2184. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2185. notpaymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2186. //contractAmountCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2187. wg.Add(1)
  2188. go func() {
  2189. defer wg.Done()
  2190. currencyOB := new(fms.CurrencyUnit)
  2191. currencyCond := `enable = 1`
  2192. currencyPars := make([]interface{}, 0)
  2193. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  2194. if e != nil {
  2195. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  2196. return
  2197. }
  2198. unitMap := make(map[string]string)
  2199. for i := range currencyList {
  2200. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  2201. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2202. Name: currencyList[i].Name,
  2203. UnitName: currencyList[i].UnitName,
  2204. Code: currencyList[i].Code,
  2205. FlagImg: currencyList[i].FlagImg,
  2206. })
  2207. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2208. Name: currencyList[i].Name,
  2209. UnitName: currencyList[i].UnitName,
  2210. Code: currencyList[i].Code,
  2211. FlagImg: currencyList[i].FlagImg,
  2212. })
  2213. notpaymentCurrencyTotals = append(notpaymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2214. Name: currencyList[i].Name,
  2215. UnitName: currencyList[i].UnitName,
  2216. Code: currencyList[i].Code,
  2217. FlagImg: currencyList[i].FlagImg,
  2218. })
  2219. //contractAmountCurrencyTotals = append(contractAmountCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  2220. // Name: currencyList[i].Name,
  2221. // UnitName: currencyList[i].UnitName,
  2222. // Code: currencyList[i].Code,
  2223. // FlagImg: currencyList[i].FlagImg,
  2224. //})
  2225. }
  2226. if len(summaryIds) == 0 {
  2227. return
  2228. }
  2229. totalGroupCond := `a.id IN ?`
  2230. totalGroupPars := make([]interface{}, 0)
  2231. totalGroupPars = append(totalGroupPars, summaryIds)
  2232. invoiceSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 1)
  2233. if e != nil {
  2234. totalGroupErr = fmt.Errorf("获取汇总货币合计开票金额失败, Err: %s", e.Error())
  2235. return
  2236. }
  2237. paymentSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 2)
  2238. if e != nil {
  2239. totalGroupErr = fmt.Errorf("获取汇总货币合计到款金额失败, Err: %s", e.Error())
  2240. return
  2241. }
  2242. invoiceSumMap := make(map[string]float64)
  2243. paymentSumMap := make(map[string]float64)
  2244. //contractSumMap := make(map[string]float64)
  2245. for i := range invoiceSumGroup {
  2246. invoiceSumMap[invoiceSumGroup[i].CurrencyUnit] = invoiceSumGroup[i].OriginAmountTotal
  2247. continue
  2248. }
  2249. for i := range paymentSumGroup {
  2250. paymentSumMap[paymentSumGroup[i].CurrencyUnit] = paymentSumGroup[i].OriginAmountTotal
  2251. continue
  2252. }
  2253. for i := range invoiceCurrencyTotals {
  2254. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
  2255. invoiceCurrencyTotals[i].Amount = a
  2256. }
  2257. for i := range paymentCurrencyTotals {
  2258. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  2259. paymentCurrencyTotals[i].Amount = a
  2260. }
  2261. for i := range notpaymentCurrencyTotals {
  2262. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]-paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  2263. notpaymentCurrencyTotals[i].Amount = a
  2264. }
  2265. //contractRegisters, err := fms.GetContractInfoByRegisterIds(queryRegisterIds)
  2266. //if err != nil {
  2267. // resp.FailMsg("查询合同信息失败", "查询合同信息失败, Err: "+err.Error(), c)
  2268. // return
  2269. //}
  2270. //for _, v := range contractRegisters {
  2271. // if v.RMBRate == 0.0 {
  2272. // v.RMBRate = 1
  2273. // }
  2274. // amount, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", v.ContractAmount/v.RMBRate), 64)
  2275. // contractAmount += amount
  2276. // contractSumMap[v.CurrencyUnit] = v.ContractAmount
  2277. //}
  2278. //for _, v := range contractAmountCurrencyTotals {
  2279. // v.Amount = contractSumMap[v.Code] - invoiceSumMap[v.Code]
  2280. //}
  2281. }()
  2282. wg.Wait()
  2283. if listErr != nil {
  2284. resp.FailMsg("获取失败", listErr.Error(), c)
  2285. return
  2286. }
  2287. if totalErr != nil {
  2288. resp.FailMsg("获取失败", totalErr.Error(), c)
  2289. return
  2290. }
  2291. if totalGroupErr != nil {
  2292. resp.FailMsg("获取失败", totalGroupErr.Error(), c)
  2293. return
  2294. }
  2295. results.DataList = respList
  2296. results.InvoiceTotal = invoiceTotal
  2297. results.PaymentTotal = paymentTotal
  2298. results.NotPaymentTotal = invoiceTotal - paymentTotal
  2299. results.NotPaymentCurrencyTotal = notpaymentCurrencyTotals
  2300. }
  2301. // 是否导出
  2302. if req.IsExport == 1 {
  2303. ExportNotPaymentCensusList(c, results)
  2304. return
  2305. }
  2306. page.SetTotal(total)
  2307. baseData := new(base.BaseData)
  2308. baseData.SetPage(page)
  2309. baseData.SetList(results)
  2310. resp.OkData("获取成功", baseData, c)
  2311. }
  2312. // ExportNotInvoiceCensusList 导出未开票统计列表
  2313. func ExportNotInvoiceCensusList(c *gin.Context, results *fms.NotInvoicePaymentCensusResp) {
  2314. list := results.DataList
  2315. if len(list) == 0 {
  2316. resp.Fail("列表数据为空", c)
  2317. return
  2318. }
  2319. // 生成Excel文件
  2320. xlsxFile := xlsx.NewFile()
  2321. style := xlsx.NewStyle()
  2322. alignment := xlsx.Alignment{
  2323. Horizontal: "center",
  2324. Vertical: "center",
  2325. WrapText: true,
  2326. }
  2327. style.Alignment = alignment
  2328. style.ApplyAlignment = true
  2329. sheetName := "未开票统计表"
  2330. sheet, err := xlsxFile.AddSheet(sheetName)
  2331. if err != nil {
  2332. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  2333. return
  2334. }
  2335. // 数据表头
  2336. rowTitle := []string{"序号", "客户名称", "合同编号", "合同开始时间", "合同结束时间", "合同金额", "金额单位", "未开票金额", "套餐类型", "销售", "销售组别", "销售类型"}
  2337. titleRow := sheet.AddRow()
  2338. for i := range rowTitle {
  2339. v := titleRow.AddCell()
  2340. v.SetString(rowTitle[i])
  2341. v.SetStyle(style)
  2342. }
  2343. incomeSummaryItemList := make([]*fms.NotPaymentCensusItem, 0)
  2344. incomeSummaryItemList = list
  2345. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  2346. if e != nil {
  2347. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  2348. return
  2349. }
  2350. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  2351. for i := range sellerList {
  2352. sellerMap[sellerList[i].SellerId] = sellerList[i]
  2353. }
  2354. sellerTypeMap := map[int]string{2: "FICC销售", 5: "权益销售"}
  2355. serviceProductIdMap := map[int]string{
  2356. 1: "FICC套餐",
  2357. 2: "权益套餐",
  2358. }
  2359. // 填充数据
  2360. for i, v := range incomeSummaryItemList {
  2361. dataRow := sheet.AddRow()
  2362. dataRow2 := sheet.AddRow()
  2363. cell := dataRow.AddCell()
  2364. cell.VMerge = 1
  2365. cell.SetString(strconv.Itoa(i + 1)) //序号
  2366. dataRow2.AddCell().SetString("")
  2367. cell2 := dataRow.AddCell()
  2368. cell2.VMerge = 1
  2369. cell2.SetString(v.CompanyName) // 客户名称
  2370. dataRow2.AddCell().SetString("")
  2371. cell3 := dataRow.AddCell()
  2372. cell3.VMerge = 1
  2373. cell3.SetString(v.ContractCode) // 合同编号
  2374. dataRow2.AddCell().SetString("")
  2375. cell4 := dataRow.AddCell()
  2376. cell4.VMerge = 1
  2377. cell4.SetString(v.StartDate) // 合同开始时间
  2378. dataRow2.AddCell().SetString("")
  2379. cell5 := dataRow.AddCell()
  2380. cell5.VMerge = 1
  2381. cell5.SetString(v.EndDate) // 合同结束时间
  2382. dataRow2.AddCell().SetString("")
  2383. cell6 := dataRow.AddCell()
  2384. cell6.VMerge = 1
  2385. cell6.SetString(fmt.Sprintf("%.2f", v.ContractAmount)) // 合同金额
  2386. dataRow2.AddCell().SetString("")
  2387. cell7 := dataRow.AddCell()
  2388. cell7.VMerge = 1
  2389. cell7.SetString(v.UnitName) // 金额单位
  2390. dataRow2.AddCell().SetString("")
  2391. for j, item := range v.NotInvoiceList {
  2392. if j == 1 {
  2393. dataRow2.AddCell().SetString(fmt.Sprintf("%.2f", item.NotInvoicedAmountTotal)) // 未开票金额
  2394. dataRow2.AddCell().SetString(serviceProductIdMap[item.ServiceProductId]) // 套餐类型
  2395. if item.SellerId > 0 && item.RaiSellerId > 0 {
  2396. if item.ServiceProductId == 1 {
  2397. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2398. item.SellerType = sellerTypeMap[sellerMap[item.SellerId].DepartmentId]
  2399. dataRow2.AddCell().SetString(item.SellerName) // 销售
  2400. dataRow2.AddCell().SetString(item.SellerGroupName) // 销售组别
  2401. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2402. } else {
  2403. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2404. item.SellerType = sellerTypeMap[sellerMap[item.RaiSellerId].DepartmentId]
  2405. dataRow2.AddCell().SetString(item.RaiSellerName) // 销售
  2406. dataRow2.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2407. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2408. }
  2409. } else if item.SellerId > 0 && item.RaiSellerId == 0 {
  2410. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2411. item.SellerType = sellerTypeMap[sellerMap[item.SellerId].DepartmentId]
  2412. dataRow2.AddCell().SetString(item.SellerName) // 销售
  2413. dataRow2.AddCell().SetString(item.SellerGroupName) // 销售组别
  2414. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2415. } else if item.SellerId == 0 && item.RaiSellerId > 0 {
  2416. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2417. item.SellerType = sellerTypeMap[sellerMap[item.RaiSellerId].DepartmentId]
  2418. dataRow2.AddCell().SetString(item.RaiSellerName) // 销售
  2419. dataRow2.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2420. dataRow2.AddCell().SetString(item.SellerType) // 销售类型
  2421. }
  2422. } else {
  2423. dataRow.AddCell().SetString(fmt.Sprintf("%.2f", item.NotInvoicedAmountTotal)) // 未开票金额
  2424. dataRow.AddCell().SetString(serviceProductIdMap[item.ServiceProductId]) // 套餐类型
  2425. if item.SellerId > 0 && item.RaiSellerId > 0 {
  2426. if item.ServiceProductId == 1 {
  2427. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2428. item.SellerType = sellerTypeMap[sellerMap[item.SellerId].DepartmentId]
  2429. dataRow.AddCell().SetString(item.SellerName) // 销售
  2430. dataRow.AddCell().SetString(item.SellerGroupName) // 销售组别
  2431. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2432. } else {
  2433. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2434. item.SellerType = sellerTypeMap[sellerMap[item.RaiSellerId].DepartmentId]
  2435. dataRow.AddCell().SetString(item.RaiSellerName) // 销售
  2436. dataRow.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2437. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2438. }
  2439. } else if item.SellerId > 0 && item.RaiSellerId == 0 {
  2440. item.SellerGroupName = sellerMap[item.SellerId].GroupName
  2441. item.SellerType = sellerTypeMap[sellerMap[item.SellerId].DepartmentId]
  2442. dataRow.AddCell().SetString(item.SellerName) // 销售
  2443. dataRow.AddCell().SetString(item.SellerGroupName) // 销售组别
  2444. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2445. } else if item.SellerId == 0 && item.RaiSellerId > 0 {
  2446. item.RaiSellerGroupName = sellerMap[item.RaiSellerId].GroupName
  2447. item.SellerType = sellerTypeMap[sellerMap[item.RaiSellerId].DepartmentId]
  2448. dataRow.AddCell().SetString(item.RaiSellerName) // 销售
  2449. dataRow.AddCell().SetString(item.RaiSellerGroupName) // 销售组别
  2450. dataRow.AddCell().SetString(item.SellerType) // 销售类型
  2451. }
  2452. }
  2453. }
  2454. }
  2455. // 输出文件
  2456. var buffer bytes.Buffer
  2457. _ = xlsxFile.Write(&buffer)
  2458. content := bytes.NewReader(buffer.Bytes())
  2459. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2460. fileName := sheetName + randStr + ".xlsx"
  2461. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  2462. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2463. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  2464. }
  2465. // ExportNotPaymentCensusList 导出开票未到款统计列表
  2466. func ExportNotPaymentCensusList(c *gin.Context, results *fms.NotInvoicePaymentCensusResp) {
  2467. list := results.DataList
  2468. if len(list) == 0 {
  2469. resp.Fail("列表数据为空", c)
  2470. return
  2471. }
  2472. // 生成Excel文件
  2473. xlsxFile := xlsx.NewFile()
  2474. style := xlsx.NewStyle()
  2475. alignment := xlsx.Alignment{
  2476. Horizontal: "center",
  2477. Vertical: "center",
  2478. WrapText: true,
  2479. }
  2480. style.Alignment = alignment
  2481. style.ApplyAlignment = true
  2482. sheet, err := xlsxFile.AddSheet("开票未到款统计")
  2483. if err != nil {
  2484. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  2485. return
  2486. }
  2487. _ = sheet.SetColWidth(1, 1, 30)
  2488. _ = sheet.SetColWidth(3, 3, 30)
  2489. // 前三行-开票金额合计
  2490. rowA := sheet.AddRow()
  2491. cellAA := rowA.AddCell()
  2492. cellAA.SetString(fmt.Sprintf("开票未到款合计金额(换算后):%.2f(元)", results.InvoiceTotal))
  2493. rowBData := "开票未到款金额:"
  2494. for _, v := range results.NotPaymentCurrencyTotal {
  2495. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  2496. }
  2497. rowB := sheet.AddRow()
  2498. rowB.AddCell().SetString(rowBData)
  2499. sheet.AddRow()
  2500. // 表头, 套餐动态获取
  2501. rowTitle := []string{"序号", "客户名称", "合同编号", "合同有效期", "套餐类型", "开票日", "开票金额", "金额单位", "开票销售",
  2502. "销售组别", "销售类型"}
  2503. titleRow := sheet.AddRow()
  2504. for i := range rowTitle {
  2505. v := titleRow.AddCell()
  2506. v.SetString(rowTitle[i])
  2507. v.SetStyle(style)
  2508. }
  2509. serviceProductIdMap := map[int]string{
  2510. 1: "FICC套餐",
  2511. 2: "权益套餐",
  2512. }
  2513. sellerTypeMap := map[int]string{1: "FICC销售", 2: "权益销售"}
  2514. for k, v := range list {
  2515. dataRow := sheet.AddRow()
  2516. // 前四个单元格根据每行开票到款条数向下合并
  2517. l := len(v.InvoicePaymentList)
  2518. mergeRowNum := l - 1
  2519. // 序号
  2520. sortNum := k + 1
  2521. colA := dataRow.AddCell()
  2522. colA.VMerge = mergeRowNum
  2523. colA.SetString(fmt.Sprint(sortNum))
  2524. // 客户名称
  2525. colB := dataRow.AddCell()
  2526. colB.VMerge = mergeRowNum
  2527. colB.SetString(v.CompanyName)
  2528. // 合同编号
  2529. colC := dataRow.AddCell()
  2530. colC.VMerge = mergeRowNum
  2531. colC.SetString(v.ContractCode)
  2532. // 合同有效期
  2533. colD := dataRow.AddCell()
  2534. colD.VMerge = mergeRowNum
  2535. colD.SetString(fmt.Sprint(v.StartDate, "至", v.EndDate))
  2536. // 套餐类型
  2537. colE := dataRow.AddCell()
  2538. colE.VMerge = mergeRowNum
  2539. colE.SetString(serviceProductIdMap[v.InvoicePaymentList[0].ServiceProductId])
  2540. // 开票到款信息
  2541. for _, v2 := range v.InvoicePaymentList {
  2542. rowData := []string{
  2543. v2.InvoiceDate, // 开票日
  2544. fmt.Sprint(v2.InvoiceAmount), // 开票金额
  2545. v2.UnitName, // 开票金额
  2546. v2.SellerName, // 销售
  2547. v2.SellerGroupName, // 组别
  2548. sellerTypeMap[v2.SellerType], // 销售类型
  2549. }
  2550. for i := range rowData {
  2551. dataRow.AddCell().SetString(rowData[i])
  2552. }
  2553. }
  2554. }
  2555. // 输出文件
  2556. var buffer bytes.Buffer
  2557. _ = xlsxFile.Write(&buffer)
  2558. content := bytes.NewReader(buffer.Bytes())
  2559. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2560. fileName := "商品到款统计_" + randStr + ".xlsx"
  2561. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  2562. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2563. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  2564. }