seller.go 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  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/shopspring/decimal"
  8. "github.com/tealeg/xlsx"
  9. "hongze/fms_api/controller/resp"
  10. "hongze/fms_api/global"
  11. "hongze/fms_api/models/base"
  12. "hongze/fms_api/models/crm"
  13. "hongze/fms_api/models/fms"
  14. crmService "hongze/fms_api/services/crm"
  15. "hongze/fms_api/utils"
  16. "net/http"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "time"
  21. )
  22. // SellerController 销售统计
  23. type SellerController struct{}
  24. // GroupInvoiceList
  25. // @Title 销售组开票统计列表-弃用
  26. // @Description 销售组开票统计列表-弃用
  27. // @Param StartDate query string false "开始日期"
  28. // @Param EndDate query string false "结束日期"
  29. // @Param SortField query int false "排序字段: 1-开票金额; 2-组别占比"
  30. // @Param SortType query int false "排序方式: 1-正序; 2-倒序"
  31. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  32. // @Success 200 {object} fms.CensusSellerGroupInvoiceItem
  33. // @router /census/seller/group_invoice_list [get]
  34. //func (ct *SellerController) GroupInvoiceList(c *gin.Context) {
  35. // var req fms.CensusSellerGroupInvoiceListReq
  36. // if e := c.BindQuery(&req); e != nil {
  37. // err, ok := e.(validator.ValidationErrors)
  38. // if !ok {
  39. // resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  40. // return
  41. // }
  42. // resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  43. // return
  44. // }
  45. // var departmentId int
  46. // if req.SellerType == 1 {
  47. // departmentId = crm.SellerDepartmentId
  48. // } else if req.SellerType == 2 {
  49. // departmentId = crm.RaiSellerDepartmentId
  50. // } else if req.SellerType == 0 {
  51. // resp.Fail("请选择销售类型", c)
  52. // return
  53. // } else {
  54. // resp.Fail("请选择正确的销售类型", c)
  55. // return
  56. // }
  57. // outCond := ` department_id = %d AND parent_id = 0 `
  58. // outCond = fmt.Sprintf(outCond, departmentId)
  59. // cond := ` (invoice_type = %d OR invoice_type = %d) AND a.is_deleted = 0 AND a.seller_id != 0 `
  60. // cond = fmt.Sprintf(cond, fms.ContractInvoiceTypeMake, fms.ContractInvoiceTypePreMake)
  61. //
  62. // //adminCond := ` (invoice_type = %d OR invoice_type = %d) AND is_deleted = 0 AND seller_group_id != 0 `
  63. // //adminCond = fmt.Sprintf(cond, fms.ContractInvoiceTypeMake, fms.ContractInvoiceTypePreMake)
  64. // pars := make([]interface{}, 0)
  65. // // 开票日期
  66. // if req.StartDate != "" && req.EndDate != "" {
  67. // st := fmt.Sprint(req.StartDate, " 00:00:00")
  68. // ed := fmt.Sprint(req.EndDate, " 23:59:59")
  69. // cond += ` AND (invoice_time BETWEEN '%s' AND '%s')`
  70. // cond = fmt.Sprintf(cond, st, ed)
  71. //
  72. // //adminCond += ` AND (invoice_time BETWEEN '%s' AND '%s')`
  73. // //adminCond = fmt.Sprintf(cond, st, ed)
  74. // }
  75. //
  76. // if req.CompanyType == 1 {
  77. // cond += ` AND b.contract_type = 1 `
  78. // //historyCond += ` AND new_company = 1 `
  79. // } else if req.CompanyType == 2 {
  80. // cond += ` AND b.contract_type IN (2,3,4) `
  81. // //historyCond += ` AND new_company = 0 `
  82. // }
  83. //
  84. // page := new(base.Page)
  85. // page.SetPageSize(req.PageSize)
  86. // page.SetCurrent(req.Current)
  87. // // 排序, 默认开票金额倒序
  88. // sortFieldMap := map[int]string{0: "invoice_amount", 1: "invoice_amount", 2: "group_rate"}
  89. // sortTypeMap := map[int]bool{0: false, 1: true, 2: false}
  90. // page.AddOrderItem(base.OrderItem{Column: sortFieldMap[req.SortField], Asc: sortTypeMap[req.SortType]})
  91. // if req.IsExport == 1 {
  92. // page.SetPageSize(10000)
  93. // page.SetCurrent(1)
  94. // }
  95. //
  96. // // 查询开票金额总和(减少子查询)
  97. // invOB := new(fms.ContractInvoice)
  98. // sumCond := cond
  99. // sumPars := make([]interface{}, 0)
  100. // invSum, e := invOB.Sum("amount", sumCond, sumPars)
  101. // if e != nil {
  102. // resp.FailMsg("获取失败", "获取开票金额总和失败, Err: "+e.Error(), c)
  103. // return
  104. // }
  105. //
  106. // // 查询列表
  107. // groupOB := new(crm.SysGroup)
  108. // //totalCond := outCond
  109. // //totalPars := make([]interface{}, 0)
  110. // //total, e := groupOB.Count(totalCond, totalPars)
  111. // //if e != nil {
  112. // // resp.FailMsg("获取失败", "获取销售组开票统计列表总数失败, Err: "+e.Error(), c)
  113. // // return
  114. // //}
  115. // //list, e := fms.GetCensusSellerGroupInvoicePageList(page, cond, outCond, pars, invSum)
  116. // //if e != nil {
  117. // // resp.FailMsg("获取失败", "获取销售组开票统计列表失败, Err: "+e.Error(), c)
  118. // // return
  119. // //}
  120. // groupCond := ` department_id = %d AND parent_id = 0 `
  121. // groupCond = fmt.Sprintf(groupCond, departmentId)
  122. // groupPars := make([]interface{}, 0)
  123. // groupList, e := groupOB.List(groupCond, groupPars)
  124. // if e != nil {
  125. // resp.FailMsg("获取失败", "获取组别列表失败, Err: "+e.Error(), c)
  126. // return
  127. // }
  128. // //total := len(groupList)
  129. // groupMap := make(map[int]*crm.SysGroup)
  130. // groupIdSlice := make([]string, 0)
  131. // for i := range groupList {
  132. // groupMap[groupList[i].GroupId] = groupList[i]
  133. // groupIdSlice = append(groupIdSlice, strconv.Itoa(groupList[i].GroupId))
  134. // }
  135. //
  136. // groupStr := strings.Join(groupIdSlice, ",")
  137. // total, list, e := fms.GetCensusSellerGroupInvoicePageListV2(page, groupStr, cond, pars, invSum)
  138. // if e != nil {
  139. // resp.FailMsg("获取失败", "获取销售组开票统计列表失败, Err: "+e.Error(), c)
  140. // return
  141. // }
  142. // for _, v := range list {
  143. // if group, ok := groupMap[v.GroupId]; ok {
  144. // v.GroupName = group.GroupName
  145. // }
  146. // }
  147. // // 处理百分比, 乘100并保留两位小数
  148. // mulNum := decimal.NewFromFloat(100)
  149. // for i := range list {
  150. // d := decimal.NewFromFloat(list[i].GroupRate)
  151. // d = d.Mul(mulNum).Round(2)
  152. // a, _ := d.Float64()
  153. // list[i].GroupRate = a
  154. // }
  155. //
  156. // // 是否导出
  157. // if req.IsExport == 1 {
  158. // ExportGroupInvoiceList(c, list, req)
  159. // return
  160. // }
  161. // page.SetTotal(int64(total))
  162. // baseData := new(base.BaseData)
  163. // baseData.SetPage(page)
  164. // baseData.SetList(list)
  165. // resp.OkData("获取成功", baseData, c)
  166. //}
  167. // ExportGroupInvoiceList 导出销售组开票统计列表
  168. func ExportGroupInvoiceList(c *gin.Context, list []*fms.CensusSellerGroupInvoiceItem, req fms.CensusSellerGroupInvoiceListReq) {
  169. // 生成Excel文件
  170. xlsxFile := xlsx.NewFile()
  171. style := xlsx.NewStyle()
  172. alignment := xlsx.Alignment{
  173. Horizontal: "center",
  174. Vertical: "center",
  175. WrapText: true,
  176. }
  177. style.Alignment = alignment
  178. style.ApplyAlignment = true
  179. sheetName := "销售组开票统计"
  180. sheet, err := xlsxFile.AddSheet(sheetName)
  181. if err != nil {
  182. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  183. return
  184. }
  185. // 存在筛选则前两行显示时间信息
  186. if req.StartDate != "" && req.EndDate != "" {
  187. timeData := fmt.Sprintf("时间:%s至%s", req.StartDate, req.EndDate)
  188. rowA := sheet.AddRow()
  189. cellAA := rowA.AddCell()
  190. cellAA.SetString("销售统计表")
  191. cellAA.SetStyle(style)
  192. rowB := sheet.AddRow()
  193. rowB.AddCell().SetString(timeData)
  194. // 第三行空出
  195. sheet.AddRow()
  196. }
  197. // 数据表头
  198. rowTitle := []string{"排名", "销售组别", "收入金额(元)", "组别占比"}
  199. titleRow := sheet.AddRow()
  200. for i := range rowTitle {
  201. v := titleRow.AddCell()
  202. v.SetString(rowTitle[i])
  203. v.SetStyle(style)
  204. }
  205. // 填充数据
  206. for k, v := range list {
  207. dataRow := sheet.AddRow()
  208. dataRow.AddCell().SetString(fmt.Sprint(k + 1)) // 排名
  209. dataRow.AddCell().SetString(v.GroupName) // 销售组别
  210. dataRow.AddCell().SetString(fmt.Sprintf("%.2f", v.InvoiceAmount)) // 开票金额
  211. dataRow.AddCell().SetString(fmt.Sprint(v.GroupRate, "%")) // 组别占比
  212. }
  213. // 输出文件
  214. var buffer bytes.Buffer
  215. _ = xlsxFile.Write(&buffer)
  216. content := bytes.NewReader(buffer.Bytes())
  217. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  218. fileName := sheetName + randStr + ".xlsx"
  219. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  220. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  221. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  222. }
  223. // InvoiceList
  224. // @Title 销售开票统计列表-弃用
  225. // @Description 销售开票统计列表-弃用
  226. // @Param GroupId query int false "组别ID"
  227. // @Param StartDate query string false "开始日期"
  228. // @Param EndDate query string false "结束日期"
  229. // @Param SortField query int false "排序字段: 1-开票金额; 2-组别占比; 3-全员占比"
  230. // @Param SortType query int false "排序方式: 1-正序; 2-倒序"
  231. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  232. // @Success 200 {object} fms.CensusSellerInvoiceListReq
  233. // @router /census/seller/invoice_list [get]
  234. //func (ct *SellerController) InvoiceList(c *gin.Context) {
  235. // var req fms.CensusSellerInvoiceListReq
  236. // if e := c.BindQuery(&req); e != nil {
  237. // err, ok := e.(validator.ValidationErrors)
  238. // if !ok {
  239. // resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  240. // return
  241. // }
  242. // resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  243. // return
  244. // }
  245. // var departmentId int
  246. // if req.SellerType == 1 {
  247. // departmentId = crm.SellerDepartmentId
  248. // } else if req.SellerType == 2 {
  249. // departmentId = crm.RaiSellerDepartmentId
  250. // } else if req.SellerType == 0 {
  251. // resp.Fail("请选择销售类型", c)
  252. // return
  253. // } else {
  254. // resp.Fail("请选择正确的销售类型", c)
  255. // return
  256. // }
  257. //
  258. // pars := make([]interface{}, 0)
  259. // adminPars := make([]interface{}, 0)
  260. // outCond := ` a.department_id = %d `
  261. // outCond = fmt.Sprintf(outCond, departmentId)
  262. // adminCond := ` department_id = %d `
  263. // adminCond = fmt.Sprintf(adminCond, departmentId)
  264. // totalCond := ` department_id = %d `
  265. // totalCond = fmt.Sprintf(totalCond, departmentId)
  266. // totalPars := make([]interface{}, 0)
  267. //
  268. // if !req.ShowResign {
  269. // adminCond += ` AND enabled = 1 `
  270. // }
  271. // if req.GroupId > 0 {
  272. // // 筛选组别时, 查询当前组别的下级组(因为admin表存的group_id, 有三级的存的是子ID, 只有二级的存的才是父ID =_=!)
  273. // groupCond := `parent_id = ?`
  274. // groupPars := make([]interface{}, 0)
  275. // groupPars = append(groupPars, req.GroupId)
  276. // groupOB := new(crm.SysGroup)
  277. // groupList, e := groupOB.List(groupCond, groupPars)
  278. // if e != nil {
  279. // resp.FailMsg("获取失败", "获取组别下级组列表失败, Err: "+e.Error(), c)
  280. // return
  281. // }
  282. // groupIds := make([]int, 0)
  283. // groupIds = append(groupIds, req.GroupId)
  284. // for i := range groupList {
  285. // groupIds = append(groupIds, groupList[i].GroupId)
  286. // }
  287. // outCond += ` AND a.group_id IN (?) `
  288. // pars = append(pars, groupIds)
  289. // adminCond += ` AND group_id IN (?) `
  290. // adminPars = append(adminPars, groupIds)
  291. // totalCond += ` AND group_id IN (?) `
  292. // totalPars = append(totalPars, groupIds)
  293. // }
  294. //
  295. // sumCond := ` (invoice_type = ? OR invoice_type = ? ) AND a.is_deleted = 0 AND a.seller_id != 0 `
  296. // sumPars := make([]interface{}, 0)
  297. // sumPars = append(sumPars, fms.ContractInvoiceTypeMake, fms.ContractInvoiceTypePreMake)
  298. // cond := ` (c.invoice_type = %d OR c.invoice_type = %d) AND c.is_deleted = 0 AND c.seller_id != 0 `
  299. // inCond := ` (invoice_type = %d OR invoice_type = %d) AND is_deleted = 0 AND seller_id != 0 `
  300. // cond = fmt.Sprintf(cond, fms.ContractInvoiceTypeMake, fms.ContractInvoiceTypePreMake)
  301. // inCond = fmt.Sprintf(inCond, fms.ContractInvoiceTypeMake, fms.ContractInvoiceTypePreMake)
  302. //
  303. // if req.CompanyType == 1 {
  304. // cond += ` AND b.contract_type = 1 `
  305. // //historyCond += ` AND new_company = 1 `
  306. // } else if req.CompanyType == 2 {
  307. // cond += ` AND b.contract_type IN (2,3,4) `
  308. // //historyCond += ` AND new_company = 0 `
  309. // }
  310. //
  311. // // 开票日期
  312. // if 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 (c.invoice_time BETWEEN '%s' AND '%s')`
  316. // inCond += ` AND (invoice_time BETWEEN '%s' AND '%s')`
  317. // cond = fmt.Sprintf(cond, st, ed)
  318. // inCond = fmt.Sprintf(inCond, st, ed)
  319. // sumCond += ` AND (invoice_time BETWEEN ? AND ?)`
  320. // sumPars = append(sumPars, st, ed)
  321. // }
  322. //
  323. // page := new(base.Page)
  324. // page.SetPageSize(req.PageSize)
  325. // page.SetCurrent(req.Current)
  326. // // 排序, 默认开票金额倒序
  327. // sortFieldMap := map[int]string{0: "invoice_amount", 1: "invoice_amount", 2: "group_rate", 3: "seller_rate"}
  328. // sortTypeMap := map[int]bool{0: false, 1: true, 2: false}
  329. // page.AddOrderItem(base.OrderItem{Column: sortFieldMap[req.SortField], Asc: sortTypeMap[req.SortType]})
  330. // if req.IsExport == 1 {
  331. // page.SetPageSize(10000)
  332. // page.SetCurrent(1)
  333. // }
  334. //
  335. // // 查询开票金额总和(减少子查询)
  336. // invOB := new(fms.ContractInvoice)
  337. // invSum, e := invOB.Sum("amount", sumCond, sumPars)
  338. // if e != nil {
  339. // resp.FailMsg("获取失败", "获取开票金额总和失败, Err: "+e.Error(), c)
  340. // return
  341. // }
  342. //
  343. // // 查询列表
  344. // adminOB := new(crm.Admin)
  345. // //total, e := adminOB.Count(totalCond, totalPars)
  346. // //if e != nil {
  347. // // resp.FailMsg("获取失败", "获取销售开票统计列表总数失败, Err: "+e.Error(), c)
  348. // // return
  349. // //}
  350. // //list, e := fms.GetCensusSellerInvoicePageList(page, cond, outCond, pars, invSum)
  351. // //if e != nil {
  352. // // resp.FailMsg("获取失败", "获取销售开票统计列表失败, Err: "+e.Error(), c)
  353. // // return
  354. // //}
  355. //
  356. // adminList, e := adminOB.List(adminCond, adminPars)
  357. // if e != nil {
  358. // resp.FailMsg("获取失败", "获取销售列表失败, Err: "+e.Error(), c)
  359. // return
  360. // }
  361. // //total := len(adminList)
  362. // adminIdSlice := make([]string, 0)
  363. // sellerMap := make(map[int]*crm.Admin)
  364. // for i := range adminList {
  365. // sellerMap[adminList[i].AdminId] = adminList[i]
  366. // adminIdSlice = append(adminIdSlice, strconv.Itoa(adminList[i].AdminId))
  367. // }
  368. //
  369. // adminStr := strings.Join(adminIdSlice, ",")
  370. //
  371. // total, list, e := fms.GetCensusSellerInvoicePageListV2(page, adminStr, inCond, cond, pars, invSum)
  372. // if e != nil {
  373. // resp.FailMsg("获取失败", "获取销售开票统计列表失败, Err: "+e.Error(), c)
  374. // return
  375. // }
  376. //
  377. // for _, v := range list {
  378. // if admin, ok := sellerMap[v.SellerId]; ok {
  379. // v.GroupName = admin.GroupName
  380. // v.SellerName = admin.RealName
  381. // v.GroupId = admin.GroupId
  382. // }
  383. // }
  384. // // 分组信息, list的groupId可能是三级的ID, 要转为对应的二级
  385. // groupMap, e := crmService.GetSellerTeamGroupMap()
  386. // if e != nil {
  387. // resp.FailMsg("获取失败", "获取组别对应信息失败, Err: "+e.Error(), c)
  388. // return
  389. // }
  390. //
  391. // mulNum := decimal.NewFromFloat(100)
  392. // for i := range list {
  393. // g := groupMap[list[i].GroupId]
  394. // if g != nil {
  395. // list[i].GroupId = g.GroupId
  396. // list[i].GroupName = g.GroupName
  397. // }
  398. // // 处理百分比, 乘100并保留两位小数
  399. // d := decimal.NewFromFloat(list[i].GroupRate)
  400. // d = d.Mul(mulNum).Round(2)
  401. // a, _ := d.Float64()
  402. // list[i].GroupRate = a
  403. // d2 := decimal.NewFromFloat(list[i].SellerRate)
  404. // d2 = d2.Mul(mulNum).Round(2)
  405. // a2, _ := d2.Float64()
  406. // list[i].SellerRate = a2
  407. // }
  408. //
  409. // // 是否导出
  410. // if req.IsExport == 1 {
  411. // ExportInvoiceList(c, list, req)
  412. // return
  413. // }
  414. // page.SetTotal(int64(total))
  415. // baseData := new(base.BaseData)
  416. // baseData.SetPage(page)
  417. // baseData.SetList(list)
  418. // resp.OkData("获取成功", baseData, c)
  419. //}
  420. func (this *SellerController) InvoiceListV2(c *gin.Context) {
  421. var req fms.CensusSellerInvoiceListReq
  422. if e := c.BindQuery(&req); e != nil {
  423. err, ok := e.(validator.ValidationErrors)
  424. if !ok {
  425. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  426. return
  427. }
  428. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  429. return
  430. }
  431. page := new(base.Page)
  432. page.SetPageSize(req.PageSize)
  433. page.SetCurrent(req.Current)
  434. if req.IsExport == 1 {
  435. page.SetPageSize(10000)
  436. page.SetCurrent(1)
  437. }
  438. //var departmentId int
  439. //if req.SellerType == 1 {
  440. // departmentId = crm.SellerDepartmentId
  441. //} else if req.SellerType == 2 {
  442. // departmentId = crm.RaiSellerDepartmentId
  443. //} else if req.SellerType == 0 {
  444. // resp.Fail("请选择销售类型", c)
  445. // return
  446. //} else {
  447. // resp.Fail("请选择正确的销售类型", c)
  448. // return
  449. //}
  450. var totalMoneySlice []float64
  451. historyTime, _ := time.Parse(utils.FormatDate, "2023-04-01")
  452. // 累计值
  453. var accumulate float64
  454. var startDate, endDate string
  455. //开始日期
  456. if req.StartDate != "" && req.EndDate != "" {
  457. startDate = fmt.Sprint(req.StartDate, " 00:00:00")
  458. endDate = fmt.Sprint(req.EndDate, " 23:59:59")
  459. }
  460. startDateTime, _ := time.Parse(utils.FormatDateTime, startDate)
  461. endDateTime, _ := time.Parse(utils.FormatDateTime, endDate)
  462. cond := ` 1 = 1 `
  463. historyCond := ` 1=1 `
  464. pars := make([]interface{}, 0)
  465. historyPars := make([]interface{}, 0)
  466. if req.CompanyType == 1 {
  467. cond += ` AND b.contract_type = 1 `
  468. historyCond += ` AND new_company = 1 `
  469. } else if req.CompanyType == 2 {
  470. cond += ` AND b.contract_type IN (2,3,4) `
  471. historyCond += ` AND new_company = 0 `
  472. }
  473. if req.SellerIds != "" {
  474. sellerIds := strings.Split(req.SellerIds, ",")
  475. //cond += ` AND (a.seller_id in ? ) `
  476. historyCond += ` AND (seller_id in ? ) `
  477. //pars = append(pars, sellerIds)
  478. historyPars = append(historyPars, sellerIds)
  479. }
  480. //groupIds := make([]int, 0)
  481. //if req.GroupId > 0 {
  482. // // 筛选组别时, 查询当前组别的下级组(因为admin表存的group_id, 有三级的存的是子ID, 只有二级的存的才是父ID =_=!)
  483. // groupCond := `parent_id = ?`
  484. // groupPars := make([]interface{}, 0)
  485. // groupPars = append(groupPars, req.GroupId)
  486. // groupOB := new(crm.SysGroup)
  487. // groupList, e := groupOB.List(groupCond, groupPars)
  488. // if e != nil {
  489. // resp.FailMsg("获取失败", "获取组别下级组列表失败, Err: "+e.Error(), c)
  490. // return
  491. // }
  492. // groupIds = append(groupIds, req.GroupId)
  493. // for i := range groupList {
  494. // groupIds = append(groupIds, groupList[i].GroupId)
  495. // }
  496. // cond += ` AND (c.seller_group_id IN (?) OR d.seller_group_id IN (?))`
  497. // pars = append(pars, groupIds, groupIds)
  498. // historyCond += ` AND group_id IN (?) `
  499. // historyPars = append(historyPars, groupIds)
  500. //}
  501. if req.CompanyType == 1 {
  502. cond += ` AND b.contract_type = 1 `
  503. historyCond += ` AND new_company = 1 `
  504. } else if req.CompanyType == 2 {
  505. cond += ` AND b.contract_type IN (2,3,4) `
  506. historyCond += ` AND new_company = 0 `
  507. }
  508. //if req.SellerIds != "" {
  509. // sellerIds := strings.Split(req.SellerIds, ",")
  510. // cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  511. // pars = append(pars, sellerIds, sellerIds)
  512. // prevCond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  513. // prevPars = append(prevPars, sellerIds, sellerIds)
  514. // histrtyCond += ` AND seller_id in ? `
  515. // prevHistoryCond += ` AND seller_id in ? `
  516. // historyPars = append(historyPars, sellerIds)
  517. // prevHistoryPars = append(prevHistoryPars, sellerIds)
  518. //}
  519. st := startDate
  520. ed := endDate
  521. groupInvoiceMap := make(map[int]float64)
  522. sellerInvoiceMap := make(map[int]float64)
  523. sellerGroupMap := make(map[int]int)
  524. //校验日期,分段查询
  525. if req.StartDate == "" && req.EndDate == "" {
  526. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  527. if e != nil {
  528. return
  529. }
  530. // 开票到款金额合计(换算后)
  531. var amountTotal float64
  532. var amountSum float64
  533. if len(summaryIds) > 0 {
  534. amountCond := `a.id IN ? `
  535. amountPars := make([]interface{}, 0)
  536. amountPars = append(amountPars, summaryIds)
  537. //if len(groupIds) > 0 {
  538. // amountCond += ` AND IF ( a.invoice_id = 0, d.seller_group_id, b.seller_group_id ) IN (?) `
  539. // amountPars = append(amountPars, groupIds)
  540. //}
  541. if req.SellerIds != "" {
  542. sellerIds := strings.Split(req.SellerIds, ",")
  543. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  544. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  545. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  546. } else {
  547. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  548. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  549. amountPars = append(amountPars, st, ed, st, ed)
  550. }
  551. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  552. if e != nil {
  553. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  554. return
  555. }
  556. //dataList = append(dataList, results...)
  557. for _, result := range results {
  558. amountSum += result.Amount
  559. fmt.Println("result.Amount:", result.Amount)
  560. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  561. groupInvoiceMap[result.SellerGroupId] += result.Amount
  562. } else {
  563. groupInvoiceMap[result.SellerGroupId] = result.Amount
  564. }
  565. if _, ok := sellerInvoiceMap[result.FinalSellerId]; ok {
  566. sellerInvoiceMap[result.FinalSellerId] += result.Amount
  567. } else {
  568. sellerInvoiceMap[result.FinalSellerId] = result.Amount
  569. }
  570. if _, ok := sellerGroupMap[result.FinalSellerId]; !ok {
  571. sellerGroupMap[result.FinalSellerId] = result.SellerGroupId
  572. }
  573. }
  574. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  575. accumulate += amountTotal
  576. amountSum = 0
  577. }
  578. results, e := fms.GetIncomeHistory(historyCond, historyPars)
  579. if e != nil {
  580. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  581. return
  582. }
  583. for _, result := range results {
  584. amountSum += result.Amount
  585. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  586. groupInvoiceMap[result.SellerGroupId] += result.Amount
  587. } else {
  588. groupInvoiceMap[result.SellerGroupId] = result.Amount
  589. }
  590. if _, ok := sellerInvoiceMap[result.FinalSellerId]; ok {
  591. sellerInvoiceMap[result.FinalSellerId] += result.Amount
  592. } else {
  593. sellerInvoiceMap[result.FinalSellerId] = result.Amount
  594. }
  595. if _, ok := sellerGroupMap[result.FinalSellerId]; !ok {
  596. sellerGroupMap[result.FinalSellerId] = result.SellerGroupId
  597. }
  598. }
  599. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  600. accumulate += amountTotal
  601. } else if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
  602. //全部走新查询
  603. //fmt.Println("新查询")
  604. if st != "" && ed != "" {
  605. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  606. pars = append(pars, st, ed, st, ed)
  607. }
  608. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  609. if e != nil {
  610. return
  611. }
  612. // 开票到款金额合计(换算后)
  613. var amountTotal float64
  614. if len(summaryIds) > 0 {
  615. amountCond := `a.id IN ? `
  616. amountPars := make([]interface{}, 0)
  617. amountPars = append(amountPars, summaryIds)
  618. //if len(groupIds) > 0 {
  619. // amountCond += ` AND IF ( a.invoice_id = 0, d.seller_group_id, b.seller_group_id ) IN (?) `
  620. // amountPars = append(amountPars, groupIds)
  621. //}
  622. if req.SellerIds != "" {
  623. sellerIds := strings.Split(req.SellerIds, ",")
  624. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  625. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  626. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  627. } else {
  628. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  629. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  630. amountPars = append(amountPars, st, ed, st, ed)
  631. }
  632. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  633. if e != nil {
  634. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  635. return
  636. }
  637. //dataList = append(dataList, results...)
  638. var amountSum float64
  639. for _, result := range results {
  640. amountSum += result.Amount
  641. fmt.Println("result.Amount:", result.Amount)
  642. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  643. groupInvoiceMap[result.SellerGroupId] += result.Amount
  644. } else {
  645. groupInvoiceMap[result.SellerGroupId] = result.Amount
  646. }
  647. if _, ok := sellerInvoiceMap[result.FinalSellerId]; ok {
  648. sellerInvoiceMap[result.FinalSellerId] += result.Amount
  649. } else {
  650. sellerInvoiceMap[result.FinalSellerId] = result.Amount
  651. }
  652. if _, ok := sellerGroupMap[result.FinalSellerId]; !ok {
  653. sellerGroupMap[result.FinalSellerId] = result.SellerGroupId
  654. }
  655. }
  656. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  657. accumulate += amountTotal
  658. }
  659. } else if endDateTime.Before(historyTime) || endDateTime.Equal(historyTime) {
  660. //全部走旧查询
  661. //fmt.Println("旧查询")
  662. //fmt.Println("st:",st)
  663. //fmt.Println("ed:",ed)
  664. if st != "" && ed != "" {
  665. historyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  666. historyPars = append(historyPars, st, ed)
  667. }
  668. //fmt.Println("st:",st)
  669. //fmt.Println("ed:",ed)
  670. // 开票到款金额合计(换算后)
  671. var amountTotal float64
  672. results, e := fms.GetIncomeHistory(historyCond, historyPars)
  673. if e != nil {
  674. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  675. return
  676. }
  677. var amountSum float64
  678. //dataList = append(dataList, results...)
  679. for _, result := range results {
  680. amountSum += result.Amount
  681. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  682. groupInvoiceMap[result.SellerGroupId] += result.Amount
  683. } else {
  684. groupInvoiceMap[result.SellerGroupId] = result.Amount
  685. }
  686. if _, ok := sellerInvoiceMap[result.FinalSellerId]; ok {
  687. sellerInvoiceMap[result.FinalSellerId] += result.Amount
  688. } else {
  689. sellerInvoiceMap[result.FinalSellerId] = result.Amount
  690. }
  691. if _, ok := sellerGroupMap[result.FinalSellerId]; !ok {
  692. sellerGroupMap[result.FinalSellerId] = result.SellerGroupId
  693. }
  694. }
  695. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  696. accumulate += amountTotal
  697. //fmt.Println("partAccumulate:",partAccumulate)
  698. } else {
  699. if st != "" && ed != "" {
  700. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  701. pars = append(pars, st, ed, st, ed)
  702. }
  703. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  704. if e != nil {
  705. return
  706. }
  707. // 开票到款金额合计(换算后)
  708. var amountTotal float64
  709. var amountSum float64
  710. if len(summaryIds) > 0 {
  711. amountCond := `a.id IN ? `
  712. amountPars := make([]interface{}, 0)
  713. amountPars = append(amountPars, summaryIds)
  714. //if len(groupIds) > 0 {
  715. // amountCond += ` AND IF ( a.invoice_id = 0, d.seller_group_id, b.seller_group_id ) IN (?) `
  716. // amountPars = append(amountPars, groupIds)
  717. //}
  718. if req.SellerIds != "" {
  719. sellerIds := strings.Split(req.SellerIds, ",")
  720. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  721. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  722. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  723. } else {
  724. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  725. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  726. amountPars = append(amountPars, st, ed, st, ed)
  727. }
  728. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  729. if e != nil {
  730. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  731. return
  732. }
  733. //dataList = append(dataList, results...)
  734. for _, result := range results {
  735. amountSum += result.Amount
  736. fmt.Println("result.Amount:", result.Amount)
  737. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  738. groupInvoiceMap[result.SellerGroupId] += result.Amount
  739. } else {
  740. groupInvoiceMap[result.SellerGroupId] = result.Amount
  741. }
  742. if _, ok := sellerInvoiceMap[result.FinalSellerId]; ok {
  743. sellerInvoiceMap[result.FinalSellerId] += result.Amount
  744. } else {
  745. sellerInvoiceMap[result.FinalSellerId] = result.Amount
  746. }
  747. if _, ok := sellerGroupMap[result.FinalSellerId]; !ok {
  748. sellerGroupMap[result.FinalSellerId] = result.SellerGroupId
  749. }
  750. }
  751. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  752. accumulate += amountTotal
  753. amountSum = 0
  754. }
  755. if st != "" && ed != "" {
  756. historyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  757. historyPars = append(historyPars, st, ed)
  758. }
  759. results, e := fms.GetIncomeHistory(historyCond, historyPars)
  760. if e != nil {
  761. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  762. return
  763. }
  764. for _, result := range results {
  765. amountSum += result.Amount
  766. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  767. groupInvoiceMap[result.SellerGroupId] += result.Amount
  768. } else {
  769. groupInvoiceMap[result.SellerGroupId] = result.Amount
  770. }
  771. if _, ok := sellerInvoiceMap[result.FinalSellerId]; ok {
  772. sellerInvoiceMap[result.FinalSellerId] += result.Amount
  773. } else {
  774. sellerInvoiceMap[result.FinalSellerId] = result.Amount
  775. }
  776. if _, ok := sellerGroupMap[result.FinalSellerId]; !ok {
  777. sellerGroupMap[result.FinalSellerId] = result.SellerGroupId
  778. }
  779. }
  780. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  781. accumulate += amountTotal
  782. }
  783. fmt.Println("totalMoneySlice:", len(totalMoneySlice))
  784. //if req.SellerType == 1 {
  785. // departmentId = crm.SellerDepartmentId
  786. //} else if req.SellerType == 2 {
  787. // departmentId = crm.RaiSellerDepartmentId
  788. //} else if req.SellerType == 0 {
  789. // resp.FailMsg("查询错误", "请选择正确的销售类型", c)
  790. // return
  791. //} else {
  792. // resp.FailMsg("查询错误", "请选择正确的销售类型", c)
  793. // return
  794. //}
  795. adminOB := new(crm.Admin)
  796. adminPars := make([]interface{}, 0)
  797. adminCond := ` 1=1 `
  798. //adminCond = fmt.Sprintf(adminCond, departmentId)
  799. if !req.ShowResign {
  800. adminCond += ` AND enabled = 1 `
  801. }
  802. adminList, e := adminOB.List(adminCond, adminPars)
  803. if e != nil {
  804. resp.FailMsg("获取失败", "获取销售列表失败, Err: "+e.Error(), c)
  805. return
  806. }
  807. // 获取销售分组信息
  808. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  809. if e != nil {
  810. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  811. return
  812. }
  813. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  814. for i := range sellerList {
  815. sellerMap[sellerList[i].SellerId] = sellerList[i]
  816. }
  817. list := make([]*fms.CensusSellerInvoiceItem, 0)
  818. for _, v := range adminList {
  819. if vv, ok := sellerInvoiceMap[v.AdminId]; ok {
  820. rate := vv / accumulate
  821. mulNum := decimal.NewFromFloat(100)
  822. newRate := decimal.NewFromFloat(rate)
  823. newRate = newRate.Mul(mulNum).Round(2)
  824. finalRate, _ := newRate.Float64()
  825. groupId := sellerGroupMap[v.AdminId]
  826. groupRate := vv / groupInvoiceMap[groupId]
  827. newGroupRate := decimal.NewFromFloat(groupRate)
  828. newGroupRate = newGroupRate.Mul(mulNum).Round(2)
  829. finalGroupRate, _ := newGroupRate.Float64()
  830. amuont, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", vv), 64)
  831. var sellerName, groupName string
  832. if seller, ok := sellerMap[v.AdminId]; ok {
  833. sellerName = seller.SellerName
  834. groupName = seller.GroupName
  835. }
  836. list = append(list, &fms.CensusSellerInvoiceItem{
  837. SellerId: v.AdminId,
  838. SellerName: sellerName,
  839. GroupId: groupId,
  840. GroupName: groupName,
  841. InvoiceAmount: amuont,
  842. GroupRate: finalGroupRate,
  843. SellerRate: finalRate,
  844. })
  845. }
  846. }
  847. sort.Slice(list, func(i, j int) bool {
  848. if req.SortField == 2 {
  849. if req.SortType == 2 {
  850. return list[i].GroupRate < list[j].GroupRate
  851. } else {
  852. return list[i].GroupRate > list[j].GroupRate
  853. }
  854. } else {
  855. if req.SortType == 2 {
  856. return list[i].InvoiceAmount < list[j].InvoiceAmount
  857. } else {
  858. return list[i].InvoiceAmount > list[j].InvoiceAmount
  859. }
  860. }
  861. })
  862. //var respList fmsService.CensusSellerListByAmountAsc
  863. //respList = list
  864. //sort.Sort(list)
  865. // 是否导出
  866. if req.IsExport == 1 {
  867. ExportInvoiceList(c, list, req)
  868. return
  869. }
  870. page.SetTotal(int64(len(list)))
  871. baseData := new(base.BaseData)
  872. baseData.SetPage(page)
  873. if req.Current*req.PageSize > int64(len(list)) {
  874. baseData.SetList(list[(req.Current-1)*req.PageSize : len(list)])
  875. } else {
  876. baseData.SetList(list[(req.Current-1)*req.PageSize : req.Current*req.PageSize])
  877. }
  878. resp.OkData("获取成功", baseData, c)
  879. }
  880. // ExportInvoiceList 导出销售开票统计列表
  881. func ExportInvoiceList(c *gin.Context, list []*fms.CensusSellerInvoiceItem, req fms.CensusSellerInvoiceListReq) {
  882. // 生成Excel文件
  883. xlsxFile := xlsx.NewFile()
  884. style := xlsx.NewStyle()
  885. alignment := xlsx.Alignment{
  886. Horizontal: "center",
  887. Vertical: "center",
  888. WrapText: true,
  889. }
  890. style.Alignment = alignment
  891. style.ApplyAlignment = true
  892. sheetName := "销售开票统计"
  893. sheet, err := xlsxFile.AddSheet(sheetName)
  894. if err != nil {
  895. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  896. return
  897. }
  898. // 存在筛选则前两行显示时间信息
  899. if req.StartDate != "" && req.EndDate != "" {
  900. timeData := fmt.Sprintf("时间:%s至%s", req.StartDate, req.EndDate)
  901. rowA := sheet.AddRow()
  902. cellAA := rowA.AddCell()
  903. cellAA.SetString("销售统计表")
  904. cellAA.SetStyle(style)
  905. rowB := sheet.AddRow()
  906. rowB.AddCell().SetString(timeData)
  907. // 第三行空出
  908. sheet.AddRow()
  909. }
  910. // 数据表头
  911. rowTitle := []string{"排名", "销售员", "销售组别", "收入金额(元)", "小组占比", "全员占比"}
  912. titleRow := sheet.AddRow()
  913. for i := range rowTitle {
  914. v := titleRow.AddCell()
  915. v.SetString(rowTitle[i])
  916. v.SetStyle(style)
  917. }
  918. // 填充数据
  919. for k, v := range list {
  920. dataRow := sheet.AddRow()
  921. dataRow.AddCell().SetString(fmt.Sprint(k + 1)) // 排名
  922. dataRow.AddCell().SetString(v.SellerName) // 销售员
  923. dataRow.AddCell().SetString(v.GroupName) // 销售组别
  924. dataRow.AddCell().SetString(fmt.Sprintf("%.2f", v.InvoiceAmount)) // 开票金额
  925. dataRow.AddCell().SetString(fmt.Sprint(v.GroupRate, "%")) // 小组占比
  926. dataRow.AddCell().SetString(fmt.Sprint(v.SellerRate, "%")) // 全员占比
  927. }
  928. // 输出文件
  929. var buffer bytes.Buffer
  930. _ = xlsxFile.Write(&buffer)
  931. content := bytes.NewReader(buffer.Bytes())
  932. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  933. fileName := sheetName + randStr + ".xlsx"
  934. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  935. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  936. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  937. }
  938. // GroupInvoiceList
  939. // @Title 销售组开票统计列表
  940. // @Description 销售组开票统计列表
  941. // @Param StartDate query string false "开始日期"
  942. // @Param EndDate query string false "结束日期"
  943. // @Param SortField query int false "排序字段: 1-开票金额; 2-组别占比"
  944. // @Param SortType query int false "排序方式: 1-正序; 2-倒序"
  945. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  946. // @Success 200 {object} fms.CensusSellerGroupInvoiceItem
  947. // @router /census/seller/group_invoice_list [get]
  948. func (this *SellerController) GroupInvoiceListV2(c *gin.Context) {
  949. var req fms.CensusSellerGroupInvoiceListReq
  950. if e := c.BindQuery(&req); e != nil {
  951. err, ok := e.(validator.ValidationErrors)
  952. if !ok {
  953. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  954. return
  955. }
  956. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  957. return
  958. }
  959. //if req.SellerIds != "" {
  960. // sellerIds := strings.Split(req.SellerIds, ",")
  961. // cond += ` AND (a.seller_id in ? ) `
  962. // historyCond += ` AND (seller_id in ? ) `
  963. // pars = append(pars, sellerIds)
  964. // historyPars = append(historyPars, sellerIds)
  965. //}
  966. var totalMoneySlice []float64
  967. historyTime, _ := time.Parse(utils.FormatDate, "2023-04-01")
  968. // 累计值
  969. var accumulate float64
  970. //dataList := make([]*fms.IncomeSummaryItem, 0)
  971. //historydataList := make([]*fms.IncomeSummaryItem, 0)
  972. //timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
  973. var startDate, endDate string
  974. //开始日期
  975. if req.StartDate != "" && req.EndDate != "" {
  976. startDate = fmt.Sprint(req.StartDate, " 00:00:00")
  977. endDate = fmt.Sprint(req.EndDate, " 23:59:59")
  978. }
  979. startDateTime, _ := time.Parse(utils.FormatDate, req.StartDate)
  980. endDateTime, _ := time.Parse(utils.FormatDate, req.EndDate)
  981. cond := `1 = 1`
  982. histortyCond := `1 = 1`
  983. pars := make([]interface{}, 0)
  984. historyPars := make([]interface{}, 0)
  985. if req.CompanyType == 1 {
  986. cond += ` AND b.contract_type = 1 `
  987. histortyCond += ` AND new_company = 1 `
  988. } else if req.CompanyType == 2 {
  989. cond += ` AND b.contract_type IN (2,3,4) `
  990. histortyCond += ` AND new_company = 0 `
  991. }
  992. //if req.SellerIds != "" {
  993. // sellerIds := strings.Split(req.SellerIds, ",")
  994. // cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  995. // pars = append(pars, sellerIds, sellerIds)
  996. // prevCond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  997. // prevPars = append(prevPars, sellerIds, sellerIds)
  998. // histrtyCond += ` AND seller_id in ? `
  999. // prevHistoryCond += ` AND seller_id in ? `
  1000. // historyPars = append(historyPars, sellerIds)
  1001. // prevHistoryPars = append(prevHistoryPars, sellerIds)
  1002. //}
  1003. st := fmt.Sprint(startDate, " 00:00:00")
  1004. ed := fmt.Sprint(endDate, " 23:59:59")
  1005. groupInvoiceMap := make(map[int]float64)
  1006. //校验日期,分段查询
  1007. if req.StartDate == "" && req.EndDate == "" {
  1008. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1009. if e != nil {
  1010. return
  1011. }
  1012. // 开票到款金额合计(换算后)
  1013. var amountTotal float64
  1014. var amountSum float64
  1015. if len(summaryIds) > 0 {
  1016. amountCond := `a.id IN ? `
  1017. amountPars := make([]interface{}, 0)
  1018. amountPars = append(amountPars, summaryIds)
  1019. if req.SellerIds != "" {
  1020. sellerIds := strings.Split(req.SellerIds, ",")
  1021. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1022. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1023. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  1024. } else {
  1025. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1026. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1027. amountPars = append(amountPars, st, ed, st, ed)
  1028. }
  1029. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1030. if e != nil {
  1031. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1032. return
  1033. }
  1034. //dataList = append(dataList, results...)
  1035. for _, result := range results {
  1036. amountSum += result.Amount
  1037. fmt.Println("result.Amount:", result.Amount)
  1038. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1039. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1040. } else {
  1041. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1042. }
  1043. }
  1044. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1045. accumulate += amountTotal
  1046. amountSum = 0
  1047. }
  1048. //var amountTotal float64
  1049. results, e := fms.GetIncomeHistory(histortyCond, historyPars)
  1050. if e != nil {
  1051. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1052. return
  1053. }
  1054. //dataList = append(dataList, results...)
  1055. for _, result := range results {
  1056. amountSum += result.Amount
  1057. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1058. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1059. } else {
  1060. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1061. }
  1062. }
  1063. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1064. accumulate += amountTotal
  1065. } else if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
  1066. //全部走新查询
  1067. //fmt.Println("新查询")
  1068. if st != "" && ed != "" {
  1069. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1070. pars = append(pars, st, ed, st, ed)
  1071. }
  1072. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1073. if e != nil {
  1074. return
  1075. }
  1076. // 开票到款金额合计(换算后)
  1077. var amountTotal float64
  1078. if len(summaryIds) > 0 {
  1079. amountCond := `a.id IN ? `
  1080. amountPars := make([]interface{}, 0)
  1081. amountPars = append(amountPars, summaryIds)
  1082. if req.SellerIds != "" {
  1083. sellerIds := strings.Split(req.SellerIds, ",")
  1084. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1085. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1086. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  1087. } else {
  1088. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1089. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1090. amountPars = append(amountPars, st, ed, st, ed)
  1091. }
  1092. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1093. if e != nil {
  1094. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1095. return
  1096. }
  1097. //dataList = append(dataList, results...)
  1098. var amountSum float64
  1099. for _, result := range results {
  1100. amountSum += result.Amount
  1101. fmt.Println("result.Amount:", result.Amount)
  1102. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1103. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1104. } else {
  1105. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1106. }
  1107. }
  1108. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1109. accumulate += amountTotal
  1110. }
  1111. } else if endDateTime.Before(historyTime) || endDateTime.Equal(historyTime) {
  1112. //全部走旧查询
  1113. //fmt.Println("旧查询")
  1114. //fmt.Println("st:",st)
  1115. //fmt.Println("ed:",ed)
  1116. if st != "" && ed != "" {
  1117. histortyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1118. historyPars = append(historyPars, st, ed)
  1119. }
  1120. //fmt.Println("st:",st)
  1121. //fmt.Println("ed:",ed)
  1122. // 开票到款金额合计(换算后)
  1123. var amountTotal float64
  1124. results, e := fms.GetIncomeHistory(histortyCond, historyPars)
  1125. if e != nil {
  1126. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1127. return
  1128. }
  1129. var amountSum float64
  1130. //dataList = append(dataList, results...)
  1131. for _, result := range results {
  1132. amountSum += result.Amount
  1133. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1134. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1135. } else {
  1136. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1137. }
  1138. }
  1139. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1140. accumulate += amountTotal
  1141. //fmt.Println("partAccumulate:",partAccumulate)
  1142. } else {
  1143. // 有时间,分段查询
  1144. // 新查询
  1145. if st != "" && ed != "" {
  1146. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1147. pars = append(pars, st, ed, st, ed)
  1148. }
  1149. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1150. if e != nil {
  1151. return
  1152. }
  1153. // 开票到款金额合计(换算后)
  1154. var amountTotal float64
  1155. var amountSum float64
  1156. if len(summaryIds) > 0 {
  1157. amountCond := `a.id IN ? `
  1158. amountPars := make([]interface{}, 0)
  1159. amountPars = append(amountPars, summaryIds)
  1160. if req.SellerIds != "" {
  1161. sellerIds := strings.Split(req.SellerIds, ",")
  1162. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1163. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1164. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  1165. } else {
  1166. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1167. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1168. amountPars = append(amountPars, st, ed, st, ed)
  1169. }
  1170. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1171. if e != nil {
  1172. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1173. return
  1174. }
  1175. //dataList = append(dataList, results...)
  1176. for _, result := range results {
  1177. amountSum += result.Amount
  1178. fmt.Println("result.Amount:", result.Amount)
  1179. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1180. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1181. } else {
  1182. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1183. }
  1184. }
  1185. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1186. accumulate += amountTotal
  1187. amountSum = 0
  1188. //var amountTotal float64
  1189. // 旧查询
  1190. }
  1191. if st != "" && ed != "" {
  1192. histortyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1193. historyPars = append(historyPars, st, ed)
  1194. }
  1195. results, e := fms.GetIncomeHistory(histortyCond, historyPars)
  1196. if e != nil {
  1197. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1198. return
  1199. }
  1200. //dataList = append(dataList, results...)
  1201. for _, result := range results {
  1202. amountSum += result.Amount
  1203. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1204. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1205. } else {
  1206. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1207. }
  1208. }
  1209. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1210. accumulate += amountTotal
  1211. }
  1212. fmt.Println("totalMoneySlice:", len(totalMoneySlice))
  1213. var departmentId int
  1214. if req.SellerType == 1 {
  1215. departmentId = crm.SellerDepartmentId
  1216. } else if req.SellerType == 2 {
  1217. departmentId = crm.RaiSellerDepartmentId
  1218. } else if req.SellerType == 0 {
  1219. resp.FailMsg("查询错误", "请选择正确的销售类型", c)
  1220. return
  1221. } else {
  1222. resp.FailMsg("查询错误", "请选择正确的销售类型", c)
  1223. return
  1224. }
  1225. groupCond := ` department_id = %d AND parent_id = 0 `
  1226. groupCond = fmt.Sprintf(groupCond, departmentId)
  1227. groupPars := make([]interface{}, 0)
  1228. groupOB := new(crm.SysGroup)
  1229. groupList, e := groupOB.List(groupCond, groupPars)
  1230. if e != nil {
  1231. resp.FailMsg("查询错误", fmt.Sprintf("获取组别列表失败, Err: %s", e.Error()), c)
  1232. return
  1233. }
  1234. //total := len(groupList)
  1235. groupMap := make(map[int]*crm.SysGroup)
  1236. for i := range groupList {
  1237. groupMap[groupList[i].GroupId] = groupList[i]
  1238. }
  1239. list := make([]*fms.CensusSellerGroupInvoiceItem, 0)
  1240. for _, group := range groupList {
  1241. if v, ok := groupInvoiceMap[group.GroupId]; ok {
  1242. rate := v / accumulate
  1243. mulNum := decimal.NewFromFloat(100)
  1244. newRate := decimal.NewFromFloat(rate)
  1245. newRate = newRate.Mul(mulNum).Round(2)
  1246. finalRate, _ := newRate.Float64()
  1247. amuont, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", v), 64)
  1248. groupName := ""
  1249. if groupItem, ok := groupMap[group.GroupId]; ok {
  1250. groupName = groupItem.GroupName
  1251. }
  1252. list = append(list, &fms.CensusSellerGroupInvoiceItem{
  1253. GroupId: group.GroupId,
  1254. GroupName: groupName,
  1255. InvoiceAmount: amuont,
  1256. GroupRate: finalRate,
  1257. })
  1258. }
  1259. }
  1260. sort.Slice(list, func(i, j int) bool {
  1261. if req.SortField == 2 {
  1262. if req.SortType == 2 {
  1263. return list[i].GroupRate < list[j].GroupRate
  1264. } else {
  1265. return list[i].GroupRate > list[j].GroupRate
  1266. }
  1267. } else {
  1268. if req.SortType == 2 {
  1269. return list[i].InvoiceAmount < list[j].InvoiceAmount
  1270. } else {
  1271. return list[i].InvoiceAmount > list[j].InvoiceAmount
  1272. }
  1273. }
  1274. })
  1275. //var respList fms.CensusSellerGroupList
  1276. //respList = list
  1277. //sort.Sort(respList)
  1278. // 是否导出
  1279. if req.IsExport == 1 {
  1280. ExportGroupInvoiceList(c, list, req)
  1281. return
  1282. }
  1283. resp.OkData("获取成功", list, c)
  1284. }