invoice_payment.go 96 KB

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