seller.go 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  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. }
  444. var totalMoneySlice []float64
  445. historyTime, _ := time.Parse(utils.FormatDate, "2023-04-01")
  446. // 累计值
  447. var accumulate float64
  448. var startDate, endDate string
  449. //开始日期
  450. if req.StartDate != "" && req.EndDate != "" {
  451. startDate = fmt.Sprint(req.StartDate, " 00:00:00")
  452. endDate = fmt.Sprint(req.EndDate, " 23:59:59")
  453. }
  454. startDateTime, _ := time.Parse(utils.FormatDateTime, startDate)
  455. endDateTime, _ := time.Parse(utils.FormatDateTime, endDate)
  456. cond := ` 1 = 1 `
  457. historyCond := ` 1=1 `
  458. pars := make([]interface{}, 0)
  459. historyPars := make([]interface{}, 0)
  460. if req.CompanyType == 1 {
  461. cond += ` AND b.contract_type = 1 `
  462. historyCond += ` AND new_company = 1 `
  463. } else if req.CompanyType == 2 {
  464. cond += ` AND b.contract_type IN (2,3,4) `
  465. historyCond += ` AND new_company = 0 `
  466. }
  467. //if req.SellerIds != "" {
  468. // sellerIds := strings.Split(req.SellerIds, ",")
  469. // historyCond += ` AND (seller_id in ? ) `
  470. // historyPars = append(historyPars, sellerIds)
  471. //}
  472. //groupIds := make([]int, 0)
  473. //if req.GroupId > 0 {
  474. // // 筛选组别时, 查询当前组别的下级组(因为admin表存的group_id, 有三级的存的是子ID, 只有二级的存的才是父ID =_=!)
  475. // groupCond := `parent_id = ?`
  476. // groupPars := make([]interface{}, 0)
  477. // groupPars = append(groupPars, req.GroupId)
  478. // groupOB := new(crm.SysGroup)
  479. // groupList, e := groupOB.List(groupCond, groupPars)
  480. // if e != nil {
  481. // resp.FailMsg("获取失败", "获取组别下级组列表失败, Err: "+e.Error(), c)
  482. // return
  483. // }
  484. // groupIds = append(groupIds, req.GroupId)
  485. // for i := range groupList {
  486. // groupIds = append(groupIds, groupList[i].GroupId)
  487. // }
  488. // cond += ` AND (c.seller_group_id IN (?) OR d.seller_group_id IN (?))`
  489. // pars = append(pars, groupIds, groupIds)
  490. // historyCond += ` AND group_id IN (?) `
  491. // historyPars = append(historyPars, groupIds)
  492. //}
  493. // 获取销售分组信息
  494. sellerList, e := crmService.GetSellerDepartmentListWithEnable()
  495. if e != nil {
  496. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  497. return
  498. }
  499. ficcSellerIds := make([]string, 0)
  500. raiSellerIds := make([]string, 0)
  501. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  502. for i := range sellerList {
  503. sellerMap[sellerList[i].SellerId] = sellerList[i]
  504. if sellerList[i].DepartmentId == crm.SellerDepartmentId {
  505. ficcSellerIds = append(ficcSellerIds, strconv.Itoa(sellerList[i].SellerId))
  506. } else if sellerList[i].DepartmentId == crm.RaiSellerDepartmentId {
  507. raiSellerIds = append(raiSellerIds, strconv.Itoa(sellerList[i].SellerId))
  508. }
  509. }
  510. sellerIds := make([]string, 0)
  511. if req.SellerType == 1 {
  512. //cond += ` AND b.contract_type = 1 `
  513. //historyCond += ` AND new_company = 1 `
  514. sellerIds = ficcSellerIds
  515. } else if req.SellerType == 2 {
  516. //cond += ` AND b.contract_type IN (2,3,4) `
  517. //historyCond += ` AND new_company = 0 `
  518. sellerIds = raiSellerIds
  519. }
  520. st := startDate
  521. ed := endDate
  522. groupInvoiceMap := make(map[int]float64)
  523. sellerInvoiceMap := make(map[int]float64)
  524. sellerGroupMap := make(map[int]int)
  525. //校验日期,分段查询
  526. if req.StartDate == "" && req.EndDate == "" {
  527. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  528. if e != nil {
  529. return
  530. }
  531. // 开票到款金额合计(换算后)
  532. var amountTotal float64
  533. var amountSum float64
  534. if len(summaryIds) > 0 {
  535. amountCond := `a.id IN ? `
  536. amountPars := make([]interface{}, 0)
  537. amountPars = append(amountPars, summaryIds)
  538. //if len(groupIds) > 0 {
  539. // amountCond += ` AND IF ( a.invoice_id = 0, d.seller_group_id, b.seller_group_id ) IN (?) `
  540. // amountPars = append(amountPars, groupIds)
  541. //}
  542. if req.SellerType != 0 {
  543. //sellerIds := strings.Split(req.SellerIds, ",")
  544. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time > "2023-04-01")`
  545. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time > "2023-04-01")) `
  546. amountPars = append(amountPars, sellerIds, sellerIds)
  547. } else {
  548. amountCond += ` AND ((a.invoice_id <> 0 )`
  549. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 ))`
  550. amountPars = append(amountPars)
  551. }
  552. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  553. if e != nil {
  554. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  555. return
  556. }
  557. //dataList = append(dataList, results...)
  558. for _, result := range results {
  559. amountSum += result.Amount
  560. fmt.Println("result.Amount:", result.Amount)
  561. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  562. groupInvoiceMap[result.SellerGroupId] += result.Amount
  563. } else {
  564. groupInvoiceMap[result.SellerGroupId] = result.Amount
  565. }
  566. if _, ok := sellerInvoiceMap[result.FinalSellerId]; ok {
  567. sellerInvoiceMap[result.FinalSellerId] += result.Amount
  568. } else {
  569. sellerInvoiceMap[result.FinalSellerId] = result.Amount
  570. }
  571. if _, ok := sellerGroupMap[result.FinalSellerId]; !ok {
  572. sellerGroupMap[result.FinalSellerId] = result.SellerGroupId
  573. }
  574. }
  575. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  576. accumulate += amountTotal
  577. amountSum = 0
  578. }
  579. results, e := fms.GetIncomeHistory(historyCond, historyPars)
  580. if e != nil {
  581. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  582. return
  583. }
  584. for _, result := range results {
  585. amountSum += result.Amount
  586. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  587. groupInvoiceMap[result.SellerGroupId] += result.Amount
  588. } else {
  589. groupInvoiceMap[result.SellerGroupId] = result.Amount
  590. }
  591. if _, ok := sellerInvoiceMap[result.FinalSellerId]; ok {
  592. sellerInvoiceMap[result.FinalSellerId] += result.Amount
  593. } else {
  594. sellerInvoiceMap[result.FinalSellerId] = result.Amount
  595. }
  596. if _, ok := sellerGroupMap[result.FinalSellerId]; !ok {
  597. sellerGroupMap[result.FinalSellerId] = result.SellerGroupId
  598. }
  599. }
  600. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  601. accumulate += amountTotal
  602. } else if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
  603. //全部走新查询
  604. //fmt.Println("新查询")
  605. if st != "" && ed != "" {
  606. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  607. pars = append(pars, st, ed, st, ed)
  608. }
  609. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  610. if e != nil {
  611. return
  612. }
  613. // 开票到款金额合计(换算后)
  614. var amountTotal float64
  615. if len(summaryIds) > 0 {
  616. amountCond := `a.id IN ? `
  617. amountPars := make([]interface{}, 0)
  618. amountPars = append(amountPars, summaryIds)
  619. //if len(groupIds) > 0 {
  620. // amountCond += ` AND IF ( a.invoice_id = 0, d.seller_group_id, b.seller_group_id ) IN (?) `
  621. // amountPars = append(amountPars, groupIds)
  622. //}
  623. if req.SellerType != 0 {
  624. //sellerIds := strings.Split(req.SellerIds, ",")
  625. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  626. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  627. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  628. } else {
  629. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  630. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  631. amountPars = append(amountPars, st, ed, st, ed)
  632. }
  633. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  634. if e != nil {
  635. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  636. return
  637. }
  638. //dataList = append(dataList, results...)
  639. var amountSum float64
  640. for _, result := range results {
  641. amountSum += result.Amount
  642. fmt.Println("result.Amount:", result.Amount)
  643. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  644. groupInvoiceMap[result.SellerGroupId] += result.Amount
  645. } else {
  646. groupInvoiceMap[result.SellerGroupId] = result.Amount
  647. }
  648. if _, ok := sellerInvoiceMap[result.FinalSellerId]; ok {
  649. sellerInvoiceMap[result.FinalSellerId] += result.Amount
  650. } else {
  651. sellerInvoiceMap[result.FinalSellerId] = result.Amount
  652. }
  653. if _, ok := sellerGroupMap[result.FinalSellerId]; !ok {
  654. sellerGroupMap[result.FinalSellerId] = result.SellerGroupId
  655. }
  656. }
  657. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  658. accumulate += amountTotal
  659. }
  660. } else if endDateTime.Before(historyTime) || endDateTime.Equal(historyTime) {
  661. //全部走旧查询
  662. //fmt.Println("旧查询")
  663. //fmt.Println("st:",st)
  664. //fmt.Println("ed:",ed)
  665. if st != "" && ed != "" {
  666. historyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  667. historyPars = append(historyPars, st, ed)
  668. }
  669. //fmt.Println("st:",st)
  670. //fmt.Println("ed:",ed)
  671. // 开票到款金额合计(换算后)
  672. var amountTotal float64
  673. results, e := fms.GetIncomeHistory(historyCond, historyPars)
  674. if e != nil {
  675. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  676. return
  677. }
  678. var amountSum float64
  679. //dataList = append(dataList, results...)
  680. for _, result := range results {
  681. amountSum += result.Amount
  682. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  683. groupInvoiceMap[result.SellerGroupId] += result.Amount
  684. } else {
  685. groupInvoiceMap[result.SellerGroupId] = result.Amount
  686. }
  687. if _, ok := sellerInvoiceMap[result.FinalSellerId]; ok {
  688. sellerInvoiceMap[result.FinalSellerId] += result.Amount
  689. } else {
  690. sellerInvoiceMap[result.FinalSellerId] = result.Amount
  691. }
  692. if _, ok := sellerGroupMap[result.FinalSellerId]; !ok {
  693. sellerGroupMap[result.FinalSellerId] = result.SellerGroupId
  694. }
  695. }
  696. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  697. accumulate += amountTotal
  698. //fmt.Println("partAccumulate:",partAccumulate)
  699. } else {
  700. if st != "" && ed != "" {
  701. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  702. pars = append(pars, st, ed, st, ed)
  703. }
  704. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  705. if e != nil {
  706. return
  707. }
  708. // 开票到款金额合计(换算后)
  709. var amountTotal float64
  710. var amountSum float64
  711. if len(summaryIds) > 0 {
  712. amountCond := `a.id IN ? `
  713. amountPars := make([]interface{}, 0)
  714. amountPars = append(amountPars, summaryIds)
  715. //if len(groupIds) > 0 {
  716. // amountCond += ` AND IF ( a.invoice_id = 0, d.seller_group_id, b.seller_group_id ) IN (?) `
  717. // amountPars = append(amountPars, groupIds)
  718. //}
  719. if req.SellerType != 0 {
  720. //sellerIds := strings.Split(req.SellerIds, ",")
  721. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  722. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  723. amountPars = append(amountPars, sellerIds, historyTime, ed, sellerIds, historyTime, ed)
  724. } else {
  725. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  726. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  727. amountPars = append(amountPars, historyTime, ed, historyTime, ed)
  728. }
  729. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  730. if e != nil {
  731. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  732. return
  733. }
  734. //dataList = append(dataList, results...)
  735. for _, result := range results {
  736. amountSum += result.Amount
  737. fmt.Println("result.Amount:", result.Amount)
  738. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  739. groupInvoiceMap[result.SellerGroupId] += result.Amount
  740. } else {
  741. groupInvoiceMap[result.SellerGroupId] = result.Amount
  742. }
  743. if _, ok := sellerInvoiceMap[result.FinalSellerId]; ok {
  744. sellerInvoiceMap[result.FinalSellerId] += result.Amount
  745. } else {
  746. sellerInvoiceMap[result.FinalSellerId] = result.Amount
  747. }
  748. if _, ok := sellerGroupMap[result.FinalSellerId]; !ok {
  749. sellerGroupMap[result.FinalSellerId] = result.SellerGroupId
  750. }
  751. }
  752. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  753. accumulate += amountTotal
  754. amountSum = 0
  755. }
  756. if st != "" && ed != "" {
  757. historyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  758. historyPars = append(historyPars, st, historyTime)
  759. }
  760. results, e := fms.GetIncomeHistory(historyCond, historyPars)
  761. if e != nil {
  762. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  763. return
  764. }
  765. for _, result := range results {
  766. amountSum += result.Amount
  767. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  768. groupInvoiceMap[result.SellerGroupId] += result.Amount
  769. } else {
  770. groupInvoiceMap[result.SellerGroupId] = result.Amount
  771. }
  772. if _, ok := sellerInvoiceMap[result.FinalSellerId]; ok {
  773. sellerInvoiceMap[result.FinalSellerId] += result.Amount
  774. } else {
  775. sellerInvoiceMap[result.FinalSellerId] = result.Amount
  776. }
  777. if _, ok := sellerGroupMap[result.FinalSellerId]; !ok {
  778. sellerGroupMap[result.FinalSellerId] = result.SellerGroupId
  779. }
  780. }
  781. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  782. accumulate += amountTotal
  783. }
  784. fmt.Println("totalMoneySlice:", len(totalMoneySlice))
  785. adminOB := new(crm.Admin)
  786. adminPars := make([]interface{}, 0)
  787. adminCond := ` 1=1 `
  788. if req.SellerType != 0 {
  789. adminCond += ` AND department_id = ? `
  790. adminPars = append(adminPars, departmentId)
  791. }
  792. if req.SellerIds != "" {
  793. adminSellerIds := strings.Split(req.SellerIds, ",")
  794. adminCond += ` AND admin_id IN ? `
  795. adminPars = append(adminPars, adminSellerIds)
  796. }
  797. if !req.ShowResign {
  798. adminCond += ` AND enabled = 1 `
  799. }
  800. adminList, e := adminOB.List(adminCond, adminPars)
  801. if e != nil {
  802. resp.FailMsg("获取失败", "获取销售列表失败, Err: "+e.Error(), c)
  803. return
  804. }
  805. list := make([]*fms.CensusSellerInvoiceItem, 0)
  806. for _, v := range adminList {
  807. if vv, ok := sellerInvoiceMap[v.AdminId]; ok {
  808. rate := vv / accumulate
  809. mulNum := decimal.NewFromFloat(100)
  810. newRate := decimal.NewFromFloat(rate)
  811. newRate = newRate.Mul(mulNum).Round(2)
  812. finalRate, _ := newRate.Float64()
  813. groupId := sellerGroupMap[v.AdminId]
  814. groupRate := vv / groupInvoiceMap[groupId]
  815. newGroupRate := decimal.NewFromFloat(groupRate)
  816. newGroupRate = newGroupRate.Mul(mulNum).Round(2)
  817. finalGroupRate, _ := newGroupRate.Float64()
  818. amuont, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", vv), 64)
  819. var sellerName, groupName string
  820. if seller, ok := sellerMap[v.AdminId]; ok {
  821. sellerName = seller.SellerName
  822. groupName = seller.GroupName
  823. }
  824. list = append(list, &fms.CensusSellerInvoiceItem{
  825. SellerId: v.AdminId,
  826. SellerName: sellerName,
  827. GroupId: groupId,
  828. GroupName: groupName,
  829. InvoiceAmount: amuont,
  830. GroupRate: finalGroupRate,
  831. SellerRate: finalRate,
  832. })
  833. }
  834. }
  835. sort.Slice(list, func(i, j int) bool {
  836. if req.SortField == 2 {
  837. if req.SortType == 2 {
  838. return list[i].GroupRate < list[j].GroupRate
  839. } else {
  840. return list[i].GroupRate > list[j].GroupRate
  841. }
  842. } else {
  843. if req.SortType == 2 {
  844. return list[i].InvoiceAmount < list[j].InvoiceAmount
  845. } else {
  846. return list[i].InvoiceAmount > list[j].InvoiceAmount
  847. }
  848. }
  849. })
  850. //var respList fmsService.CensusSellerListByAmountAsc
  851. //respList = list
  852. //sort.Sort(list)
  853. // 是否导出
  854. if req.IsExport == 1 {
  855. ExportInvoiceList(c, list, req)
  856. return
  857. }
  858. page.SetTotal(int64(len(list)))
  859. baseData := new(base.BaseData)
  860. baseData.SetPage(page)
  861. if req.Current*req.PageSize > int64(len(list)) {
  862. baseData.SetList(list[(req.Current-1)*req.PageSize : len(list)])
  863. } else {
  864. baseData.SetList(list[(req.Current-1)*req.PageSize : req.Current*req.PageSize])
  865. }
  866. resp.OkData("获取成功", baseData, c)
  867. }
  868. // ExportInvoiceList 导出销售开票统计列表
  869. func ExportInvoiceList(c *gin.Context, list []*fms.CensusSellerInvoiceItem, req fms.CensusSellerInvoiceListReq) {
  870. // 生成Excel文件
  871. xlsxFile := xlsx.NewFile()
  872. style := xlsx.NewStyle()
  873. alignment := xlsx.Alignment{
  874. Horizontal: "center",
  875. Vertical: "center",
  876. WrapText: true,
  877. }
  878. style.Alignment = alignment
  879. style.ApplyAlignment = true
  880. sheetName := "销售开票统计"
  881. sheet, err := xlsxFile.AddSheet(sheetName)
  882. if err != nil {
  883. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  884. return
  885. }
  886. // 存在筛选则前两行显示时间信息
  887. if req.StartDate != "" && req.EndDate != "" {
  888. timeData := fmt.Sprintf("时间:%s至%s", req.StartDate, req.EndDate)
  889. rowA := sheet.AddRow()
  890. cellAA := rowA.AddCell()
  891. cellAA.SetString("销售统计表")
  892. cellAA.SetStyle(style)
  893. rowB := sheet.AddRow()
  894. rowB.AddCell().SetString(timeData)
  895. // 第三行空出
  896. sheet.AddRow()
  897. }
  898. // 数据表头
  899. rowTitle := []string{"排名", "销售员", "销售组别", "收入金额(元)", "小组占比", "全员占比"}
  900. titleRow := sheet.AddRow()
  901. for i := range rowTitle {
  902. v := titleRow.AddCell()
  903. v.SetString(rowTitle[i])
  904. v.SetStyle(style)
  905. }
  906. // 填充数据
  907. for k, v := range list {
  908. dataRow := sheet.AddRow()
  909. dataRow.AddCell().SetString(fmt.Sprint(k + 1)) // 排名
  910. dataRow.AddCell().SetString(v.SellerName) // 销售员
  911. dataRow.AddCell().SetString(v.GroupName) // 销售组别
  912. dataRow.AddCell().SetString(fmt.Sprintf("%.2f", v.InvoiceAmount)) // 开票金额
  913. dataRow.AddCell().SetString(fmt.Sprint(v.GroupRate, "%")) // 小组占比
  914. dataRow.AddCell().SetString(fmt.Sprint(v.SellerRate, "%")) // 全员占比
  915. }
  916. // 输出文件
  917. var buffer bytes.Buffer
  918. _ = xlsxFile.Write(&buffer)
  919. content := bytes.NewReader(buffer.Bytes())
  920. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  921. fileName := sheetName + randStr + ".xlsx"
  922. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  923. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  924. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  925. }
  926. // GroupInvoiceList
  927. // @Title 销售组开票统计列表
  928. // @Description 销售组开票统计列表
  929. // @Param StartDate query string false "开始日期"
  930. // @Param EndDate query string false "结束日期"
  931. // @Param SortField query int false "排序字段: 1-开票金额; 2-组别占比"
  932. // @Param SortType query int false "排序方式: 1-正序; 2-倒序"
  933. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  934. // @Success 200 {object} fms.CensusSellerGroupInvoiceItem
  935. // @router /census/seller/group_invoice_list [get]
  936. func (this *SellerController) GroupInvoiceListV2(c *gin.Context) {
  937. var req fms.CensusSellerGroupInvoiceListReq
  938. if e := c.BindQuery(&req); e != nil {
  939. err, ok := e.(validator.ValidationErrors)
  940. if !ok {
  941. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  942. return
  943. }
  944. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  945. return
  946. }
  947. //if req.SellerIds != "" {
  948. // sellerIds := strings.Split(req.SellerIds, ",")
  949. // cond += ` AND (a.seller_id in ? ) `
  950. // historyCond += ` AND (seller_id in ? ) `
  951. // pars = append(pars, sellerIds)
  952. // historyPars = append(historyPars, sellerIds)
  953. //}
  954. var totalMoneySlice []float64
  955. historyTime, _ := time.Parse(utils.FormatDate, "2023-04-01")
  956. // 累计值
  957. var accumulate float64
  958. //dataList := make([]*fms.IncomeSummaryItem, 0)
  959. //historydataList := make([]*fms.IncomeSummaryItem, 0)
  960. //timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
  961. var startDate, endDate string
  962. //开始日期
  963. if req.StartDate != "" && req.EndDate != "" {
  964. startDate = fmt.Sprint(req.StartDate, " 00:00:00")
  965. endDate = fmt.Sprint(req.EndDate, " 23:59:59")
  966. }
  967. startDateTime, _ := time.Parse(utils.FormatDate, req.StartDate)
  968. endDateTime, _ := time.Parse(utils.FormatDate, req.EndDate)
  969. cond := `1 = 1`
  970. histortyCond := `1 = 1`
  971. pars := make([]interface{}, 0)
  972. historyPars := make([]interface{}, 0)
  973. if req.CompanyType == 1 {
  974. cond += ` AND b.contract_type = 1 `
  975. histortyCond += ` AND new_company = 1 `
  976. } else if req.CompanyType == 2 {
  977. cond += ` AND b.contract_type IN (2,3,4) `
  978. histortyCond += ` AND new_company = 0 `
  979. }
  980. //if req.SellerIds != "" {
  981. // sellerIds := strings.Split(req.SellerIds, ",")
  982. // cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  983. // pars = append(pars, sellerIds, sellerIds)
  984. // prevCond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  985. // prevPars = append(prevPars, sellerIds, sellerIds)
  986. // histrtyCond += ` AND seller_id in ? `
  987. // prevHistoryCond += ` AND seller_id in ? `
  988. // historyPars = append(historyPars, sellerIds)
  989. // prevHistoryPars = append(prevHistoryPars, sellerIds)
  990. //}
  991. st := fmt.Sprint(startDate, " 00:00:00")
  992. ed := fmt.Sprint(endDate, " 23:59:59")
  993. groupInvoiceMap := make(map[int]float64)
  994. //校验日期,分段查询
  995. if req.StartDate == "" && req.EndDate == "" {
  996. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  997. if e != nil {
  998. return
  999. }
  1000. // 开票到款金额合计(换算后)
  1001. var amountTotal float64
  1002. var amountSum float64
  1003. if len(summaryIds) > 0 {
  1004. amountCond := `a.id IN ? `
  1005. amountPars := make([]interface{}, 0)
  1006. amountPars = append(amountPars, summaryIds)
  1007. if req.SellerIds != "" {
  1008. sellerIds := strings.Split(req.SellerIds, ",")
  1009. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1010. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1011. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  1012. } else {
  1013. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1014. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1015. amountPars = append(amountPars, st, ed, st, ed)
  1016. }
  1017. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1018. if e != nil {
  1019. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1020. return
  1021. }
  1022. //dataList = append(dataList, results...)
  1023. for _, result := range results {
  1024. amountSum += result.Amount
  1025. fmt.Println("result.Amount:", result.Amount)
  1026. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1027. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1028. } else {
  1029. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1030. }
  1031. }
  1032. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1033. accumulate += amountTotal
  1034. amountSum = 0
  1035. }
  1036. //var amountTotal float64
  1037. results, e := fms.GetIncomeHistory(histortyCond, historyPars)
  1038. if e != nil {
  1039. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1040. return
  1041. }
  1042. //dataList = append(dataList, results...)
  1043. for _, result := range results {
  1044. amountSum += result.Amount
  1045. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1046. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1047. } else {
  1048. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1049. }
  1050. }
  1051. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1052. accumulate += amountTotal
  1053. } else if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
  1054. //全部走新查询
  1055. //fmt.Println("新查询")
  1056. if st != "" && ed != "" {
  1057. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1058. pars = append(pars, st, ed, st, ed)
  1059. }
  1060. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1061. if e != nil {
  1062. return
  1063. }
  1064. // 开票到款金额合计(换算后)
  1065. var amountTotal float64
  1066. if len(summaryIds) > 0 {
  1067. amountCond := `a.id IN ? `
  1068. amountPars := make([]interface{}, 0)
  1069. amountPars = append(amountPars, summaryIds)
  1070. if req.SellerIds != "" {
  1071. sellerIds := strings.Split(req.SellerIds, ",")
  1072. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1073. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1074. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  1075. } else {
  1076. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1077. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1078. amountPars = append(amountPars, st, ed, st, ed)
  1079. }
  1080. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1081. if e != nil {
  1082. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1083. return
  1084. }
  1085. //dataList = append(dataList, results...)
  1086. var amountSum float64
  1087. for _, result := range results {
  1088. amountSum += result.Amount
  1089. fmt.Println("result.Amount:", result.Amount)
  1090. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1091. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1092. } else {
  1093. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1094. }
  1095. }
  1096. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1097. accumulate += amountTotal
  1098. }
  1099. } else if endDateTime.Before(historyTime) || endDateTime.Equal(historyTime) {
  1100. //全部走旧查询
  1101. //fmt.Println("旧查询")
  1102. //fmt.Println("st:",st)
  1103. //fmt.Println("ed:",ed)
  1104. if st != "" && ed != "" {
  1105. histortyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1106. historyPars = append(historyPars, st, ed)
  1107. }
  1108. //fmt.Println("st:",st)
  1109. //fmt.Println("ed:",ed)
  1110. // 开票到款金额合计(换算后)
  1111. var amountTotal float64
  1112. results, e := fms.GetIncomeHistory(histortyCond, historyPars)
  1113. if e != nil {
  1114. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1115. return
  1116. }
  1117. var amountSum float64
  1118. //dataList = append(dataList, results...)
  1119. for _, result := range results {
  1120. amountSum += result.Amount
  1121. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1122. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1123. } else {
  1124. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1125. }
  1126. }
  1127. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1128. accumulate += amountTotal
  1129. //fmt.Println("partAccumulate:",partAccumulate)
  1130. } else {
  1131. // 有时间,分段查询
  1132. // 新查询
  1133. if st != "" && ed != "" {
  1134. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1135. pars = append(pars, st, ed, st, ed)
  1136. }
  1137. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1138. if e != nil {
  1139. return
  1140. }
  1141. // 开票到款金额合计(换算后)
  1142. var amountTotal float64
  1143. var amountSum float64
  1144. if len(summaryIds) > 0 {
  1145. amountCond := `a.id IN ? `
  1146. amountPars := make([]interface{}, 0)
  1147. amountPars = append(amountPars, summaryIds)
  1148. if req.SellerIds != "" {
  1149. sellerIds := strings.Split(req.SellerIds, ",")
  1150. amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1151. amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1152. amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  1153. } else {
  1154. amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1155. amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1156. amountPars = append(amountPars, st, ed, st, ed)
  1157. }
  1158. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1159. if e != nil {
  1160. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1161. return
  1162. }
  1163. //dataList = append(dataList, results...)
  1164. for _, result := range results {
  1165. amountSum += result.Amount
  1166. fmt.Println("result.Amount:", result.Amount)
  1167. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1168. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1169. } else {
  1170. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1171. }
  1172. }
  1173. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1174. accumulate += amountTotal
  1175. amountSum = 0
  1176. //var amountTotal float64
  1177. // 旧查询
  1178. }
  1179. if st != "" && ed != "" {
  1180. histortyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1181. historyPars = append(historyPars, st, ed)
  1182. }
  1183. results, e := fms.GetIncomeHistory(histortyCond, historyPars)
  1184. if e != nil {
  1185. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1186. return
  1187. }
  1188. //dataList = append(dataList, results...)
  1189. for _, result := range results {
  1190. amountSum += result.Amount
  1191. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1192. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1193. } else {
  1194. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1195. }
  1196. }
  1197. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1198. accumulate += amountTotal
  1199. }
  1200. fmt.Println("totalMoneySlice:", len(totalMoneySlice))
  1201. var departmentId int
  1202. if req.SellerType == 1 {
  1203. departmentId = crm.SellerDepartmentId
  1204. } else if req.SellerType == 2 {
  1205. departmentId = crm.RaiSellerDepartmentId
  1206. } else if req.SellerType == 0 {
  1207. resp.FailMsg("查询错误", "请选择正确的销售类型", c)
  1208. return
  1209. } else {
  1210. resp.FailMsg("查询错误", "请选择正确的销售类型", c)
  1211. return
  1212. }
  1213. groupCond := ` department_id = %d AND parent_id = 0 `
  1214. groupCond = fmt.Sprintf(groupCond, departmentId)
  1215. groupPars := make([]interface{}, 0)
  1216. groupOB := new(crm.SysGroup)
  1217. groupList, e := groupOB.List(groupCond, groupPars)
  1218. if e != nil {
  1219. resp.FailMsg("查询错误", fmt.Sprintf("获取组别列表失败, Err: %s", e.Error()), c)
  1220. return
  1221. }
  1222. //total := len(groupList)
  1223. groupMap := make(map[int]*crm.SysGroup)
  1224. for i := range groupList {
  1225. groupMap[groupList[i].GroupId] = groupList[i]
  1226. }
  1227. list := make([]*fms.CensusSellerGroupInvoiceItem, 0)
  1228. for _, group := range groupList {
  1229. if v, ok := groupInvoiceMap[group.GroupId]; ok {
  1230. rate := v / accumulate
  1231. mulNum := decimal.NewFromFloat(100)
  1232. newRate := decimal.NewFromFloat(rate)
  1233. newRate = newRate.Mul(mulNum).Round(2)
  1234. finalRate, _ := newRate.Float64()
  1235. amuont, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", v), 64)
  1236. groupName := ""
  1237. if groupItem, ok := groupMap[group.GroupId]; ok {
  1238. groupName = groupItem.GroupName
  1239. }
  1240. list = append(list, &fms.CensusSellerGroupInvoiceItem{
  1241. GroupId: group.GroupId,
  1242. GroupName: groupName,
  1243. InvoiceAmount: amuont,
  1244. GroupRate: finalRate,
  1245. })
  1246. }
  1247. }
  1248. sort.Slice(list, func(i, j int) bool {
  1249. if req.SortField == 2 {
  1250. if req.SortType == 2 {
  1251. return list[i].GroupRate < list[j].GroupRate
  1252. } else {
  1253. return list[i].GroupRate > list[j].GroupRate
  1254. }
  1255. } else {
  1256. if req.SortType == 2 {
  1257. return list[i].InvoiceAmount < list[j].InvoiceAmount
  1258. } else {
  1259. return list[i].InvoiceAmount > list[j].InvoiceAmount
  1260. }
  1261. }
  1262. })
  1263. //var respList fms.CensusSellerGroupList
  1264. //respList = list
  1265. //sort.Sort(respList)
  1266. // 是否导出
  1267. if req.IsExport == 1 {
  1268. ExportGroupInvoiceList(c, list, req)
  1269. return
  1270. }
  1271. resp.OkData("获取成功", list, c)
  1272. }