invoice_payment.go 97 KB

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