seller.go 46 KB

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