NewUsers.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace UCore\DcatAdmin\Metrics\User;
  3. use App\Module\User\Model\User;
  4. use Carbon\Carbon;
  5. use Dcat\Admin\Widgets\Metrics\Line;
  6. use UCore\Helper\Cache;
  7. use Illuminate\Http\Request;
  8. class NewUsers extends Line
  9. {
  10. /**
  11. * 初始化卡片内容
  12. *
  13. * @return void
  14. */
  15. protected function init()
  16. {
  17. parent::init();
  18. $this->height(300);
  19. $this->chartHeight(180);
  20. $this->title('新用户');
  21. $this->dropdown([
  22. '7' => '最近 7 天',
  23. '14' => '最近 14 天',
  24. '28' => '最近 28 天',
  25. '90' => '最近 90 天',
  26. ]);
  27. }
  28. /**
  29. * 处理请求
  30. *
  31. * @param Request $request
  32. *
  33. * @return mixed|void
  34. */
  35. public function handle(Request $request)
  36. {
  37. $data = $this->getData($request->get('option', 7));
  38. // 卡片内容
  39. $this->withContent($data['count']);
  40. // 图表数据
  41. $this->withChart($data['list']);
  42. }
  43. protected function getData($day)
  44. {
  45. return Cache::cacheCall([ __CLASS__, __FUNCTION__, $day ], function ($day) {
  46. $data = [
  47. ];
  48. $data['count'] = User::query()
  49. ->where('created_at','>',Carbon::now()->subDays($day))
  50. ->count();
  51. foreach (range($day,1) as $item){
  52. $sub = $item - 1;
  53. $data['list'][] = User::query()
  54. ->whereBetween('created_at',[
  55. Carbon::now()->subDays($sub)->startOfDay(),
  56. Carbon::now()->subDays($sub)->endOfDay()
  57. ])
  58. ->count();
  59. }
  60. return $data;
  61. }, [ $day ], 30);
  62. }
  63. /**
  64. * 设置图表数据.
  65. *
  66. * @param array $data
  67. *
  68. * @return $this
  69. */
  70. public function withChart(array $data)
  71. {
  72. return $this->chart([
  73. 'series' => [
  74. [
  75. 'name' => $this->title,
  76. 'data' => $data,
  77. ],
  78. ],
  79. ]);
  80. }
  81. /**
  82. * 设置卡片内容.
  83. *
  84. * @param string $content
  85. *
  86. * @return $this
  87. */
  88. public function withContent($content)
  89. {
  90. return $this->content(
  91. <<<HTML
  92. <div class="d-flex justify-content-between align-items-center mt-1" style="margin-bottom: 2px">
  93. <h2 class="ml-1 font-lg-1">{$content}</h2>
  94. <span class="mb-0 mr-1 text-80">{$this->title}</span>
  95. </div>
  96. HTML
  97. );
  98. }
  99. }