report.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. package home
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "math"
  7. "time"
  8. contDao "dashoo.cn/micro/app/dao/contract"
  9. platDao "dashoo.cn/micro/app/dao/plat"
  10. projDao "dashoo.cn/micro/app/dao/proj"
  11. "dashoo.cn/micro/app/model/home"
  12. "dashoo.cn/micro/app/model/plat"
  13. "dashoo.cn/micro/app/service"
  14. contractService "dashoo.cn/micro/app/service/contract"
  15. platService "dashoo.cn/micro/app/service/plat"
  16. projSrv "dashoo.cn/micro/app/service/proj"
  17. "dashoo.cn/opms_libary/micro_srv"
  18. "dashoo.cn/opms_libary/myerrors"
  19. "github.com/gogf/gf/database/gdb"
  20. "github.com/gogf/gf/frame/g"
  21. "github.com/gogf/gf/os/gtime"
  22. "github.com/gogf/gf/util/gconv"
  23. )
  24. // getPersonalContractReportData 获取个人数据
  25. // dataType:collection为回款;其他为合同
  26. func getPersonalContractReportData(ctx context.Context, dataType string, params *map[string]interface{}) (*home.ReportData, error) {
  27. var reportData home.ReportData
  28. targetMap := make(map[int]gdb.Record, 0)
  29. realMap := make(map[int][]*gdb.Record, 0)
  30. targetField := "sales_target"
  31. realField := "contract_amount"
  32. year := gtime.Now().Format("Y")
  33. if params != nil && (*params)["year"] != nil {
  34. year = gconv.String((*params)["year"])
  35. }
  36. // 统计字段
  37. if dataType == "COLLECTION" {
  38. targetField = "collection_target"
  39. realField = "collection_amount"
  40. }
  41. srv, err := contractService.NewCtrContractService(ctx)
  42. if err != nil {
  43. return nil, err
  44. }
  45. // 获取用户信息
  46. userInfo, err := micro_srv.GetUserInfo(ctx)
  47. if err != nil {
  48. return nil, fmt.Errorf("获取用户信息异常:%s", err.Error())
  49. }
  50. targets, err := srv.Dao.DB.Model("rpt_sales_target").Where("sale_user_id", userInfo.Id).Order("monthly ASC").FindAll()
  51. if err != nil && err != sql.ErrNoRows {
  52. return nil, err
  53. }
  54. for index, target := range targets {
  55. targetMap[target["monthly"].Int()] = targets[index]
  56. }
  57. // 统计12个月份的数据
  58. // 统计目标值
  59. for index := 1; index <= 12; index++ {
  60. reportData.XData = append(reportData.XData, fmt.Sprintf("%v月", index))
  61. if target, ok := targetMap[index]; ok {
  62. reportData.YDataTarget = append(reportData.YDataTarget, target[targetField].Float64())
  63. } else {
  64. reportData.YDataTarget = append(reportData.YDataTarget, 0)
  65. }
  66. }
  67. // 统计合同值
  68. contractModel := srv.Dao.DB.Model("ctr_contract").Where("ctr_contract.incharge_id", userInfo.Id)
  69. if dataType != "COLLECTION" {
  70. contracts, err := contractModel.Where("ctr_contract.contract_start_time LIKE ?", year+"-%").Order("ctr_contract.contract_start_time ASC").FindAll()
  71. if err != nil && err != sql.ErrNoRows {
  72. return nil, err
  73. }
  74. for index, contract := range contracts {
  75. realMap[contract["contract_start_time"].GTime().Month()] = append(realMap[contract["contract_start_time"].GTime().Month()], &contracts[index])
  76. }
  77. } else {
  78. // 回款数据统计
  79. collections, err := contractModel.InnerJoin("ctr_contract_collection", "ctr_contract.id=ctr_contract_collection.contract_id").Where("ctr_contract_collection.appro_status", "20").Where("ctr_contract_collection.collection_datetime LIKE ?", year+"-%").Order("ctr_contract_collection.collection_datetime ASC").Fields("ctr_contract_collection.*").FindAll()
  80. if err != nil && err != sql.ErrNoRows {
  81. return nil, err
  82. }
  83. for index, collection := range collections {
  84. realMap[collection["collection_datetime"].GTime().Month()] = append(realMap[collection["collection_datetime"].GTime().Month()], &collections[index])
  85. }
  86. }
  87. // 统计12个月份的数据
  88. // 统计实际值
  89. for index := 1; index <= 12; index++ {
  90. if realData, ok := realMap[index]; ok {
  91. realAmount := float64(0)
  92. for _, data := range realData {
  93. realAmount += (*data)[realField].Float64()
  94. }
  95. reportData.YDataReal = append(reportData.YDataReal, realAmount)
  96. } else {
  97. reportData.YDataReal = append(reportData.YDataReal, 0)
  98. }
  99. if reportData.YDataTarget[index-1] == 0 {
  100. reportData.PercentData = append(reportData.PercentData, 0)
  101. } else {
  102. reportData.PercentData = append(reportData.PercentData, reportData.YDataReal[index-1]*100/reportData.YDataTarget[index-1])
  103. }
  104. }
  105. return &reportData, nil
  106. }
  107. // getCompanyContractReportData 获取总部数据
  108. // dataType:collection为回款;其他为合同
  109. func getCompanyContractReportData(ctx context.Context, dataType string, params *map[string]interface{}) (*home.ReportData, error) {
  110. var reportData home.ReportData
  111. realMap := make(map[int]gdb.Record, 0)
  112. targetField := "sales_target"
  113. realField := "contract_amount"
  114. dateWhere1 := "" // 查询条件
  115. dateWhere2 := "" // 查询条件
  116. dateWhere3 := ""
  117. date := gtime.Now()
  118. if params != nil && (*params)["date"] != nil {
  119. date = gconv.GTime((*params)["date"])
  120. }
  121. dateWhere1 = fmt.Sprintf("ctr_contract.contract_start_time LIKE '%v'", date.Format("Y")+"-%")
  122. dateWhere2 = fmt.Sprintf("ctr_contract_collection.collection_datetime LIKE '%v'", date.Format("Y")+"-%")
  123. if params != nil && (*params)["searchType"] != nil {
  124. searchType := gconv.String((*params)["searchType"])
  125. if searchType == "month" {
  126. dateWhere1 = fmt.Sprintf("ctr_contract.contract_start_time LIKE '%v'", date.Format("Y-m")+"-%")
  127. dateWhere2 = fmt.Sprintf("ctr_contract_collection.collection_datetime LIKE '%v'", date.Format("Y-m")+"-%")
  128. dateWhere3 = fmt.Sprintf("monthly=%v", date.Month())
  129. } else if searchType == "quarter" {
  130. dateWhere1 = getQuarterWhere(date, "ctr_contract.contract_start_time")
  131. dateWhere2 = getQuarterWhere(date, "ctr_contract_collection.collection_datetime")
  132. dateWhere3 = getQuarterMonthWhere(date, "monthly")
  133. }
  134. }
  135. // 统计字段
  136. if dataType == "COLLECTION" {
  137. targetField = "collection_target"
  138. realField = "collection_amount"
  139. }
  140. srv, err := contractService.NewCtrContractService(ctx)
  141. if err != nil {
  142. return nil, err
  143. }
  144. targets, err := srv.Dao.DB.Model("rpt_sales_target").Where(dateWhere3).Order("sale_user_id ASC").Group("sale_user_id").Fields(fmt.Sprintf("sale_user_id, sale_user_name, SUM(%v) %v", targetField, targetField)).FindAll()
  145. if err != nil && err != sql.ErrNoRows {
  146. return nil, err
  147. }
  148. // 统计合同值
  149. contractModel := srv.Dao.DB.Model("ctr_contract").Group("ctr_contract.incharge_id").Order("ctr_contract.incharge_id ASC")
  150. if dataType != "COLLECTION" {
  151. contracts, err := contractModel.Where(dateWhere1).Fields("ctr_contract.incharge_id, ctr_contract.incharge_name, count(ctr_contract.contract_amount) contract_amount").FindAll()
  152. if err != nil && err != sql.ErrNoRows {
  153. return nil, err
  154. }
  155. for index, contract := range contracts {
  156. realMap[contract["incharge_id"].Int()] = contracts[index]
  157. }
  158. } else {
  159. // 回款数据统计
  160. collections, err := contractModel.InnerJoin("ctr_contract_collection", "ctr_contract.id=ctr_contract_collection.contract_id").Where("ctr_contract_collection.appro_status", "20").Where(dateWhere2).Fields("ctr_contract.incharge_id, ctr_contract.incharge_name, SUM(ctr_contract_collection.collection_amount) collection_amount").FindAll()
  161. if err != nil && err != sql.ErrNoRows {
  162. return nil, err
  163. }
  164. for index, collection := range collections {
  165. realMap[collection["incharge_id"].Int()] = collections[index]
  166. }
  167. }
  168. // 过滤掉已删除的销售
  169. normalUserMap := make(map[int]bool)
  170. normalUsers, err := srv.Dao.DB.Model("sys_user").Where("status='10'").FindAll()
  171. if err != nil && err != sql.ErrNoRows {
  172. return nil, err
  173. }
  174. for _, user := range normalUsers {
  175. normalUserMap[user["id"].Int()] = true
  176. }
  177. // 统计目标值和实际值
  178. for index, target := range targets {
  179. // 过滤掉已删除的销售
  180. if !normalUserMap[target["sale_user_id"].Int()] {
  181. continue
  182. }
  183. reportData.XData = append(reportData.XData, target["sale_user_name"].String())
  184. reportData.YDataTarget = append(reportData.YDataTarget, target[targetField].Float64())
  185. if realData, ok := realMap[target["sale_user_id"].Int()]; ok {
  186. reportData.YDataReal = append(reportData.YDataReal, realData[realField].Float64())
  187. } else {
  188. reportData.YDataReal = append(reportData.YDataReal, 0)
  189. }
  190. if reportData.YDataTarget[index] == 0 {
  191. reportData.PercentData = append(reportData.PercentData, 0)
  192. } else {
  193. reportData.PercentData = append(reportData.PercentData, reportData.YDataReal[index]*100/reportData.YDataTarget[index])
  194. }
  195. }
  196. return &reportData, nil
  197. }
  198. func getQuarterGoalReportData(ctx context.Context, dataType string, params *map[string]interface{}) (*home.ReportData, error) {
  199. if params == nil {
  200. return nil, fmt.Errorf("请输入年度")
  201. }
  202. p := *params
  203. year := gconv.Int(p["year"])
  204. quarter := gconv.Int(p["quarter"])
  205. if year == 0 {
  206. return nil, fmt.Errorf("请输入年度")
  207. }
  208. srv, err := contractService.NewCtrContractService(ctx)
  209. if err != nil {
  210. return nil, err
  211. }
  212. goal := map[string]float64{}
  213. goaldao := srv.GoalDao.Where("year = ?", year).Where("goal_type = ?", dataType)
  214. if quarter != 0 {
  215. goaldao = goaldao.Where("quarter = ?", quarter)
  216. } else {
  217. goaldao = goaldao.Where("quarter = 1 || quarter = 2 || quarter = 3 || quarter = 4")
  218. }
  219. goalent, err := goaldao.All()
  220. if err != nil {
  221. return nil, err
  222. }
  223. for _, ent := range goalent {
  224. goal[ent.ProductLine] += ent.Amount
  225. }
  226. got := map[string]float64{}
  227. ctrdao := srv.Dao.As("a").InnerJoin("sys_user b", "a.incharge_id=b.id").Where("b.status='10'").Where("year(a.created_time) = ?", year)
  228. if quarter != 0 {
  229. if quarter == 1 {
  230. ctrdao = ctrdao.Where("month(a.created_time) in (1,2,3)")
  231. }
  232. if quarter == 2 {
  233. ctrdao = ctrdao.Where("month(a.created_time) in (4,5,6)")
  234. }
  235. if quarter == 3 {
  236. ctrdao = ctrdao.Where("month(a.created_time) in (7,8,9)")
  237. }
  238. if quarter == 4 {
  239. ctrdao = ctrdao.Where("month(a.created_time) in (10,11,12)")
  240. }
  241. }
  242. ctrent, err := ctrdao.All()
  243. if err != nil {
  244. return nil, err
  245. }
  246. for _, ent := range ctrent {
  247. if dataType == "10" {
  248. got[ent.ProductLine] += ent.ContractAmount
  249. }
  250. if dataType == "20" {
  251. got[ent.ProductLine] += ent.CollectedAmount
  252. }
  253. }
  254. productLine, err := service.GetDictDataByType(ctx, "sys_product_line")
  255. if err != nil {
  256. return nil, err
  257. }
  258. productLineCode := []string{}
  259. productLineName := []string{}
  260. for k, v := range productLine {
  261. productLineCode = append(productLineCode, k)
  262. productLineName = append(productLineName, v)
  263. }
  264. var reportData home.ReportData
  265. for _, c := range productLineCode {
  266. reportData.XData = append(reportData.XData, productLine[c])
  267. reportData.YDataTarget = append(reportData.YDataTarget, goal[c])
  268. reportData.YDataReal = append(reportData.YDataReal, got[c]/10000)
  269. }
  270. return &reportData, nil
  271. }
  272. // 客户现场打卡频次
  273. func getClockfrequency(ctx context.Context, dataType string, params *map[string]interface{}) (*home.ReportData, error) {
  274. var reportData home.ReportData
  275. realMap := make(map[int]gdb.Record, 0)
  276. dateWhere1 := "" // 查询条件
  277. date := gtime.Now()
  278. nowTime := gtime.Datetime()
  279. if params != nil && (*params)["date"] != nil {
  280. date = gconv.GTime((*params)["date"])
  281. }
  282. if params != nil && (*params)["searchType"] != nil {
  283. searchType := gconv.String((*params)["searchType"])
  284. if searchType == "month" {
  285. dateWhere1 = fmt.Sprintf("plat_punch_records.punch_time LIKE '%v'", date.Format("Y-m")+"-%")
  286. } else if searchType == "week" {
  287. weekday := transferWeekday(date.Weekday())
  288. fmt.Println(weekday)
  289. beforeTime := gtime.NewFromStr(nowTime).AddDate(0, 0, -gconv.Int(weekday)).String()
  290. endTime := gtime.NewFromStr(nowTime).AddDate(0, 0, 7-gconv.Int(weekday)).String()
  291. dateWhere1 = fmt.Sprintf("plat_punch_records.punch_time between '%v' and '%v'", beforeTime, endTime)
  292. }
  293. }
  294. srv, err := platService.NewPunchRecordsService(ctx)
  295. if err != nil {
  296. return nil, err
  297. }
  298. platpunchrecords, err := srv.Dao.DB.Model("plat_punch_records").Where(dateWhere1).Fields("plat_punch_records.user_nick_name,Count(plat_punch_records.user_nick_name) as punch_sum").Group("plat_punch_records.user_nick_name").FindAll()
  299. if err != nil && err != sql.ErrNoRows {
  300. return nil, err
  301. }
  302. // 过滤掉已删除的销售
  303. normalUserMap := make(map[int]bool)
  304. normalUsers, err := srv.Dao.DB.Model("sys_user").Where("status='10'").FindAll()
  305. if err != nil && err != sql.ErrNoRows {
  306. return nil, err
  307. }
  308. for _, user := range normalUsers {
  309. normalUserMap[user["id"].Int()] = true
  310. }
  311. // 赋值实际值
  312. for index, target := range platpunchrecords {
  313. // 过滤掉已删除的销售
  314. if !normalUserMap[target["user_id"].Int()] {
  315. continue
  316. }
  317. reportData.XData = append(reportData.XData, target["user_nick_name"].String())
  318. reportData.YDataTarget = append(reportData.YDataTarget, target["punch_sum"].Float64())
  319. if realData, ok := realMap[target["punch_sum"].Int()]; ok {
  320. reportData.YDataReal = append(reportData.YDataReal, realData["punch_sum"].Float64())
  321. } else {
  322. reportData.YDataReal = append(reportData.YDataReal, 0)
  323. }
  324. if reportData.YDataTarget[index] == 0 {
  325. reportData.PercentData = append(reportData.PercentData, 0)
  326. } else {
  327. reportData.PercentData = append(reportData.PercentData, reportData.YDataReal[index]*100/reportData.YDataTarget[index])
  328. }
  329. }
  330. return &reportData, nil
  331. }
  332. // 销售工程师跟进记录的打卡频次
  333. func getFollowUpRecord(ctx context.Context, dataType string, params *map[string]interface{}) ([]plat.Statistics, error) {
  334. now := time.Now()
  335. date := gconv.Int(gtime.Now().Month())
  336. if params != nil && (*params)["date"] != nil {
  337. date = gconv.Int((*params)["date"])
  338. }
  339. // 获取本月的第一天
  340. firstOfMonth := time.Date(now.Year(), time.Month(date), 1, 0, 0, 0, 0, now.Location())
  341. // 获取本月的最后一天
  342. lastOfMonth := firstOfMonth.AddDate(0, 1, -1)
  343. l, _ := time.LoadLocation("Asia/Shanghai")
  344. startTime, _ := time.ParseInLocation("2006-01-02", firstOfMonth.Format("2006-01-02"), l)
  345. endTime, _ := time.ParseInLocation("2006-01-02", lastOfMonth.Format("2006-01-02"), l)
  346. datas := GroupByWeekDate(startTime, endTime)
  347. var Follows []plat.Followlist
  348. srv, err := platService.NewFollowupService(ctx)
  349. if err != nil {
  350. return nil, err
  351. }
  352. var stats []plat.Statistics
  353. for _, d := range datas {
  354. err = srv.Dao.DB.Model("plat_followup").
  355. Where("follow_date>=? and follow_date<=?", d.StartTime.Format("2006-01-02"), d.EndTime.Format("2006-01-02")).Fields("count(follow_type)as num ,follow_type").
  356. Group("date_format(follow_date,'%v'),follow_type").Scan(&Follows)
  357. if err != nil && err != sql.ErrNoRows {
  358. return nil, err
  359. }
  360. if len(Follows) > 0 {
  361. var stat plat.Statistics
  362. for _, val := range Follows {
  363. if val.FollowType == "10" {
  364. stat.Phone = gconv.Int(val.Num)
  365. } else if val.FollowType == "20" {
  366. stat.Mail = gconv.Int(val.Num)
  367. } else if val.FollowType == "30" {
  368. stat.PayVisit = gconv.Int(val.Num)
  369. }
  370. }
  371. stat.Total = stat.Phone + stat.Mail + stat.PayVisit
  372. stat.Week = d.WeekTh + "周"
  373. stats = append(stats, stat)
  374. }
  375. }
  376. return stats, nil
  377. }
  378. func getQuarterWhere(date *gtime.Time, field string) string {
  379. if date.Month() >= 1 && date.Month() <= 3 {
  380. return fmt.Sprintf("%v >= '%v' AND %v < '%v'", field, date.Format("Y-")+"01-01 00:00:00", field, date.Format("Y-")+"04-01 00:00:00")
  381. } else if date.Month() >= 4 && date.Month() <= 6 {
  382. return fmt.Sprintf("%v >= '%v' AND %v < '%v'", field, date.Format("Y-")+"04-01 00:00:00", field, date.Format("Y-")+"07-01 00:00:00")
  383. } else if date.Month() >= 7 && date.Month() <= 9 {
  384. return fmt.Sprintf("%v >= '%v' AND %v < '%v'", field, date.Format("Y-")+"07-01 00:00:00", field, date.Format("Y-")+"10-01 00:00:00")
  385. } else if date.Month() >= 10 && date.Month() <= 12 {
  386. return fmt.Sprintf("%v >= '%v' AND %v <= '%v'", field, date.Format("Y-")+"10-01 00:00:00", field, date.Format("Y-")+"12-31 23:59:59")
  387. }
  388. return ""
  389. }
  390. func getQuarterMonthWhere(date *gtime.Time, field string) string {
  391. if date.Month() >= 1 && date.Month() <= 3 {
  392. return fmt.Sprintf("%v >= %v AND %v < %v", field, 1, field, 4)
  393. } else if date.Month() >= 4 && date.Month() <= 6 {
  394. return fmt.Sprintf("%v >= %v AND %v < %v", field, 4, field, 7)
  395. } else if date.Month() >= 7 && date.Month() <= 9 {
  396. return fmt.Sprintf("%v >= %v AND %v < %v", field, 7, field, 10)
  397. } else if date.Month() >= 10 && date.Month() <= 12 {
  398. return fmt.Sprintf("%v >= %v AND %v <= %v", field, 10, field, 12)
  399. }
  400. return ""
  401. }
  402. func transferWeekday(day time.Weekday) string {
  403. switch day {
  404. case time.Monday:
  405. return "1"
  406. case time.Tuesday:
  407. return "2"
  408. case time.Wednesday:
  409. return "3"
  410. case time.Thursday:
  411. return "4"
  412. case time.Friday:
  413. return "5"
  414. case time.Saturday:
  415. return "6"
  416. case time.Sunday:
  417. return "7"
  418. default:
  419. return ""
  420. }
  421. }
  422. // 判断时间是当年的第几周
  423. func WeekByDate(t time.Time) string {
  424. yearDay := t.YearDay()
  425. yearFirstDay := t.AddDate(0, 0, -yearDay+1)
  426. firstDayInWeek := int(yearFirstDay.Weekday())
  427. //今年第一周有几天
  428. firstWeekDays := 1
  429. if firstDayInWeek != 0 {
  430. firstWeekDays = 7 - firstDayInWeek + 1
  431. }
  432. var week int
  433. Weeks := WeekByDates(t)
  434. if yearDay <= firstWeekDays {
  435. week = 1
  436. } else {
  437. week = (yearDay-firstWeekDays)/7 + 2
  438. }
  439. return fmt.Sprintf("%d", week-gconv.Int(Weeks)+1)
  440. }
  441. func WeekByDates(now time.Time) int {
  442. l, _ := time.LoadLocation("Asia/Shanghai")
  443. // 获取本月的第一天
  444. firstOfMonth := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
  445. endTime, _ := time.ParseInLocation("2006-01-02", firstOfMonth.Format("2006-01-02"), l)
  446. t := endTime
  447. yearDay := t.YearDay()
  448. yearFirstDay := t.AddDate(0, 0, -yearDay+1)
  449. firstDayInWeek := int(yearFirstDay.Weekday())
  450. //今年第一周有几天
  451. firstWeekDays := 1
  452. if firstDayInWeek != 0 {
  453. firstWeekDays = 7 - firstDayInWeek + 1
  454. }
  455. var week int
  456. if yearDay <= firstWeekDays {
  457. week = 1
  458. } else {
  459. week = (yearDay-firstWeekDays)/7 + 2
  460. }
  461. return week
  462. }
  463. // 将开始时间和结束时间分割为周为单位
  464. func GroupByWeekDate(startTime, endTime time.Time) []plat.WeekDate {
  465. weekDate := make([]plat.WeekDate, 0)
  466. diffDuration := endTime.Sub(startTime)
  467. days := int(math.Ceil(float64(diffDuration/(time.Hour*24)))) + 1
  468. currentWeekDate := plat.WeekDate{}
  469. currentWeekDate.WeekTh = WeekByDate(endTime)
  470. currentWeekDate.EndTime = endTime
  471. currentWeekDay := int(endTime.Weekday())
  472. if currentWeekDay == 0 {
  473. currentWeekDay = 7
  474. }
  475. currentWeekDate.StartTime = endTime.AddDate(0, 0, -currentWeekDay+1)
  476. nextWeekEndTime := currentWeekDate.StartTime
  477. weekDate = append(weekDate, currentWeekDate)
  478. for i := 0; i < (days-currentWeekDay)/7; i++ {
  479. weekData := plat.WeekDate{}
  480. weekData.EndTime = nextWeekEndTime
  481. weekData.StartTime = nextWeekEndTime.AddDate(0, 0, -7)
  482. weekData.WeekTh = WeekByDate(weekData.StartTime)
  483. nextWeekEndTime = weekData.StartTime
  484. weekDate = append(weekDate, weekData)
  485. }
  486. if lastDays := (days - currentWeekDay) % 7; lastDays > 0 {
  487. lastData := plat.WeekDate{}
  488. lastData.EndTime = nextWeekEndTime
  489. lastData.StartTime = nextWeekEndTime.AddDate(0, 0, -lastDays)
  490. lastData.WeekTh = WeekByDate(lastData.StartTime)
  491. weekDate = append(weekDate, lastData)
  492. }
  493. return weekDate
  494. }
  495. type BusCount struct {
  496. NboType string `json:"nboType"`
  497. ProductLine string `json:"productLine"`
  498. Count int `json:"count"`
  499. Remark string `json:"remark"`
  500. }
  501. // 报表数据 三大产品线,新增以及转化项目(C转B、B转A、A转签约、C转A、C转签约、B转签约、储备转A/B/C/签约)数量, 按周和月
  502. // params 10:周 20:月
  503. func (s *HomeService) getNewAndConvertBusiness(productLine []string, params *map[string]interface{}) (interface{}, error) {
  504. if params == nil {
  505. return nil, myerrors.TipsError("请求参数传递不正确")
  506. }
  507. searchType, ok := (*params)["searchType"]
  508. if !ok {
  509. return nil, myerrors.TipsError("请求查询类型参数传递错误")
  510. }
  511. currentTime := gtime.Now()
  512. weekStart, weekEnd := currentTime.StartOfWeek(), currentTime.EndOfWeek()
  513. // monthStart, monthEnd := currentTime.StartOfMonth(), currentTime.EndOfMonth()
  514. monthStr, ok := (*params)["month"]
  515. if !ok {
  516. return nil, myerrors.TipsError("请求查询类型参数传递错误")
  517. }
  518. m := gconv.Int(monthStr)
  519. now := time.Now()
  520. firstOfMonth := time.Date(now.Year(), time.Month(m), 1, 0, 0, 0, 0, now.Location()) // 获取本月的第一天
  521. lastOfMonth := firstOfMonth.AddDate(0, 1, -1) // 获取本月的最后一天
  522. l, _ := time.LoadLocation("Asia/Shanghai")
  523. startTime, _ := time.ParseInLocation("2006-01-02", firstOfMonth.Format("2006-01-02"), l)
  524. endTime, _ := time.ParseInLocation("2006-01-02", lastOfMonth.Format("2006-01-02"), l)
  525. businessDao := projDao.NewProjBusinessDao(s.Tenant)
  526. busDynamicsDao := projDao.NewProjBusinessDynamicsDao(s.Tenant)
  527. contractDao := contDao.NewCtrContractDao(s.Tenant)
  528. // 获取三大产品线新增项目
  529. getAddBusCount := func(searchType string) (addCount []BusCount, err error) {
  530. commonDb := businessDao.DataScope(s.Ctx, "sale_id").Group(businessDao.C.ProductLine).OrderAsc(businessDao.C.ProductLine).
  531. Fields("product_line, count(id) as count")
  532. if searchType == "week" {
  533. err = commonDb.WhereGTE(businessDao.C.FilingTime, weekStart).WhereLTE(businessDao.C.FilingTime, weekEnd).Scan(&addCount)
  534. }
  535. if searchType == "month" {
  536. err = commonDb.WhereGTE(businessDao.C.FilingTime, startTime).WhereLTE(businessDao.C.FilingTime, endTime).Scan(&addCount)
  537. }
  538. return addCount, err
  539. }
  540. addCount, err := getAddBusCount(searchType.(string))
  541. if err != nil {
  542. return nil, err
  543. }
  544. // 获取三大产品线签约项目
  545. getSignBusCount := func(searchType string) (signCount []BusCount, err error) {
  546. commonDb := contractDao.As("contract").DataScope(s.Ctx, "incharge_id").LeftJoin(businessDao.Table, "bus", "bus.id=contract.nbo_id").
  547. Fields("bus.product_line, bus.nbo_type, count(contract.id) as count").
  548. Group("bus.product_line, bus.nbo_type").Order("bus.product_line ASC, bus.nbo_type ASC")
  549. if searchType == "week" {
  550. err = commonDb.WhereGTE("contract."+contractDao.C.CreatedTime, weekStart).WhereLTE("contract."+contractDao.C.CreatedTime, weekEnd).Scan(&signCount)
  551. }
  552. if searchType == "month" {
  553. err = commonDb.WhereGTE("contract."+contractDao.C.CreatedTime, startTime).WhereLTE("contract."+contractDao.C.CreatedTime, endTime).Scan(&signCount)
  554. }
  555. return signCount, err
  556. }
  557. signCount, err := getSignBusCount(searchType.(string))
  558. if err != nil {
  559. return nil, err
  560. }
  561. // 获取三大产品线转化项目(C转B、B转A、A转签约、C转A、C转签约、B转签约、储备转A/B/C/签约)数量
  562. getConvertBusData := func(searchType string) (convertData []BusCount, err error) {
  563. commonDb := busDynamicsDao.As("dy").LeftJoin(businessDao.Table, "bus", "bus.id=dy.bus_id").DataScope(s.Ctx, "sale_id", "bus").
  564. Where("dy."+busDynamicsDao.C.OpnType, projSrv.OpnUpgradeApproval).WhereNot("dy."+busDynamicsDao.C.Remark, "").
  565. Fields("bus.product_line, dy.remark").OrderAsc("bus.product_line")
  566. if searchType == "week" {
  567. err = commonDb.WhereGTE("dy."+busDynamicsDao.C.CreatedTime, weekStart).WhereLTE("dy."+busDynamicsDao.C.CreatedTime, weekEnd).Scan(&convertData)
  568. }
  569. if searchType == "month" {
  570. err = commonDb.WhereGTE("dy."+busDynamicsDao.C.CreatedTime, startTime).WhereLTE("dy."+busDynamicsDao.C.CreatedTime, endTime).Scan(&convertData)
  571. }
  572. return convertData, err
  573. }
  574. convertBusData, err := getConvertBusData(searchType.(string))
  575. if err != nil {
  576. return nil, err
  577. }
  578. // 处理数据
  579. result := make([][]int, len(productLine))
  580. for i, pl := range productLine {
  581. result[i] = make([]int, 8)
  582. for _, item := range addCount {
  583. if item.ProductLine == pl {
  584. result[i][0] = item.Count
  585. }
  586. }
  587. for _, item := range signCount {
  588. if item.ProductLine != pl {
  589. continue
  590. }
  591. switch item.NboType {
  592. case projSrv.StatusA:
  593. result[i][3] += item.Count
  594. case projSrv.StatusB:
  595. result[i][6] += item.Count
  596. case projSrv.StatusC:
  597. result[i][5] += item.Count
  598. case projSrv.StatusReserve:
  599. result[i][7] += item.Count
  600. }
  601. }
  602. for _, item := range convertBusData {
  603. if item.ProductLine != pl {
  604. continue
  605. }
  606. info := gconv.Map(item.Remark)
  607. if info["origNboType"] == projSrv.StatusC && info["nboType"] == projSrv.StatusB {
  608. result[i][1] += 1
  609. }
  610. if info["origNboType"] == projSrv.StatusB && info["nboType"] == projSrv.StatusA {
  611. result[i][2] += 1
  612. }
  613. if info["origNboType"] == projSrv.StatusC && info["nboType"] == projSrv.StatusA {
  614. result[i][4] += 1
  615. }
  616. if info["origNboType"] == projSrv.StatusReserve {
  617. result[i][7] += 1
  618. }
  619. }
  620. }
  621. return result, nil
  622. }
  623. // 报表数据 三大产品线,AB类项目出货金额
  624. func (s *HomeService) getShipmentAmount(productLine, nboType []string) (interface{}, error) {
  625. businessDao := projDao.NewProjBusinessDao(s.Tenant)
  626. data, err := businessDao.As("a").InnerJoin("sys_user b", "a.sale_id=b.id").Fields("a.product_line, a.nbo_type, SUM(a.est_trans_price) as est_trans_price").Where("b.status='10'").
  627. WhereIn("a.product_line", productLine).WhereIn("a.nbo_type", nboType).
  628. Group("a.product_line, a.nbo_type").Order("a.product_line ASC, a.nbo_type ASC").DataScope(s.Ctx, "a.sale_id").All()
  629. if err != nil {
  630. return nil, err
  631. }
  632. result := make([][]float64, len(productLine))
  633. for i, pl := range productLine {
  634. result[i] = make([]float64, len(nboType))
  635. for j, t := range nboType {
  636. for _, item := range data {
  637. if item.ProductLine == pl && item.NboType == t {
  638. result[i][j] = item.EstTransPrice
  639. }
  640. }
  641. }
  642. }
  643. return arrayReversal(result), nil
  644. }
  645. // 报表数据 三大产品线,当月和累计的签约、回款额
  646. func (s *HomeService) getProductLineSignedAndBackAmount(productLine []string) (interface{}, error) {
  647. currentTime := gtime.Now()
  648. monthStart := currentTime.StartOfMonth()
  649. monthEnd := currentTime.EndOfMonth()
  650. contractDao := contDao.NewCtrContractDao(s.Tenant)
  651. commonDao := contractDao.As("a").InnerJoin("sys_user b", "a.incharge_id=b.id").DataScope(s.Ctx, "incharge_id").WhereIn(contractDao.C.ProductLine, productLine).Where("b.status='10'").
  652. Group(contractDao.C.ProductLine).OrderAsc(contractDao.C.ProductLine)
  653. //累计签约合同金额 contract_amount
  654. allContractAmount, err := commonDao.Fields("a.product_line, SUM(a.contract_amount) as contract_amount").All()
  655. if err != nil {
  656. return nil, err
  657. }
  658. //累计回款金额 collected_amount
  659. allCollectedAmount, err := commonDao.Fields("a.product_line, SUM(a.collected_amount) as collected_amount").All()
  660. if err != nil {
  661. return nil, err
  662. }
  663. //当月签约合同金额(维度:月)
  664. monthContractAmount, err := commonDao.WhereGTE(contractDao.C.ContractStartTime, monthStart).WhereLTE(contractDao.C.ContractStartTime, monthEnd).
  665. Fields("a.product_line, SUM(a.contract_amount) as contract_amount").All()
  666. if err != nil {
  667. return nil, err
  668. }
  669. //当月回款金额(维度:月)
  670. monthCollectedAmount, err := commonDao.WhereGTE(contractDao.C.ContractStartTime, monthStart).WhereLTE(contractDao.C.ContractStartTime, monthEnd).
  671. Fields("a.product_line, SUM(a.collected_amount) as collected_amount").All()
  672. if err != nil {
  673. return nil, err
  674. }
  675. result := make([][]float64, len(productLine))
  676. for i, pl := range productLine {
  677. result[i] = make([]float64, 4)
  678. for _, item := range monthContractAmount {
  679. if item.ProductLine == pl {
  680. result[i][0] = item.ContractAmount
  681. }
  682. }
  683. for _, item := range allContractAmount {
  684. if item.ProductLine == pl {
  685. result[i][1] = item.ContractAmount
  686. }
  687. }
  688. for _, item := range monthCollectedAmount {
  689. if item.ProductLine == pl {
  690. result[i][2] = item.CollectedAmount
  691. }
  692. }
  693. for _, item := range allCollectedAmount {
  694. if item.ProductLine == pl {
  695. result[i][3] = item.CollectedAmount
  696. }
  697. }
  698. }
  699. return arrayReversal(result), nil
  700. }
  701. // 二维数组反转
  702. func arrayReversal(result [][]float64) [][]float64 {
  703. if len(result) == 0 {
  704. return [][]float64{}
  705. }
  706. data := make([][]float64, len(result[0]))
  707. for k, v := range result {
  708. for m, n := range v {
  709. if k == 0 {
  710. data[m] = make([]float64, len(result))
  711. }
  712. data[m][k] = n
  713. }
  714. }
  715. return data
  716. }
  717. type FollowUpCount struct {
  718. CreatedBy int `json:"createdBy"`
  719. CreatedName string `json:"createdName"`
  720. FollowType string `json:"followType"`
  721. Count int `json:"count"`
  722. }
  723. // QuerySalesEngineerFollowUpNum 查询销售工程师跟进记录频次
  724. func (s *HomeService) QuerySalesEngineerFollowUpNum(day *gtime.Time) (interface{}, error) {
  725. weekData := GetMonthWeekDay(day)
  726. followUpDao := platDao.NewPlatFollowupDao(s.Tenant)
  727. followUpMonthData := make([][]FollowUpCount, 0)
  728. for _, item := range weekData {
  729. data := make([]FollowUpCount, 0)
  730. err := followUpDao.Fields("created_by, created_name, follow_type, COUNT(id) as count").
  731. WhereGTE(followUpDao.C.FollowDate, item[0]).WhereLTE(followUpDao.C.FollowDate, item[1]).
  732. Group("created_by, follow_type").Order("created_by ASC, follow_type ASC").Scan(&data)
  733. if err != nil {
  734. return nil, err
  735. }
  736. followUpMonthData = append(followUpMonthData, data)
  737. }
  738. // 409022238
  739. userList, err := service.GetUsersByRoleCode(s.Ctx, []string{"SalesEngineer"}, 100)
  740. if err != nil {
  741. return nil, err
  742. }
  743. followMethod, err := service.GetDictDataTreeByType(s.Ctx, "plat_follow_method")
  744. if err != nil {
  745. return nil, err
  746. }
  747. header, data := make([]g.Map, 0), make([]g.Map, 0)
  748. header = append(header, g.Map{"prop": "userName", "label": "销售工程师"})
  749. header = append(header, g.Map{"prop": "followType", "label": "跟进方式"})
  750. for k, _ := range weekData {
  751. header = append(header, g.Map{"prop": fmt.Sprintf("W%d", k+1), "label": fmt.Sprintf("第%d周", k+1)})
  752. }
  753. header = append(header, g.Map{"prop": "monthTotal", "label": "月度合计"})
  754. for userName, id := range userList {
  755. for _, key := range followMethod.Keys() {
  756. data = append(data, followUpReportDataConvert(g.Map{
  757. "userName": userName,
  758. "userId": id,
  759. "followTypeKey": key,
  760. "followType": followMethod.Get(key),
  761. }, followUpMonthData))
  762. }
  763. }
  764. return g.Map{"header": header, "data": data}, nil
  765. }
  766. type PunchRecordsCount struct {
  767. UserId int `json:"userId"`
  768. UserNickName string `json:"userNickName"`
  769. PunchType string `json:"punchType"`
  770. Count int `json:"count"`
  771. }
  772. // QueryPunchRecordsNum 打卡记录数据统计
  773. func (s *HomeService) QueryPunchRecordsNum(day *gtime.Time) (interface{}, error) {
  774. weekData := GetMonthWeekDay(day)
  775. punchRecordsDao := platDao.NewPlatPunchRecordsDao(s.Tenant)
  776. punchRecordsMonthData := make([][]PunchRecordsCount, 0)
  777. for _, item := range weekData {
  778. data := make([]PunchRecordsCount, 0)
  779. err := punchRecordsDao.Fields("user_id, user_nick_name, punch_type, COUNT(id) as count").
  780. WhereGTE(punchRecordsDao.C.PunchTime, item[0]).WhereLTE(punchRecordsDao.C.PunchTime, item[1]).
  781. Group("user_id, punch_type").Order("user_id ASC, punch_type ASC").Scan(&data)
  782. if err != nil {
  783. return nil, err
  784. }
  785. punchRecordsMonthData = append(punchRecordsMonthData, data)
  786. }
  787. // 409022238
  788. userList, err := service.GetUsersByRoleCode(s.Ctx, []string{"SalesEngineer"}, 100)
  789. if err != nil {
  790. return nil, err
  791. }
  792. // 打卡类型(10居家20客户30经销商40代理商)
  793. var punchTypes = []string{"10", "20", "30", "40"}
  794. var punchTypeNames = []string{"居家", "客户", "经销商", "代理商"}
  795. header, data := make([]g.Map, 0), make([]g.Map, 0)
  796. header = append(header, g.Map{"prop": "userName", "label": "销售工程师"})
  797. header = append(header, g.Map{"prop": "punchType", "label": "打卡方式"})
  798. for k, _ := range weekData {
  799. header = append(header, g.Map{"prop": fmt.Sprintf("W%d", k+1), "label": fmt.Sprintf("第%d周", k+1)})
  800. }
  801. header = append(header, g.Map{"prop": "monthTotal", "label": "月度合计"})
  802. // 打卡类型(10居家20客户30经销商40代理商)
  803. for userName, id := range userList {
  804. for index, key := range punchTypes {
  805. data = append(data, punchRecordsDataConvert(g.Map{
  806. "userName": userName,
  807. "userId": id,
  808. "punchTypeKey": key,
  809. "punchType": punchTypeNames[index],
  810. }, punchRecordsMonthData))
  811. }
  812. }
  813. return g.Map{"header": header, "data": data}, nil
  814. }
  815. func followUpReportDataConvert(data g.Map, followUpMonthData [][]FollowUpCount) g.Map {
  816. var total int
  817. for k, items := range followUpMonthData {
  818. data[fmt.Sprintf("W%d", k+1)] = 0
  819. for _, item := range items {
  820. if item.CreatedBy == data["userId"] && item.FollowType == data["followTypeKey"] {
  821. data[fmt.Sprintf("W%d", k+1)] = item.Count
  822. total += item.Count
  823. break
  824. }
  825. }
  826. }
  827. data["monthTotal"] = total
  828. return data
  829. }
  830. func punchRecordsDataConvert(data g.Map, punchRecordsCMonthData [][]PunchRecordsCount) g.Map {
  831. var total int
  832. for k, items := range punchRecordsCMonthData {
  833. data[fmt.Sprintf("W%d", k+1)] = 0
  834. for _, item := range items {
  835. if item.UserId == data["userId"] && item.PunchType == data["punchTypeKey"] {
  836. data[fmt.Sprintf("W%d", k+1)] = item.Count
  837. total += item.Count
  838. break
  839. }
  840. }
  841. }
  842. data["monthTotal"] = total
  843. return data
  844. }
  845. // GetMonthWeekDay 获取月份下的每周日期
  846. func GetMonthWeekDay(day *gtime.Time) [][]*gtime.Time {
  847. fmt.Println(day)
  848. result := make([][]*gtime.Time, 0)
  849. monthStart, monthEnd := day.StartOfMonth(), day.EndOfMonth()
  850. startWeekS, startWeekE := monthStart.StartOfWeek(), monthStart.EndOfWeek()
  851. endWeekS, endWeekE := monthEnd.StartOfWeek(), monthEnd.EndOfWeek()
  852. // 计算开始
  853. if startWeekS.Before(monthStart) || startWeekS.Equal(monthStart) {
  854. result = append(result, []*gtime.Time{monthStart, startWeekE})
  855. }
  856. // 计算整周
  857. sub := int(endWeekS.Sub(startWeekE).Hours() / 24 / 7)
  858. forDay := startWeekE.AddDate(0, 0, 1)
  859. for i := 1; i <= sub; i++ {
  860. result = append(result, []*gtime.Time{forDay.StartOfDay(), forDay.EndOfWeek()})
  861. forDay = forDay.AddDate(0, 0, 7)
  862. }
  863. // 计算结束
  864. if endWeekE.After(monthEnd) || endWeekE.Equal(monthEnd) {
  865. result = append(result, []*gtime.Time{endWeekS, monthEnd})
  866. }
  867. return result
  868. }