seller.go 16 KB

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