seller.go 40 KB

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