invoice_payment.go 97 KB

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