seller.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. "time"
  18. )
  19. // SellerController 销售统计
  20. type SellerController struct{}
  21. // GroupInvoiceList
  22. // @Title 销售组开票统计列表
  23. // @Description 销售组开票统计列表
  24. // @Param StartDate query string false "开始日期"
  25. // @Param EndDate query string false "结束日期"
  26. // @Param SortField query int false "排序字段: 1-开票金额; 2-组别占比"
  27. // @Param SortType query int false "排序方式: 1-正序; 2-倒序"
  28. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  29. // @Success 200 {object} fms.CensusSellerGroupInvoiceItem
  30. // @router /census/seller/group_invoice_list [get]
  31. func (ct *SellerController) GroupInvoiceList(c *gin.Context) {
  32. var req fms.CensusSellerGroupInvoiceListReq
  33. if e := c.BindQuery(&req); e != nil {
  34. err, ok := e.(validator.ValidationErrors)
  35. if !ok {
  36. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  37. return
  38. }
  39. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  40. return
  41. }
  42. outCond := ` department_id = %d AND parent_id = 0 `
  43. outCond = fmt.Sprintf(outCond, crm.SellerDepartmentId)
  44. cond := ` invoice_type = %d AND is_deleted = 0 AND seller_group_id != 0 `
  45. cond = fmt.Sprintf(cond, fms.ContractInvoiceTypeMake)
  46. pars := make([]interface{}, 0)
  47. // 开票日期
  48. if req.StartDate != "" && req.EndDate != "" {
  49. st := fmt.Sprint(req.StartDate, " 00:00:00")
  50. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  51. cond += ` AND (invoice_time BETWEEN '%s' AND '%s')`
  52. cond = fmt.Sprintf(cond, st, ed)
  53. }
  54. page := new(base.Page)
  55. page.SetPageSize(req.PageSize)
  56. page.SetCurrent(req.Current)
  57. // 排序, 默认开票金额倒序
  58. sortFieldMap := map[int]string{0: "invoice_amount", 1: "invoice_amount", 2: "group_rate"}
  59. sortTypeMap := map[int]bool{0: false, 1: true, 2: false}
  60. page.AddOrderItem(base.OrderItem{Column: sortFieldMap[req.SortField], Asc: sortTypeMap[req.SortType]})
  61. if req.IsExport == 1 {
  62. page.SetPageSize(10000)
  63. page.SetCurrent(1)
  64. }
  65. // 查询开票金额总和(减少子查询)
  66. invOB := new(fms.ContractInvoice)
  67. sumCond := cond
  68. sumPars := make([]interface{}, 0)
  69. invSum, e := invOB.Sum("amount", sumCond, sumPars)
  70. if e != nil {
  71. resp.FailMsg("获取失败", "获取开票金额总和失败, Err: "+e.Error(), c)
  72. return
  73. }
  74. // 查询列表
  75. groupOB := new(crm.SysGroup)
  76. totalCond := outCond
  77. totalPars := make([]interface{}, 0)
  78. total, e := groupOB.Count(totalCond, totalPars)
  79. if e != nil {
  80. resp.FailMsg("获取失败", "获取销售组开票统计列表总数失败, Err: "+e.Error(), c)
  81. return
  82. }
  83. list, e := fms.GetCensusSellerGroupInvoicePageList(page, cond, outCond, pars, invSum)
  84. if e != nil {
  85. resp.FailMsg("获取失败", "获取销售组开票统计列表失败, Err: "+e.Error(), c)
  86. return
  87. }
  88. // 处理百分比, 乘100并保留两位小数
  89. mulNum := decimal.NewFromFloat(100)
  90. for i := range list {
  91. d := decimal.NewFromFloat(list[i].GroupRate)
  92. d = d.Mul(mulNum).Round(2)
  93. a, _ := d.Float64()
  94. list[i].GroupRate = a
  95. }
  96. // 是否导出
  97. if req.IsExport == 1 {
  98. ExportGroupInvoiceList(c, list, req)
  99. return
  100. }
  101. page.SetTotal(total)
  102. baseData := new(base.BaseData)
  103. baseData.SetPage(page)
  104. baseData.SetList(list)
  105. resp.OkData("获取成功", baseData, c)
  106. }
  107. // ExportGroupInvoiceList 导出销售组开票统计列表
  108. func ExportGroupInvoiceList(c *gin.Context, list []*fms.CensusSellerGroupInvoiceItem, req fms.CensusSellerGroupInvoiceListReq) {
  109. // 生成Excel文件
  110. xlsxFile := xlsx.NewFile()
  111. style := xlsx.NewStyle()
  112. alignment := xlsx.Alignment{
  113. Horizontal: "center",
  114. Vertical: "center",
  115. WrapText: true,
  116. }
  117. style.Alignment = alignment
  118. style.ApplyAlignment = true
  119. sheetName := "销售组开票统计"
  120. sheet, err := xlsxFile.AddSheet(sheetName)
  121. if err != nil {
  122. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  123. return
  124. }
  125. // 存在筛选则前两行显示时间信息
  126. if req.StartDate != "" && req.EndDate != "" {
  127. timeData := fmt.Sprintf("时间:%s至%s", req.StartDate, req.EndDate)
  128. rowA := sheet.AddRow()
  129. cellAA := rowA.AddCell()
  130. cellAA.SetString("销售统计表")
  131. cellAA.SetStyle(style)
  132. rowB := sheet.AddRow()
  133. rowB.AddCell().SetString(timeData)
  134. // 第三行空出
  135. sheet.AddRow()
  136. }
  137. // 数据表头
  138. rowTitle := []string{"排名", "销售组别", "收入金额(元)", "组别占比"}
  139. titleRow := sheet.AddRow()
  140. for i := range rowTitle {
  141. v := titleRow.AddCell()
  142. v.SetString(rowTitle[i])
  143. v.SetStyle(style)
  144. }
  145. // 填充数据
  146. for k, v := range list {
  147. dataRow := sheet.AddRow()
  148. dataRow.AddCell().SetString(fmt.Sprint(k + 1)) // 排名
  149. dataRow.AddCell().SetString(v.GroupName) // 销售组别
  150. dataRow.AddCell().SetString(fmt.Sprint(v.InvoiceAmount)) // 开票金额
  151. dataRow.AddCell().SetString(fmt.Sprint(v.GroupRate, "%")) // 组别占比
  152. }
  153. // 输出文件
  154. var buffer bytes.Buffer
  155. _ = xlsxFile.Write(&buffer)
  156. content := bytes.NewReader(buffer.Bytes())
  157. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  158. fileName := sheetName + randStr + ".xlsx"
  159. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  160. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  161. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  162. }
  163. // InvoiceList
  164. // @Title 销售开票统计列表
  165. // @Description 销售开票统计列表
  166. // @Param GroupId query int false "组别ID"
  167. // @Param StartDate query string false "开始日期"
  168. // @Param EndDate query string false "结束日期"
  169. // @Param SortField query int false "排序字段: 1-开票金额; 2-组别占比; 3-全员占比"
  170. // @Param SortType query int false "排序方式: 1-正序; 2-倒序"
  171. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  172. // @Success 200 {object} fms.CensusSellerInvoiceListReq
  173. // @router /census/seller/invoice_list [get]
  174. func (ct *SellerController) InvoiceList(c *gin.Context) {
  175. var req fms.CensusSellerInvoiceListReq
  176. if e := c.BindQuery(&req); e != nil {
  177. err, ok := e.(validator.ValidationErrors)
  178. if !ok {
  179. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  180. return
  181. }
  182. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  183. return
  184. }
  185. pars := make([]interface{}, 0)
  186. outCond := ` a.department_id = %d AND a.enabled = 1 `
  187. outCond = fmt.Sprintf(outCond, crm.SellerDepartmentId)
  188. totalCond := ` department_id = %d AND enabled = 1 `
  189. totalCond = fmt.Sprintf(totalCond, crm.SellerDepartmentId)
  190. totalPars := make([]interface{}, 0)
  191. if req.GroupId > 0 {
  192. // 筛选组别时, 查询当前组别的下级组(因为admin表存的group_id, 有三级的存的是子ID, 只有二级的存的才是父ID =_=!)
  193. groupCond := `parent_id = ?`
  194. groupPars := make([]interface{}, 0)
  195. groupPars = append(groupPars, req.GroupId)
  196. groupOB := new(crm.SysGroup)
  197. groupList, e := groupOB.List(groupCond, groupPars)
  198. if e != nil {
  199. resp.FailMsg("获取失败", "获取组别下级组列表失败, Err: "+e.Error(), c)
  200. return
  201. }
  202. groupIds := make([]int, 0)
  203. groupIds = append(groupIds, req.GroupId)
  204. for i := range groupList {
  205. groupIds = append(groupIds, groupList[i].GroupId)
  206. }
  207. outCond += ` AND a.group_id IN (?) `
  208. pars = append(pars, groupIds)
  209. totalCond += ` AND group_id IN (?) `
  210. totalPars = append(totalPars, groupIds)
  211. }
  212. sumCond := ` invoice_type = ? AND is_deleted = 0 AND seller_id != 0 `
  213. sumPars := make([]interface{}, 0)
  214. sumPars = append(sumPars, fms.ContractInvoiceTypeMake)
  215. cond := ` c.invoice_type = %d AND c.is_deleted = 0 AND c.seller_id != 0 `
  216. cond = fmt.Sprintf(cond, fms.ContractInvoiceTypeMake)
  217. // 开票日期
  218. if req.StartDate != "" && req.EndDate != "" {
  219. st := fmt.Sprint(req.StartDate, " 00:00:00")
  220. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  221. cond += ` AND (c.invoice_time BETWEEN '%s' AND '%s')`
  222. cond = fmt.Sprintf(cond, st, ed)
  223. sumCond += ` AND (invoice_time BETWEEN ? AND ?)`
  224. sumPars = append(sumPars, st, ed)
  225. }
  226. page := new(base.Page)
  227. page.SetPageSize(req.PageSize)
  228. page.SetCurrent(req.Current)
  229. // 排序, 默认开票金额倒序
  230. sortFieldMap := map[int]string{0: "invoice_amount", 1: "invoice_amount", 2: "group_rate", 3: "seller_rate"}
  231. sortTypeMap := map[int]bool{0: false, 1: true, 2: false}
  232. page.AddOrderItem(base.OrderItem{Column: sortFieldMap[req.SortField], Asc: sortTypeMap[req.SortType]})
  233. if req.IsExport == 1 {
  234. page.SetPageSize(10000)
  235. page.SetCurrent(1)
  236. }
  237. // 查询开票金额总和(减少子查询)
  238. invOB := new(fms.ContractInvoice)
  239. invSum, e := invOB.Sum("amount", sumCond, sumPars)
  240. if e != nil {
  241. resp.FailMsg("获取失败", "获取开票金额总和失败, Err: "+e.Error(), c)
  242. return
  243. }
  244. // 查询列表
  245. adminOB := new(crm.Admin)
  246. total, e := adminOB.Count(totalCond, totalPars)
  247. if e != nil {
  248. resp.FailMsg("获取失败", "获取销售开票统计列表总数失败, Err: "+e.Error(), c)
  249. return
  250. }
  251. list, e := fms.GetCensusSellerInvoicePageList(page, cond, outCond, pars, invSum)
  252. if e != nil {
  253. resp.FailMsg("获取失败", "获取销售开票统计列表失败, Err: "+e.Error(), c)
  254. return
  255. }
  256. // 分组信息, list的groupId可能是三级的ID, 要转为对应的二级
  257. groupMap, e := crmService.GetSellerTeamGroupMap()
  258. if e != nil {
  259. resp.FailMsg("获取失败", "获取组别对应信息失败, Err: "+e.Error(), c)
  260. return
  261. }
  262. mulNum := decimal.NewFromFloat(100)
  263. for i := range list {
  264. g := groupMap[list[i].GroupId]
  265. if g != nil {
  266. list[i].GroupId = g.GroupId
  267. list[i].GroupName = g.GroupName
  268. }
  269. // 处理百分比, 乘100并保留两位小数
  270. d := decimal.NewFromFloat(list[i].GroupRate)
  271. d = d.Mul(mulNum).Round(2)
  272. a, _ := d.Float64()
  273. list[i].GroupRate = a
  274. d2 := decimal.NewFromFloat(list[i].SellerRate)
  275. d2 = d2.Mul(mulNum).Round(2)
  276. a2, _ := d2.Float64()
  277. list[i].SellerRate = a2
  278. }
  279. // 是否导出
  280. if req.IsExport == 1 {
  281. ExportInvoiceList(c, list, req)
  282. return
  283. }
  284. page.SetTotal(total)
  285. baseData := new(base.BaseData)
  286. baseData.SetPage(page)
  287. baseData.SetList(list)
  288. resp.OkData("获取成功", baseData, c)
  289. }
  290. // ExportInvoiceList 导出销售开票统计列表
  291. func ExportInvoiceList(c *gin.Context, list []*fms.CensusSellerInvoiceItem, req fms.CensusSellerInvoiceListReq) {
  292. // 生成Excel文件
  293. xlsxFile := xlsx.NewFile()
  294. style := xlsx.NewStyle()
  295. alignment := xlsx.Alignment{
  296. Horizontal: "center",
  297. Vertical: "center",
  298. WrapText: true,
  299. }
  300. style.Alignment = alignment
  301. style.ApplyAlignment = true
  302. sheetName := "销售开票统计"
  303. sheet, err := xlsxFile.AddSheet(sheetName)
  304. if err != nil {
  305. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  306. return
  307. }
  308. // 存在筛选则前两行显示时间信息
  309. if req.StartDate != "" && req.EndDate != "" {
  310. timeData := fmt.Sprintf("时间:%s至%s", req.StartDate, req.EndDate)
  311. rowA := sheet.AddRow()
  312. cellAA := rowA.AddCell()
  313. cellAA.SetString("销售统计表")
  314. cellAA.SetStyle(style)
  315. rowB := sheet.AddRow()
  316. rowB.AddCell().SetString(timeData)
  317. // 第三行空出
  318. sheet.AddRow()
  319. }
  320. // 数据表头
  321. rowTitle := []string{"排名", "销售员", "销售组别", "收入金额(元)", "小组占比", "全员占比"}
  322. titleRow := sheet.AddRow()
  323. for i := range rowTitle {
  324. v := titleRow.AddCell()
  325. v.SetString(rowTitle[i])
  326. v.SetStyle(style)
  327. }
  328. // 填充数据
  329. for k, v := range list {
  330. dataRow := sheet.AddRow()
  331. dataRow.AddCell().SetString(fmt.Sprint(k + 1)) // 排名
  332. dataRow.AddCell().SetString(v.SellerName) // 销售员
  333. dataRow.AddCell().SetString(v.GroupName) // 销售组别
  334. dataRow.AddCell().SetString(fmt.Sprint(v.InvoiceAmount)) // 开票金额
  335. dataRow.AddCell().SetString(fmt.Sprint(v.GroupRate, "%")) // 小组占比
  336. dataRow.AddCell().SetString(fmt.Sprint(v.SellerRate, "%")) // 全员占比
  337. }
  338. // 输出文件
  339. var buffer bytes.Buffer
  340. _ = xlsxFile.Write(&buffer)
  341. content := bytes.NewReader(buffer.Bytes())
  342. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  343. fileName := sheetName + randStr + ".xlsx"
  344. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  345. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  346. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  347. }