report.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. package home
  2. import (
  3. "context"
  4. contDao "dashoo.cn/micro/app/dao/contract"
  5. platDao "dashoo.cn/micro/app/dao/plat"
  6. projDao "dashoo.cn/micro/app/dao/proj"
  7. "dashoo.cn/micro/app/model/home"
  8. "dashoo.cn/micro/app/model/plat"
  9. "dashoo.cn/micro/app/service"
  10. contractService "dashoo.cn/micro/app/service/contract"
  11. platService "dashoo.cn/micro/app/service/plat"
  12. projSrv "dashoo.cn/micro/app/service/proj"
  13. "dashoo.cn/opms_libary/micro_srv"
  14. "dashoo.cn/opms_libary/myerrors"
  15. "database/sql"
  16. "fmt"
  17. "github.com/gogf/gf/database/gdb"
  18. "github.com/gogf/gf/frame/g"
  19. "github.com/gogf/gf/os/gtime"
  20. "github.com/gogf/gf/util/gconv"
  21. "math"
  22. "time"
  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. for index, target := range targets {
  170. reportData.XData = append(reportData.XData, target["sale_user_name"].String())
  171. reportData.YDataTarget = append(reportData.YDataTarget, target[targetField].Float64())
  172. if realData, ok := realMap[target["sale_user_id"].Int()]; ok {
  173. reportData.YDataReal = append(reportData.YDataReal, realData[realField].Float64())
  174. } else {
  175. reportData.YDataReal = append(reportData.YDataReal, 0)
  176. }
  177. if reportData.YDataTarget[index] == 0 {
  178. reportData.PercentData = append(reportData.PercentData, 0)
  179. } else {
  180. reportData.PercentData = append(reportData.PercentData, reportData.YDataReal[index]*100/reportData.YDataTarget[index])
  181. }
  182. }
  183. return &reportData, nil
  184. }
  185. func getQuarterGoalReportData(ctx context.Context, dataType string, params *map[string]interface{}) (*home.ReportData, error) {
  186. if params == nil {
  187. return nil, fmt.Errorf("请输入年度")
  188. }
  189. p := *params
  190. year := gconv.Int(p["year"])
  191. quarter := gconv.Int(p["quarter"])
  192. if year == 0 {
  193. return nil, fmt.Errorf("请输入年度")
  194. }
  195. srv, err := contractService.NewCtrContractService(ctx)
  196. if err != nil {
  197. return nil, err
  198. }
  199. goal := map[string]float64{}
  200. goaldao := srv.GoalDao.Where("year = ?", year).Where("goal_type = ?", dataType)
  201. if quarter != 0 {
  202. goaldao = goaldao.Where("quarter = ?", quarter)
  203. } else {
  204. goaldao = goaldao.Where("quarter = 1 || quarter = 2 || quarter = 3 || quarter = 4")
  205. }
  206. goalent, err := goaldao.All()
  207. if err != nil {
  208. return nil, err
  209. }
  210. for _, ent := range goalent {
  211. goal[ent.ProductLine] += ent.Amount
  212. }
  213. got := map[string]float64{}
  214. ctrdao := srv.Dao.Where("year(created_time) = ?", year)
  215. if quarter != 0 {
  216. if quarter == 1 {
  217. ctrdao = ctrdao.Where("month(created_time) in (1,2,3)")
  218. }
  219. if quarter == 2 {
  220. ctrdao = ctrdao.Where("month(created_time) in (4,5,6)")
  221. }
  222. if quarter == 3 {
  223. ctrdao = ctrdao.Where("month(created_time) in (7,8,9)")
  224. }
  225. if quarter == 4 {
  226. ctrdao = ctrdao.Where("month(created_time) in (10,11,12)")
  227. }
  228. }
  229. ctrent, err := ctrdao.All()
  230. if err != nil {
  231. return nil, err
  232. }
  233. for _, ent := range ctrent {
  234. if dataType == "10" {
  235. got[ent.ProductLine] += ent.ContractAmount
  236. }
  237. if dataType == "20" {
  238. got[ent.ProductLine] += ent.CollectedAmount
  239. }
  240. }
  241. productLine, err := service.GetDictDataByType(ctx, "sys_product_line")
  242. if err != nil {
  243. return nil, err
  244. }
  245. productLineCode := []string{}
  246. productLineName := []string{}
  247. for k, v := range productLine {
  248. productLineCode = append(productLineCode, k)
  249. productLineName = append(productLineName, v)
  250. }
  251. var reportData home.ReportData
  252. for _, c := range productLineCode {
  253. reportData.XData = append(reportData.XData, productLine[c])
  254. reportData.YDataTarget = append(reportData.YDataTarget, goal[c])
  255. reportData.YDataReal = append(reportData.YDataReal, got[c]/10000)
  256. }
  257. return &reportData, nil
  258. }
  259. // 客户现场打卡频次
  260. func getClockfrequency(ctx context.Context, dataType string, params *map[string]interface{}) (*home.ReportData, error) {
  261. var reportData home.ReportData
  262. realMap := make(map[int]gdb.Record, 0)
  263. dateWhere1 := "" // 查询条件
  264. date := gtime.Now()
  265. nowTime := gtime.Datetime()
  266. if params != nil && (*params)["date"] != nil {
  267. date = gconv.GTime((*params)["date"])
  268. }
  269. if params != nil && (*params)["searchType"] != nil {
  270. searchType := gconv.String((*params)["searchType"])
  271. if searchType == "month" {
  272. dateWhere1 = fmt.Sprintf("plat_punch_records.punch_time LIKE '%v'", date.Format("Y-m")+"-%")
  273. } else if searchType == "week" {
  274. weekday := transferWeekday(date.Weekday())
  275. fmt.Println(weekday)
  276. beforeTime := gtime.NewFromStr(nowTime).AddDate(0, 0, -gconv.Int(weekday)).String()
  277. endTime := gtime.NewFromStr(nowTime).AddDate(0, 0, 7-gconv.Int(weekday)).String()
  278. dateWhere1 = fmt.Sprintf("plat_punch_records.punch_time between '%v' and '%v'", beforeTime, endTime)
  279. }
  280. }
  281. srv, err := platService.NewPunchRecordsService(ctx)
  282. if err != nil {
  283. return nil, err
  284. }
  285. 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()
  286. if err != nil && err != sql.ErrNoRows {
  287. return nil, err
  288. }
  289. // 赋值实际值
  290. for index, target := range platpunchrecords {
  291. reportData.XData = append(reportData.XData, target["user_nick_name"].String())
  292. reportData.YDataTarget = append(reportData.YDataTarget, target["punch_sum"].Float64())
  293. if realData, ok := realMap[target["punch_sum"].Int()]; ok {
  294. reportData.YDataReal = append(reportData.YDataReal, realData["punch_sum"].Float64())
  295. } else {
  296. reportData.YDataReal = append(reportData.YDataReal, 0)
  297. }
  298. if reportData.YDataTarget[index] == 0 {
  299. reportData.PercentData = append(reportData.PercentData, 0)
  300. } else {
  301. reportData.PercentData = append(reportData.PercentData, reportData.YDataReal[index]*100/reportData.YDataTarget[index])
  302. }
  303. }
  304. return &reportData, nil
  305. }
  306. // 销售工程师跟进记录的打卡频次
  307. func getFollowUpRecord(ctx context.Context, dataType string, params *map[string]interface{}) ([]plat.Statistics, error) {
  308. now := time.Now()
  309. date := gconv.Int(gtime.Now().Month())
  310. if params != nil && (*params)["date"] != nil {
  311. date = gconv.Int((*params)["date"])
  312. }
  313. // 获取本月的第一天
  314. firstOfMonth := time.Date(now.Year(), time.Month(date), 1, 0, 0, 0, 0, now.Location())
  315. // 获取本月的最后一天
  316. lastOfMonth := firstOfMonth.AddDate(0, 1, -1)
  317. l, _ := time.LoadLocation("Asia/Shanghai")
  318. startTime, _ := time.ParseInLocation("2006-01-02", firstOfMonth.Format("2006-01-02"), l)
  319. endTime, _ := time.ParseInLocation("2006-01-02", lastOfMonth.Format("2006-01-02"), l)
  320. datas := GroupByWeekDate(startTime, endTime)
  321. var Follows []plat.Followlist
  322. srv, err := platService.NewFollowupService(ctx)
  323. if err != nil {
  324. return nil, err
  325. }
  326. var stats []plat.Statistics
  327. for _, d := range datas {
  328. err = srv.Dao.DB.Model("plat_followup").
  329. 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").
  330. Group("date_format(follow_date,'%v'),follow_type").Scan(&Follows)
  331. if err != nil && err != sql.ErrNoRows {
  332. return nil, err
  333. }
  334. if len(Follows) > 0 {
  335. var stat plat.Statistics
  336. for _, val := range Follows {
  337. if val.FollowType == "10" {
  338. stat.Phone = gconv.Int(val.Num)
  339. } else if val.FollowType == "20" {
  340. stat.Mail = gconv.Int(val.Num)
  341. } else if val.FollowType == "30" {
  342. stat.PayVisit = gconv.Int(val.Num)
  343. }
  344. }
  345. stat.Total = stat.Phone + stat.Mail + stat.PayVisit
  346. stat.Week = d.WeekTh + "周"
  347. stats = append(stats, stat)
  348. }
  349. }
  350. return stats, nil
  351. }
  352. func getQuarterWhere(date *gtime.Time, field string) string {
  353. if date.Month() >= 1 && date.Month() <= 3 {
  354. 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")
  355. } else if date.Month() >= 4 && date.Month() <= 6 {
  356. 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")
  357. } else if date.Month() >= 7 && date.Month() <= 9 {
  358. 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")
  359. } else if date.Month() >= 10 && date.Month() <= 12 {
  360. 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")
  361. }
  362. return ""
  363. }
  364. func getQuarterMonthWhere(date *gtime.Time, field string) string {
  365. if date.Month() >= 1 && date.Month() <= 3 {
  366. return fmt.Sprintf("%v >= %v AND %v < %v", field, 1, field, 4)
  367. } else if date.Month() >= 4 && date.Month() <= 6 {
  368. return fmt.Sprintf("%v >= %v AND %v < %v", field, 4, field, 7)
  369. } else if date.Month() >= 7 && date.Month() <= 9 {
  370. return fmt.Sprintf("%v >= %v AND %v < %v", field, 7, field, 10)
  371. } else if date.Month() >= 10 && date.Month() <= 12 {
  372. return fmt.Sprintf("%v >= %v AND %v <= %v", field, 10, field, 12)
  373. }
  374. return ""
  375. }
  376. func transferWeekday(day time.Weekday) string {
  377. switch day {
  378. case time.Monday:
  379. return "1"
  380. case time.Tuesday:
  381. return "2"
  382. case time.Wednesday:
  383. return "3"
  384. case time.Thursday:
  385. return "4"
  386. case time.Friday:
  387. return "5"
  388. case time.Saturday:
  389. return "6"
  390. case time.Sunday:
  391. return "7"
  392. default:
  393. return ""
  394. }
  395. }
  396. // 判断时间是当年的第几周
  397. func WeekByDate(t time.Time) string {
  398. yearDay := t.YearDay()
  399. yearFirstDay := t.AddDate(0, 0, -yearDay+1)
  400. firstDayInWeek := int(yearFirstDay.Weekday())
  401. //今年第一周有几天
  402. firstWeekDays := 1
  403. if firstDayInWeek != 0 {
  404. firstWeekDays = 7 - firstDayInWeek + 1
  405. }
  406. var week int
  407. Weeks := WeekByDates(t)
  408. if yearDay <= firstWeekDays {
  409. week = 1
  410. } else {
  411. week = (yearDay-firstWeekDays)/7 + 2
  412. }
  413. return fmt.Sprintf("%d", week-gconv.Int(Weeks)+1)
  414. }
  415. func WeekByDates(now time.Time) int {
  416. l, _ := time.LoadLocation("Asia/Shanghai")
  417. // 获取本月的第一天
  418. firstOfMonth := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
  419. endTime, _ := time.ParseInLocation("2006-01-02", firstOfMonth.Format("2006-01-02"), l)
  420. t := endTime
  421. yearDay := t.YearDay()
  422. yearFirstDay := t.AddDate(0, 0, -yearDay+1)
  423. firstDayInWeek := int(yearFirstDay.Weekday())
  424. //今年第一周有几天
  425. firstWeekDays := 1
  426. if firstDayInWeek != 0 {
  427. firstWeekDays = 7 - firstDayInWeek + 1
  428. }
  429. var week int
  430. if yearDay <= firstWeekDays {
  431. week = 1
  432. } else {
  433. week = (yearDay-firstWeekDays)/7 + 2
  434. }
  435. return week
  436. }
  437. // 将开始时间和结束时间分割为周为单位
  438. func GroupByWeekDate(startTime, endTime time.Time) []plat.WeekDate {
  439. weekDate := make([]plat.WeekDate, 0)
  440. diffDuration := endTime.Sub(startTime)
  441. days := int(math.Ceil(float64(diffDuration/(time.Hour*24)))) + 1
  442. currentWeekDate := plat.WeekDate{}
  443. currentWeekDate.WeekTh = WeekByDate(endTime)
  444. currentWeekDate.EndTime = endTime
  445. currentWeekDay := int(endTime.Weekday())
  446. if currentWeekDay == 0 {
  447. currentWeekDay = 7
  448. }
  449. currentWeekDate.StartTime = endTime.AddDate(0, 0, -currentWeekDay+1)
  450. nextWeekEndTime := currentWeekDate.StartTime
  451. weekDate = append(weekDate, currentWeekDate)
  452. for i := 0; i < (days-currentWeekDay)/7; i++ {
  453. weekData := plat.WeekDate{}
  454. weekData.EndTime = nextWeekEndTime
  455. weekData.StartTime = nextWeekEndTime.AddDate(0, 0, -7)
  456. weekData.WeekTh = WeekByDate(weekData.StartTime)
  457. nextWeekEndTime = weekData.StartTime
  458. weekDate = append(weekDate, weekData)
  459. }
  460. if lastDays := (days - currentWeekDay) % 7; lastDays > 0 {
  461. lastData := plat.WeekDate{}
  462. lastData.EndTime = nextWeekEndTime
  463. lastData.StartTime = nextWeekEndTime.AddDate(0, 0, -lastDays)
  464. lastData.WeekTh = WeekByDate(lastData.StartTime)
  465. weekDate = append(weekDate, lastData)
  466. }
  467. return weekDate
  468. }
  469. type BusCount struct {
  470. NboType string `json:"nboType"`
  471. ProductLine string `json:"productLine"`
  472. Count int `json:"count"`
  473. Remark string `json:"remark"`
  474. }
  475. // 报表数据 三大产品线,新增以及转化项目(C转B、B转A、A转签约、C转A、C转签约、B转签约、储备转A/B/C/签约)数量, 按周和月
  476. // params 10:周 20:月
  477. func (s *HomeService) getNewAndConvertBusiness(productLine []string, params *map[string]interface{}) (interface{}, error) {
  478. if params == nil {
  479. return nil, myerrors.TipsError("请求参数传递不正确")
  480. }
  481. searchType, ok := (*params)["searchType"]
  482. if !ok {
  483. return nil, myerrors.TipsError("请求查询类型参数传递错误")
  484. }
  485. currentTime := gtime.Now()
  486. weekStart, weekEnd := currentTime.StartOfWeek(), currentTime.EndOfWeek()
  487. monthStart, monthEnd := currentTime.StartOfMonth(), currentTime.EndOfMonth()
  488. businessDao := projDao.NewProjBusinessDao(s.Tenant)
  489. busDynamicsDao := projDao.NewProjBusinessDynamicsDao(s.Tenant)
  490. contractDao := contDao.NewCtrContractDao(s.Tenant)
  491. // 获取三大产品线新增项目
  492. getAddBusCount := func(searchType string) (addCount []BusCount, err error) {
  493. commonDb := businessDao.DataScope(s.Ctx, "sale_id").Group(businessDao.C.ProductLine).OrderAsc(businessDao.C.ProductLine).
  494. Fields("product_line, count(id) as count")
  495. if searchType == "week" {
  496. err = commonDb.WhereGTE(businessDao.C.FilingTime, weekStart).WhereLTE(businessDao.C.FilingTime, weekEnd).Scan(&addCount)
  497. }
  498. if searchType == "month" {
  499. err = commonDb.WhereGTE(businessDao.C.FilingTime, monthStart).WhereLTE(businessDao.C.FilingTime, monthEnd).Scan(&addCount)
  500. }
  501. return addCount, err
  502. }
  503. addCount, err := getAddBusCount(searchType.(string))
  504. if err != nil {
  505. return nil, err
  506. }
  507. // 获取三大产品线签约项目
  508. getSignBusCount := func(searchType string) (signCount []BusCount, err error) {
  509. commonDb := contractDao.As("contract").DataScope(s.Ctx, "incharge_id").LeftJoin(businessDao.Table, "bus", "bus.id=contract.nbo_id").
  510. Fields("bus.product_line, bus.nbo_type, count(contract.id) as count").
  511. Group("bus.product_line, bus.nbo_type").Order("bus.product_line ASC, bus.nbo_type ASC")
  512. if searchType == "week" {
  513. err = commonDb.WhereGTE("contract."+contractDao.C.CreatedTime, weekStart).WhereLTE("contract."+contractDao.C.CreatedTime, weekEnd).Scan(&signCount)
  514. }
  515. if searchType == "month" {
  516. err = commonDb.WhereGTE("contract."+contractDao.C.CreatedTime, monthStart).WhereLTE("contract."+contractDao.C.CreatedTime, monthEnd).Scan(&signCount)
  517. }
  518. return signCount, err
  519. }
  520. signCount, err := getSignBusCount(searchType.(string))
  521. if err != nil {
  522. return nil, err
  523. }
  524. // 获取三大产品线转化项目(C转B、B转A、A转签约、C转A、C转签约、B转签约、储备转A/B/C/签约)数量
  525. getConvertBusData := func(searchType string) (convertData []BusCount, err error) {
  526. commonDb := busDynamicsDao.As("dy").LeftJoin(businessDao.Table, "bus", "bus.id=dy.bus_id").DataScope(s.Ctx, "sale_id", "bus").
  527. Where("dy."+busDynamicsDao.C.OpnType, projSrv.OpnUpgradeApproval).WhereNot("dy."+busDynamicsDao.C.Remark, "").
  528. Fields("bus.product_line, dy.remark").OrderAsc("bus.product_line")
  529. if searchType == "week" {
  530. err = commonDb.WhereGTE("dy."+busDynamicsDao.C.CreatedTime, weekStart).WhereLTE("dy."+busDynamicsDao.C.CreatedTime, weekEnd).Scan(&convertData)
  531. }
  532. if searchType == "month" {
  533. err = commonDb.WhereGTE("dy."+busDynamicsDao.C.CreatedTime, monthStart).WhereLTE("dy."+busDynamicsDao.C.CreatedTime, monthEnd).Scan(&convertData)
  534. }
  535. return convertData, err
  536. }
  537. convertBusData, err := getConvertBusData(searchType.(string))
  538. if err != nil {
  539. return nil, err
  540. }
  541. // 处理数据
  542. result := make([][]int, len(productLine))
  543. for i, pl := range productLine {
  544. result[i] = make([]int, 8)
  545. for _, item := range addCount {
  546. if item.ProductLine == pl {
  547. result[i][0] = item.Count
  548. }
  549. }
  550. for _, item := range signCount {
  551. if item.ProductLine != pl {
  552. continue
  553. }
  554. switch item.NboType {
  555. case projSrv.StatusA:
  556. result[i][3] += item.Count
  557. case projSrv.StatusB:
  558. result[i][6] += item.Count
  559. case projSrv.StatusC:
  560. result[i][5] += item.Count
  561. case projSrv.StatusReserve:
  562. result[i][7] += item.Count
  563. }
  564. }
  565. for _, item := range convertBusData {
  566. if item.ProductLine != pl {
  567. continue
  568. }
  569. info := gconv.Map(item.Remark)
  570. if info["origNboType"] == projSrv.StatusC && info["nboType"] == projSrv.StatusB {
  571. result[i][1] += 1
  572. }
  573. if info["origNboType"] == projSrv.StatusB && info["nboType"] == projSrv.StatusA {
  574. result[i][2] += 1
  575. }
  576. if info["origNboType"] == projSrv.StatusC && info["nboType"] == projSrv.StatusA {
  577. result[i][4] += 1
  578. }
  579. if info["origNboType"] == projSrv.StatusReserve {
  580. result[i][7] += 1
  581. }
  582. }
  583. }
  584. return result, nil
  585. }
  586. // 报表数据 三大产品线,AB类项目出货金额
  587. func (s *HomeService) getShipmentAmount(productLine, nboType []string) (interface{}, error) {
  588. businessDao := projDao.NewProjBusinessDao(s.Tenant)
  589. data, err := businessDao.Fields("product_line, nbo_type, SUM(est_trans_price) as est_trans_price").
  590. WhereIn("product_line", productLine).WhereIn("nbo_type", nboType).
  591. Group("product_line, nbo_type").Order("product_line ASC, nbo_type ASC").DataScope(s.Ctx, "sale_id").All()
  592. if err != nil {
  593. return nil, err
  594. }
  595. result := make([][]float64, len(productLine))
  596. for i, pl := range productLine {
  597. result[i] = make([]float64, len(nboType))
  598. for j, t := range nboType {
  599. for _, item := range data {
  600. if item.ProductLine == pl && item.NboType == t {
  601. result[i][j] = item.EstTransPrice
  602. }
  603. }
  604. }
  605. }
  606. return arrayReversal(result), nil
  607. }
  608. // 报表数据 三大产品线,当月和累计的签约、回款额
  609. func (s *HomeService) getProductLineSignedAndBackAmount(productLine []string) (interface{}, error) {
  610. currentTime := gtime.Now()
  611. monthStart := currentTime.StartOfMonth()
  612. monthEnd := currentTime.EndOfMonth()
  613. contractDao := contDao.NewCtrContractDao(s.Tenant)
  614. commonDao := contractDao.DataScope(s.Ctx, "incharge_id").WhereIn(contractDao.C.ProductLine, productLine).
  615. Group(contractDao.C.ProductLine).OrderAsc(contractDao.C.ProductLine)
  616. //累计签约合同金额 contract_amount
  617. allContractAmount, err := commonDao.Fields("product_line, SUM(contract_amount) as contract_amount").All()
  618. if err != nil {
  619. return nil, err
  620. }
  621. //累计回款金额 collected_amount
  622. allCollectedAmount, err := commonDao.Fields("product_line, SUM(collected_amount) as collected_amount").All()
  623. if err != nil {
  624. return nil, err
  625. }
  626. //当月签约合同金额(维度:月)
  627. monthContractAmount, err := commonDao.WhereGTE(contractDao.C.ContractStartTime, monthStart).WhereLTE(contractDao.C.ContractStartTime, monthEnd).
  628. Fields("product_line, SUM(contract_amount) as contract_amount").All()
  629. if err != nil {
  630. return nil, err
  631. }
  632. //当月回款金额(维度:月)
  633. monthCollectedAmount, err := commonDao.WhereGTE(contractDao.C.ContractStartTime, monthStart).WhereLTE(contractDao.C.ContractStartTime, monthEnd).
  634. Fields("product_line, SUM(collected_amount) as collected_amount").All()
  635. if err != nil {
  636. return nil, err
  637. }
  638. result := make([][]float64, len(productLine))
  639. for i, pl := range productLine {
  640. result[i] = make([]float64, 4)
  641. for _, item := range monthContractAmount {
  642. if item.ProductLine == pl {
  643. result[i][0] = item.ContractAmount
  644. }
  645. }
  646. for _, item := range allContractAmount {
  647. if item.ProductLine == pl {
  648. result[i][1] = item.ContractAmount
  649. }
  650. }
  651. for _, item := range monthCollectedAmount {
  652. if item.ProductLine == pl {
  653. result[i][2] = item.CollectedAmount
  654. }
  655. }
  656. for _, item := range allCollectedAmount {
  657. if item.ProductLine == pl {
  658. result[i][3] = item.CollectedAmount
  659. }
  660. }
  661. }
  662. return arrayReversal(result), nil
  663. }
  664. // 二维数组反转
  665. func arrayReversal(result [][]float64) [][]float64 {
  666. if len(result) == 0 {
  667. return [][]float64{}
  668. }
  669. data := make([][]float64, len(result[0]))
  670. for k, v := range result {
  671. for m, n := range v {
  672. if k == 0 {
  673. data[m] = make([]float64, len(result))
  674. }
  675. data[m][k] = n
  676. }
  677. }
  678. return data
  679. }
  680. type FollowUpCount struct {
  681. CreatedBy int `json:"createdBy"`
  682. CreatedName string `json:"createdName"`
  683. FollowType string `json:"followType"`
  684. Count int `json:"count"`
  685. }
  686. // QuerySalesEngineerFollowUpNum 查询销售工程师跟进记录频次
  687. func (s *HomeService) QuerySalesEngineerFollowUpNum(day *gtime.Time) (interface{}, error) {
  688. weekData := GetMonthWeekDay(day)
  689. followUpDao := platDao.NewPlatFollowupDao(s.Tenant)
  690. followUpMonthData := make([][]FollowUpCount, 0)
  691. for _, item := range weekData {
  692. data := make([]FollowUpCount, 0)
  693. err := followUpDao.Fields("created_by, created_name, follow_type, COUNT(id) as count").
  694. WhereGTE(followUpDao.C.FollowDate, item[0]).WhereLTE(followUpDao.C.FollowDate, item[1]).
  695. Group("created_by, follow_type").Order("created_by ASC, follow_type ASC").Scan(&data)
  696. if err != nil {
  697. return nil, err
  698. }
  699. followUpMonthData = append(followUpMonthData, data)
  700. }
  701. // 409022238
  702. userList, err := service.GetUsersByDept(s.Ctx, &service.DeptIdReq{DeptId: 409022238, Include: true})
  703. if err != nil {
  704. return nil, err
  705. }
  706. followMethod, err := service.GetDictDataTreeByType(s.Ctx, "plat_follow_method")
  707. if err != nil {
  708. return nil, err
  709. }
  710. header, data := make([]g.Map, 0), make([]g.Map, 0)
  711. header = append(header, g.Map{"prop": "userName", "label": "销售工程师"})
  712. header = append(header, g.Map{"prop": "followType", "label": "跟进方式"})
  713. for k, _ := range weekData {
  714. header = append(header, g.Map{"prop": fmt.Sprintf("W%d", k+1), "label": fmt.Sprintf("第%d周", k+1)})
  715. }
  716. header = append(header, g.Map{"prop": "monthTotal", "label": "月度合计"})
  717. for userName, id := range userList {
  718. for _, key := range followMethod.Keys() {
  719. data = append(data, followUpReportDataConvert(g.Map{
  720. "userName": userName,
  721. "userId": id,
  722. "followTypeKey": key,
  723. "followType": followMethod.Get(key),
  724. }, followUpMonthData))
  725. }
  726. }
  727. return g.Map{"header": header, "data": data}, nil
  728. }
  729. func followUpReportDataConvert(data g.Map, followUpMonthData [][]FollowUpCount) g.Map {
  730. var total int
  731. for k, items := range followUpMonthData {
  732. data[fmt.Sprintf("W%d", k+1)] = 0
  733. for _, item := range items {
  734. if item.CreatedBy == data["userId"] && item.FollowType == data["followTypeKey"] {
  735. data[fmt.Sprintf("W%d", k+1)] = item.Count
  736. total += item.Count
  737. break
  738. }
  739. }
  740. }
  741. data["monthTotal"] = total
  742. return data
  743. }
  744. // GetMonthWeekDay 获取月份下的每周日期
  745. func GetMonthWeekDay(day *gtime.Time) [][]*gtime.Time {
  746. fmt.Println(day)
  747. result := make([][]*gtime.Time, 0)
  748. monthStart, monthEnd := day.StartOfMonth(), day.EndOfMonth()
  749. startWeekS, startWeekE := monthStart.StartOfWeek(), monthStart.EndOfWeek()
  750. endWeekS, endWeekE := monthEnd.StartOfWeek(), monthEnd.EndOfWeek()
  751. // 计算开始
  752. if startWeekS.Before(monthStart) || startWeekS.Equal(monthStart) {
  753. result = append(result, []*gtime.Time{monthStart, startWeekE})
  754. }
  755. // 计算整周
  756. sub := int(endWeekS.Sub(startWeekE).Hours() / 24 / 7)
  757. forDay := startWeekE.AddDate(0, 0, 1)
  758. for i := 1; i <= sub; i++ {
  759. result = append(result, []*gtime.Time{forDay.StartOfDay(), forDay.EndOfWeek()})
  760. forDay = forDay.AddDate(0, 0, 7)
  761. }
  762. // 计算结束
  763. if endWeekE.After(monthEnd) || endWeekE.Equal(monthEnd) {
  764. result = append(result, []*gtime.Time{endWeekS, monthEnd})
  765. }
  766. return result
  767. }