seller.go 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  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.Sprintf("%.2f", 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 IF ( a.invoice_id = 0, d.seller_group_id, b.seller_group_id ) IN (?) `
  538. amountPars = append(amountPars, 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 IF ( a.invoice_id = 0, d.seller_group_id, b.seller_group_id ) IN (?) `
  619. amountPars = append(amountPars, 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 IF ( a.invoice_id = 0, d.seller_group_id, b.seller_group_id ) IN (?) `
  715. amountPars = append(amountPars, 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. sort.Slice(list, func(i, j int) bool {
  844. if req.SortField == 2 {
  845. if req.SortType == 2 {
  846. return list[i].GroupRate < list[j].GroupRate
  847. } else {
  848. return list[i].GroupRate > list[j].GroupRate
  849. }
  850. } else {
  851. if req.SortType == 2 {
  852. return list[i].InvoiceAmount < list[j].InvoiceAmount
  853. } else {
  854. return list[i].InvoiceAmount > list[j].InvoiceAmount
  855. }
  856. }
  857. })
  858. //var respList fmsService.CensusSellerListByAmountAsc
  859. //respList = list
  860. //sort.Sort(list)
  861. // 是否导出
  862. if req.IsExport == 1 {
  863. ExportInvoiceList(c, list, req)
  864. return
  865. }
  866. page.SetTotal(int64(len(list)))
  867. baseData := new(base.BaseData)
  868. baseData.SetPage(page)
  869. if req.Current*req.PageSize > int64(len(list)) {
  870. baseData.SetList(list[(req.Current-1)*req.PageSize : len(list)])
  871. } else {
  872. baseData.SetList(list[(req.Current-1)*req.PageSize : req.Current*req.PageSize])
  873. }
  874. resp.OkData("获取成功", baseData, c)
  875. }
  876. // ExportInvoiceList 导出销售开票统计列表
  877. func ExportInvoiceList(c *gin.Context, list []*fms.CensusSellerInvoiceItem, req fms.CensusSellerInvoiceListReq) {
  878. // 生成Excel文件
  879. xlsxFile := xlsx.NewFile()
  880. style := xlsx.NewStyle()
  881. alignment := xlsx.Alignment{
  882. Horizontal: "center",
  883. Vertical: "center",
  884. WrapText: true,
  885. }
  886. style.Alignment = alignment
  887. style.ApplyAlignment = true
  888. sheetName := "销售开票统计"
  889. sheet, err := xlsxFile.AddSheet(sheetName)
  890. if err != nil {
  891. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  892. return
  893. }
  894. // 存在筛选则前两行显示时间信息
  895. if req.StartDate != "" && req.EndDate != "" {
  896. timeData := fmt.Sprintf("时间:%s至%s", req.StartDate, req.EndDate)
  897. rowA := sheet.AddRow()
  898. cellAA := rowA.AddCell()
  899. cellAA.SetString("销售统计表")
  900. cellAA.SetStyle(style)
  901. rowB := sheet.AddRow()
  902. rowB.AddCell().SetString(timeData)
  903. // 第三行空出
  904. sheet.AddRow()
  905. }
  906. // 数据表头
  907. rowTitle := []string{"排名", "销售员", "销售组别", "收入金额(元)", "小组占比", "全员占比"}
  908. titleRow := sheet.AddRow()
  909. for i := range rowTitle {
  910. v := titleRow.AddCell()
  911. v.SetString(rowTitle[i])
  912. v.SetStyle(style)
  913. }
  914. // 填充数据
  915. for k, v := range list {
  916. dataRow := sheet.AddRow()
  917. dataRow.AddCell().SetString(fmt.Sprint(k + 1)) // 排名
  918. dataRow.AddCell().SetString(v.SellerName) // 销售员
  919. dataRow.AddCell().SetString(v.GroupName) // 销售组别
  920. dataRow.AddCell().SetString(fmt.Sprintf("%.2f", v.InvoiceAmount)) // 开票金额
  921. dataRow.AddCell().SetString(fmt.Sprint(v.GroupRate, "%")) // 小组占比
  922. dataRow.AddCell().SetString(fmt.Sprint(v.SellerRate, "%")) // 全员占比
  923. }
  924. // 输出文件
  925. var buffer bytes.Buffer
  926. _ = xlsxFile.Write(&buffer)
  927. content := bytes.NewReader(buffer.Bytes())
  928. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  929. fileName := sheetName + randStr + ".xlsx"
  930. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  931. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  932. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  933. }
  934. // GroupInvoiceList
  935. // @Title 销售组开票统计列表
  936. // @Description 销售组开票统计列表
  937. // @Param StartDate query string false "开始日期"
  938. // @Param EndDate query string false "结束日期"
  939. // @Param SortField query int false "排序字段: 1-开票金额; 2-组别占比"
  940. // @Param SortType query int false "排序方式: 1-正序; 2-倒序"
  941. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  942. // @Success 200 {object} fms.CensusSellerGroupInvoiceItem
  943. // @router /census/seller/group_invoice_list [get]
  944. func (this *SellerController) GroupInvoiceListV2(c *gin.Context) {
  945. var req fms.CensusSellerGroupInvoiceListReq
  946. if e := c.BindQuery(&req); e != nil {
  947. err, ok := e.(validator.ValidationErrors)
  948. if !ok {
  949. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  950. return
  951. }
  952. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  953. return
  954. }
  955. //if req.SellerIds != "" {
  956. // sellerIds := strings.Split(req.SellerIds, ",")
  957. // cond += ` AND (a.seller_id in ? ) `
  958. // historyCond += ` AND (seller_id in ? ) `
  959. // pars = append(pars, sellerIds)
  960. // historyPars = append(historyPars, sellerIds)
  961. //}
  962. var totalMoneySlice []float64
  963. historyTime, _ := time.Parse(utils.FormatDate, "2023-04-01")
  964. // 累计值
  965. var accumulate float64
  966. //dataList := make([]*fms.IncomeSummaryItem, 0)
  967. //historydataList := make([]*fms.IncomeSummaryItem, 0)
  968. //timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
  969. var startDate, endDate string
  970. //开始日期
  971. if req.StartDate != "" && req.EndDate != "" {
  972. startDate = fmt.Sprint(req.StartDate, " 00:00:00")
  973. endDate = fmt.Sprint(req.EndDate, " 23:59:59")
  974. }
  975. startDateTime, _ := time.Parse(utils.FormatDate, req.StartDate)
  976. endDateTime, _ := time.Parse(utils.FormatDate, req.EndDate)
  977. cond := `1 = 1`
  978. histortyCond := `1 = 1`
  979. pars := make([]interface{}, 0)
  980. historyPars := make([]interface{}, 0)
  981. if req.CompanyType == 1 {
  982. cond += ` AND b.contract_type = 1 `
  983. histortyCond += ` AND new_company = 1 `
  984. } else if req.CompanyType == 2 {
  985. cond += ` AND b.contract_type IN (2,3,4) `
  986. histortyCond += ` AND new_company = 0 `
  987. }
  988. //if req.SellerIds != "" {
  989. // sellerIds := strings.Split(req.SellerIds, ",")
  990. // cond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  991. // pars = append(pars, sellerIds, sellerIds)
  992. // prevCond += ` AND (c.seller_id in ? OR d.seller_id in ?)`
  993. // prevPars = append(prevPars, sellerIds, sellerIds)
  994. // histrtyCond += ` AND seller_id in ? `
  995. // prevHistoryCond += ` AND seller_id in ? `
  996. // historyPars = append(historyPars, sellerIds)
  997. // prevHistoryPars = append(prevHistoryPars, sellerIds)
  998. //}
  999. st := fmt.Sprint(startDate, " 00:00:00")
  1000. ed := fmt.Sprint(endDate, " 23:59:59")
  1001. groupInvoiceMap := make(map[int]float64)
  1002. //校验日期,分段查询
  1003. if req.StartDate == "" && req.EndDate == "" {
  1004. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1005. if e != nil {
  1006. return
  1007. }
  1008. // 开票到款金额合计(换算后)
  1009. var amountTotal float64
  1010. var amountSum float64
  1011. if len(summaryIds) > 0 {
  1012. amountCond := `a.id IN ? `
  1013. amountPars := make([]interface{}, 0)
  1014. amountPars = append(amountPars, summaryIds)
  1015. //if req.SellerIds != "" {
  1016. // sellerIds := strings.Split(req.SellerIds, ",")
  1017. // amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1018. // amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1019. // amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  1020. //} else {
  1021. // amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1022. // amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1023. // amountPars = append(amountPars, st, ed, st, ed)
  1024. //}
  1025. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1026. if e != nil {
  1027. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1028. return
  1029. }
  1030. //dataList = append(dataList, results...)
  1031. for _, result := range results {
  1032. amountSum += result.Amount
  1033. fmt.Println("result.Amount:", result.Amount)
  1034. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1035. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1036. } else {
  1037. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1038. }
  1039. }
  1040. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1041. accumulate += amountTotal
  1042. amountSum = 0
  1043. }
  1044. //var amountTotal float64
  1045. results, e := fms.GetIncomeHistory(histortyCond, historyPars)
  1046. if e != nil {
  1047. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1048. return
  1049. }
  1050. //dataList = append(dataList, results...)
  1051. for _, result := range results {
  1052. amountSum += result.Amount
  1053. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1054. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1055. } else {
  1056. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1057. }
  1058. }
  1059. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1060. accumulate += amountTotal
  1061. } else if startDateTime.After(historyTime) || startDateTime.Equal(historyTime) {
  1062. //全部走新查询
  1063. //fmt.Println("新查询")
  1064. if st != "" && ed != "" {
  1065. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1066. pars = append(pars, st, ed, st, ed)
  1067. }
  1068. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1069. if e != nil {
  1070. return
  1071. }
  1072. // 开票到款金额合计(换算后)
  1073. var amountTotal float64
  1074. if len(summaryIds) > 0 {
  1075. amountCond := `a.id IN ? `
  1076. amountPars := make([]interface{}, 0)
  1077. amountPars = append(amountPars, summaryIds)
  1078. //if req.SellerIds != "" {
  1079. // sellerIds := strings.Split(req.SellerIds, ",")
  1080. // amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1081. // amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1082. // amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  1083. //} else {
  1084. // amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1085. // amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1086. // amountPars = append(amountPars, st, ed, st, ed)
  1087. //}
  1088. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1089. if e != nil {
  1090. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1091. return
  1092. }
  1093. //dataList = append(dataList, results...)
  1094. var amountSum float64
  1095. for _, result := range results {
  1096. amountSum += result.Amount
  1097. fmt.Println("result.Amount:", result.Amount)
  1098. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1099. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1100. } else {
  1101. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1102. }
  1103. }
  1104. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1105. accumulate += amountTotal
  1106. }
  1107. } else if endDateTime.Before(historyTime) || endDateTime.Equal(historyTime) {
  1108. //全部走旧查询
  1109. //fmt.Println("旧查询")
  1110. //fmt.Println("st:",st)
  1111. //fmt.Println("ed:",ed)
  1112. if st != "" && ed != "" {
  1113. histortyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1114. historyPars = append(historyPars, st, ed)
  1115. }
  1116. //fmt.Println("st:",st)
  1117. //fmt.Println("ed:",ed)
  1118. // 开票到款金额合计(换算后)
  1119. var amountTotal float64
  1120. results, e := fms.GetIncomeHistory(histortyCond, historyPars)
  1121. if e != nil {
  1122. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1123. return
  1124. }
  1125. var amountSum float64
  1126. //dataList = append(dataList, results...)
  1127. for _, result := range results {
  1128. amountSum += result.Amount
  1129. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1130. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1131. } else {
  1132. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1133. }
  1134. }
  1135. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1136. accumulate += amountTotal
  1137. //fmt.Println("partAccumulate:",partAccumulate)
  1138. } else {
  1139. // 有时间,分段查询
  1140. // 新查询
  1141. if st != "" && ed != "" {
  1142. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  1143. pars = append(pars, st, ed, st, ed)
  1144. }
  1145. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(cond, pars)
  1146. if e != nil {
  1147. return
  1148. }
  1149. // 开票到款金额合计(换算后)
  1150. var amountTotal float64
  1151. var amountSum float64
  1152. if len(summaryIds) > 0 {
  1153. amountCond := `a.id IN ? `
  1154. amountPars := make([]interface{}, 0)
  1155. amountPars = append(amountPars, summaryIds)
  1156. //if req.SellerIds != "" {
  1157. // sellerIds := strings.Split(req.SellerIds, ",")
  1158. // amountCond += ` AND (( b.seller_id IN ? AND a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1159. // amountCond += `OR ( d.seller_id IN ? AND a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?)) `
  1160. // amountPars = append(amountPars, sellerIds, st, ed, sellerIds, st, ed)
  1161. //} else {
  1162. // amountCond += ` AND ((a.invoice_id <> 0 AND b.invoice_time BETWEEN ? AND ?)`
  1163. // amountCond += `OR (a.payment_id <> 0 AND a.invoice_id = 0 AND d.invoice_time BETWEEN ? AND ?))`
  1164. // amountPars = append(amountPars, st, ed, st, ed)
  1165. //}
  1166. results, e := fms.GetContractSummaryIncomeAmount(amountCond, amountPars)
  1167. if e != nil {
  1168. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1169. return
  1170. }
  1171. //dataList = append(dataList, results...)
  1172. for _, result := range results {
  1173. amountSum += result.Amount
  1174. fmt.Println("result.Amount:", result.Amount)
  1175. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1176. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1177. } else {
  1178. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1179. }
  1180. }
  1181. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1182. accumulate += amountTotal
  1183. amountSum = 0
  1184. //var amountTotal float64
  1185. // 旧查询
  1186. }
  1187. if st != "" && ed != "" {
  1188. histortyCond += ` AND (invoice_time BETWEEN ? AND ? )`
  1189. historyPars = append(historyPars, st, ed)
  1190. }
  1191. results, e := fms.GetIncomeHistory(histortyCond, historyPars)
  1192. if e != nil {
  1193. resp.FailMsg("查询错误", fmt.Sprintf("获取汇总数据失败, Err: %s", e.Error()), c)
  1194. return
  1195. }
  1196. //dataList = append(dataList, results...)
  1197. for _, result := range results {
  1198. amountSum += result.Amount
  1199. if _, ok := groupInvoiceMap[result.SellerGroupId]; ok {
  1200. groupInvoiceMap[result.SellerGroupId] += result.Amount
  1201. } else {
  1202. groupInvoiceMap[result.SellerGroupId] = result.Amount
  1203. }
  1204. }
  1205. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  1206. accumulate += amountTotal
  1207. }
  1208. fmt.Println("totalMoneySlice:", len(totalMoneySlice))
  1209. var departmentId int
  1210. if req.SellerType == 1 {
  1211. departmentId = crm.SellerDepartmentId
  1212. } else if req.SellerType == 2 {
  1213. departmentId = crm.RaiSellerDepartmentId
  1214. } else if req.SellerType == 0 {
  1215. resp.FailMsg("查询错误", "请选择正确的销售类型", c)
  1216. return
  1217. } else {
  1218. resp.FailMsg("查询错误", "请选择正确的销售类型", c)
  1219. return
  1220. }
  1221. groupCond := ` department_id = %d AND parent_id = 0 `
  1222. groupCond = fmt.Sprintf(groupCond, departmentId)
  1223. groupPars := make([]interface{}, 0)
  1224. groupOB := new(crm.SysGroup)
  1225. groupList, e := groupOB.List(groupCond, groupPars)
  1226. if e != nil {
  1227. resp.FailMsg("查询错误", fmt.Sprintf("获取组别列表失败, Err: %s", e.Error()), c)
  1228. return
  1229. }
  1230. //total := len(groupList)
  1231. groupMap := make(map[int]*crm.SysGroup)
  1232. for i := range groupList {
  1233. groupMap[groupList[i].GroupId] = groupList[i]
  1234. }
  1235. list := make([]*fms.CensusSellerGroupInvoiceItem, 0)
  1236. for _, group := range groupList {
  1237. if v, ok := groupInvoiceMap[group.GroupId]; ok {
  1238. rate := v / accumulate
  1239. mulNum := decimal.NewFromFloat(100)
  1240. newRate := decimal.NewFromFloat(rate)
  1241. newRate = newRate.Mul(mulNum).Round(2)
  1242. finalRate, _ := newRate.Float64()
  1243. amuont, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", v), 64)
  1244. groupName := ""
  1245. if groupItem, ok := groupMap[group.GroupId]; ok {
  1246. groupName = groupItem.GroupName
  1247. }
  1248. list = append(list, &fms.CensusSellerGroupInvoiceItem{
  1249. GroupId: group.GroupId,
  1250. GroupName: groupName,
  1251. InvoiceAmount: amuont,
  1252. GroupRate: finalRate,
  1253. })
  1254. }
  1255. }
  1256. sort.Slice(list, func(i, j int) bool {
  1257. if req.SortField == 2 {
  1258. if req.SortType == 2 {
  1259. return list[i].GroupRate < list[j].GroupRate
  1260. } else {
  1261. return list[i].GroupRate > list[j].GroupRate
  1262. }
  1263. } else {
  1264. if req.SortType == 2 {
  1265. return list[i].InvoiceAmount < list[j].InvoiceAmount
  1266. } else {
  1267. return list[i].InvoiceAmount > list[j].InvoiceAmount
  1268. }
  1269. }
  1270. })
  1271. //var respList fms.CensusSellerGroupList
  1272. //respList = list
  1273. //sort.Sort(respList)
  1274. // 是否导出
  1275. if req.IsExport == 1 {
  1276. ExportGroupInvoiceList(c, list, req)
  1277. return
  1278. }
  1279. resp.OkData("获取成功", list, c)
  1280. }