UrsNewUsersChart.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace App\Module\UrsPromotion\AdminControllers\Metrics;
  3. use App\Module\UrsPromotion\Models\UrsUserMapping;
  4. use Carbon\Carbon;
  5. use Dcat\Admin\Widgets\Metrics\Line;
  6. use Illuminate\Http\Request;
  7. /**
  8. * URS新用户折线图
  9. * 显示每日新用户数量趋势
  10. */
  11. class UrsNewUsersChart extends Line
  12. {
  13. /**
  14. * 初始化卡片内容
  15. *
  16. * @return void
  17. */
  18. protected function init()
  19. {
  20. parent::init();
  21. $this->height(300);
  22. $this->chartHeight(180);
  23. $this->title('URS新用户趋势');
  24. $this->dropdown([
  25. '7' => '最近 7 天',
  26. '14' => '最近 14 天',
  27. '28' => '最近 28 天',
  28. '90' => '最近 90 天',
  29. ]);
  30. }
  31. /**
  32. * 处理请求
  33. *
  34. * @param Request $request
  35. *
  36. * @return mixed|void
  37. */
  38. public function handle(Request $request)
  39. {
  40. $days = (int) $request->get('option', 7);
  41. $data = $this->getNewUsersData($days);
  42. // 卡片内容 - 显示总数
  43. $this->withContent($data['total']);
  44. // 图表数据 - 显示每日数量
  45. $this->withChart($data['daily']);
  46. }
  47. /**
  48. * 获取新用户数据
  49. *
  50. * @param int $days 天数
  51. * @return array
  52. */
  53. private function getNewUsersData(int $days): array
  54. {
  55. $endDate = Carbon::today();
  56. $startDate = $endDate->copy()->subDays($days - 1);
  57. // 获取指定时间范围内的新用户数据
  58. $newUsers = UrsUserMapping::where('created_at', '>=', $startDate)
  59. ->where('created_at', '<=', $endDate->endOfDay())
  60. ->where('status', UrsUserMapping::STATUS_VALID)
  61. ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
  62. ->groupBy('date')
  63. ->orderBy('date')
  64. ->get()
  65. ->keyBy('date');
  66. // 构建每日数据数组
  67. $dailyData = [];
  68. $totalCount = 0;
  69. for ($i = 0; $i < $days; $i++) {
  70. $date = $startDate->copy()->addDays($i)->format('Y-m-d');
  71. $count = $newUsers->get($date)->count ?? 0;
  72. $dailyData[] = $count;
  73. $totalCount += $count;
  74. }
  75. return [
  76. 'total' => number_format($totalCount),
  77. 'daily' => $dailyData,
  78. ];
  79. }
  80. /**
  81. * 设置图表数据
  82. *
  83. * @param array $data
  84. * @return $this
  85. */
  86. public function withChart(array $data)
  87. {
  88. return $this->chart([
  89. 'series' => [
  90. [
  91. 'name' => $this->title,
  92. 'data' => $data,
  93. ],
  94. ],
  95. ]);
  96. }
  97. }