seller.go 46 KB

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